diff --git a/.editorconfig b/.editorconfig index 15658bab8d06e..91d15d8df5b2d 100644 --- a/.editorconfig +++ b/.editorconfig @@ -187,4 +187,3 @@ indent_size = 2 end_of_line = lf [*.{cmd,bat}] end_of_line = crlf - diff --git a/eng/CodeAnalysis.src.globalconfig b/eng/CodeAnalysis.src.globalconfig index 2120ec72ecfc3..d369fd9dc7ed3 100644 --- a/eng/CodeAnalysis.src.globalconfig +++ b/eng/CodeAnalysis.src.globalconfig @@ -1485,7 +1485,7 @@ dotnet_diagnostic.IDE0058.severity = silent dotnet_diagnostic.IDE0059.severity = warning # IDE0060: Remove unused parameter -dotnet_diagnostic.IDE0060.severity = silent +dotnet_diagnostic.IDE0060.severity = warning dotnet_code_quality_unused_parameters = non_public # IDE0061: Use expression body for local functions diff --git a/src/coreclr/System.Private.CoreLib/src/Internal/Runtime/InteropServices/InMemoryAssemblyLoader.PlatformNotSupported.cs b/src/coreclr/System.Private.CoreLib/src/Internal/Runtime/InteropServices/InMemoryAssemblyLoader.PlatformNotSupported.cs index 042f256f79f3d..4d944f40a3638 100644 --- a/src/coreclr/System.Private.CoreLib/src/Internal/Runtime/InteropServices/InMemoryAssemblyLoader.PlatformNotSupported.cs +++ b/src/coreclr/System.Private.CoreLib/src/Internal/Runtime/InteropServices/InMemoryAssemblyLoader.PlatformNotSupported.cs @@ -5,6 +5,8 @@ using System.Runtime.InteropServices; using System.Runtime.Loader; +#pragma warning disable IDE0060 + namespace Internal.Runtime.InteropServices { /// diff --git a/src/coreclr/System.Private.CoreLib/src/System/Buffer.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Buffer.CoreCLR.cs index 4131391fd4519..68e4d777aab2f 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Buffer.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Buffer.CoreCLR.cs @@ -38,6 +38,7 @@ internal static void BulkMoveWithWriteBarrier(ref byte destination, ref byte sou _BulkMoveWithWriteBarrier(ref destination, ref source, byteCount); } +#pragma warning disable IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 // Non-inlinable wrapper around the loop for copying large blocks in chunks [MethodImpl(MethodImplOptions.NoInlining)] private static void _BulkMoveWithWriteBarrier(ref byte destination, ref byte source, nuint byteCount) @@ -72,6 +73,7 @@ private static void _BulkMoveWithWriteBarrier(ref byte destination, ref byte sou } __BulkMoveWithWriteBarrier(ref destination, ref source, byteCount); } +#pragma warning restore IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 [MethodImpl(MethodImplOptions.InternalCall)] private static extern void __BulkMoveWithWriteBarrier(ref byte destination, ref byte source, nuint byteCount); diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs index ff95cf2d54bbb..f5650b4e1ff7b 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.CoreCLR.cs @@ -311,6 +311,7 @@ public static string GetTypeInfoName(ITypeInfo typeInfo) return strTypeLibName; } +#pragma warning disable IDE0060 // This method is identical to Type.GetTypeFromCLSID. Since it's interop specific, we expose it // on Marshal for more consistent API surface. internal static Type? GetTypeFromCLSID(Guid clsid, string? server, bool throwOnError) @@ -327,6 +328,7 @@ public static string GetTypeInfoName(ITypeInfo typeInfo) GetTypeFromCLSID(clsid, server, ObjectHandleOnStack.Create(ref type)); return type; } +#pragma warning restore IDE0060 [LibraryImport(RuntimeHelpers.QCall, EntryPoint = "MarshalNative_GetTypeFromCLSID", StringMarshalling = StringMarshalling.Utf16)] private static partial void GetTypeFromCLSID(in Guid clsid, string? server, ObjectHandleOnStack retType); diff --git a/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs index 9d0b1f681b4ae..60416d4dbb724 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs @@ -3774,7 +3774,7 @@ private CheckValueStatus TryChangeType( CorElementType dstElementType = GetUnderlyingType(this); if (dstElementType != srcElementType) { - value = InvokeUtils.ConvertOrWiden(srcType, srcElementType, value, this, dstElementType); + value = InvokeUtils.ConvertOrWiden(srcType, value, this, dstElementType); } } @@ -3929,7 +3929,7 @@ private void CreateInstanceCheckThis() } // fast path?? - instance = CreateInstanceLocal(this, nonPublic: true, wrapExceptions: wrapExceptions); + instance = CreateInstanceLocal(wrapExceptions: wrapExceptions); } else { @@ -3943,7 +3943,7 @@ private void CreateInstanceCheckThis() [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2082:UnrecognizedReflectionPattern", Justification = "Implementation detail of Activator that linker intrinsically recognizes")] - object? CreateInstanceLocal(Type type, bool nonPublic, bool wrapExceptions) + object? CreateInstanceLocal(bool wrapExceptions) { return Activator.CreateInstance(this, nonPublic: true, wrapExceptions: wrapExceptions); } diff --git a/src/coreclr/nativeaot/Common/src/System/Collections/Concurrent/ConcurrentUnifierWKeyed.cs b/src/coreclr/nativeaot/Common/src/System/Collections/Concurrent/ConcurrentUnifierWKeyed.cs index 49938feb8afa0..48708eac12a98 100644 --- a/src/coreclr/nativeaot/Common/src/System/Collections/Concurrent/ConcurrentUnifierWKeyed.cs +++ b/src/coreclr/nativeaot/Common/src/System/Collections/Concurrent/ConcurrentUnifierWKeyed.cs @@ -161,7 +161,7 @@ public V GetOrAdd(K key) return heyIWasHereFirst; if (!_container.HasCapacity) _container.Resize(); // This overwrites the _container field. - _container.Add(key, hashCode, value); + _container.Add(hashCode, value); return value; } } @@ -218,7 +218,7 @@ public bool TryGetValue(K key, int hashCode, out V value) return false; } - public void Add(K key, int hashCode, V value) + public void Add(int hashCode, V value) { Debug.Assert(_owner._lock.IsAcquired); diff --git a/src/coreclr/nativeaot/Runtime.Base/src/System/AttributeUsageAttribute.cs b/src/coreclr/nativeaot/Runtime.Base/src/System/AttributeUsageAttribute.cs index 63e45d4a4753d..a57bb21f5092f 100644 --- a/src/coreclr/nativeaot/Runtime.Base/src/System/AttributeUsageAttribute.cs +++ b/src/coreclr/nativeaot/Runtime.Base/src/System/AttributeUsageAttribute.cs @@ -16,6 +16,7 @@ namespace System [AttributeUsage(AttributeTargets.Class, Inherited = true)] public sealed class AttributeUsageAttribute : Attribute { +#pragma warning disable IDE0060 //Constructors public AttributeUsageAttribute(AttributeTargets validOn) { @@ -24,6 +25,7 @@ public AttributeUsageAttribute(AttributeTargets validOn) public AttributeUsageAttribute(AttributeTargets validOn, bool allowMultiple, bool inherited) { } +#pragma warning restore IDE0060 //Properties. // Allowing the set properties as it allows a more readable syntax in the specifiers (and are commonly used) diff --git a/src/coreclr/nativeaot/Runtime.Base/src/System/Runtime/ExceptionHandling.cs b/src/coreclr/nativeaot/Runtime.Base/src/System/Runtime/ExceptionHandling.cs index 81242191d1aab..4576862fda02e 100644 --- a/src/coreclr/nativeaot/Runtime.Base/src/System/Runtime/ExceptionHandling.cs +++ b/src/coreclr/nativeaot/Runtime.Base/src/System/Runtime/ExceptionHandling.cs @@ -72,12 +72,14 @@ private struct EHEnum private IntPtr _dummy; // For alignment } +#pragma warning disable IDE0060 // This is a fail-fast function used by the runtime as a last resort that will terminate the process with // as little effort as possible. No guarantee is made about the semantics of this fail-fast. internal static void FallbackFailFast(RhFailFastReason reason, object unhandledException) { InternalCalls.RhpFallbackFailFast(); } +#pragma warning restore IDE0060 // Given an address pointing somewhere into a managed module, get the classlib-defined fail-fast // function and invoke it. Any failure to find and invoke the function, or if it returns, results in @@ -921,6 +923,7 @@ private static void InvokeSecondPass(ref ExInfo exInfo, uint idxStart, uint idxL } } +#pragma warning disable IDE0060 [UnmanagedCallersOnly(EntryPoint = "RhpFailFastForPInvokeExceptionPreemp", CallConvs = new Type[] { typeof(CallConvCdecl) })] public static void RhpFailFastForPInvokeExceptionPreemp(IntPtr PInvokeCallsiteReturnAddr, void* pExceptionRecord, void* pContextRecord) { @@ -931,5 +934,7 @@ public static void RhpFailFastForPInvokeExceptionCoop(IntPtr classlibBreadcrumb, { FailFastViaClasslib(RhFailFastReason.UnhandledExceptionFromPInvoke, null, classlibBreadcrumb); } +#pragma warning restore IDE0060 + } // static class EH } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/ComAwareWeakReference.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/ComAwareWeakReference.NativeAot.cs index d97196a7e31ca..42916dad1ed5b 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/ComAwareWeakReference.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/ComAwareWeakReference.NativeAot.cs @@ -4,6 +4,9 @@ using System; #if FEATURE_COMINTEROP || FEATURE_COMWRAPPERS + +#pragma warning disable IDE0060 + namespace System { internal sealed partial class ComAwareWeakReference diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Delegate.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Delegate.cs index f2c9c293bcfb4..61496ddf2c5ad 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Delegate.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Delegate.cs @@ -15,7 +15,6 @@ namespace System { - [DebuggerDisplay("Target method(s) = {GetTargetMethodsDescriptionForDebugger()}")] public abstract partial class Delegate : ICloneable, ISerializable { // V1 API: Create closed instance delegates. Method name matching is case sensitive. @@ -218,7 +217,7 @@ private void InitializeClosedStaticThunk(object firstParameter, IntPtr functionP } // This function is known to the compiler backend. - private void InitializeOpenStaticThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk) + private void InitializeOpenStaticThunk(object _ /*firstParameter*/, IntPtr functionPointer, IntPtr functionPointerThunk) { // This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself. m_firstParameter = this; @@ -422,48 +421,5 @@ internal static Delegate CreateDelegate(EETypePtr delegateEEType, IntPtr ldftnRe } return del; } - - private string GetTargetMethodsDescriptionForDebugger() - { - if (m_functionPointer == GetThunk(MulticastThunk)) - { - // Multi-cast delegates return the Target of the last delegate in the list - Delegate[] invocationList = (Delegate[])m_helperObject; - int invocationCount = (int)m_extraFunctionPointerOrData; - StringBuilder builder = new StringBuilder(); - for (int c = 0; c < invocationCount; c++) - { - if (c != 0) - builder.Append(", "); - - builder.Append(invocationList[c].GetTargetMethodsDescriptionForDebugger()); - } - - return builder.ToString(); - } - else - { - RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate; - IntPtr functionPointer = GetFunctionPointer(out typeOfFirstParameterIfInstanceDelegate, out bool _, out bool _); - if (!FunctionPointerOps.IsGenericMethodPointer(functionPointer)) - { - return DebuggerFunctionPointerFormattingHook(functionPointer, typeOfFirstParameterIfInstanceDelegate); - } - else - { - unsafe - { - GenericMethodDescriptor* pointerDef = FunctionPointerOps.ConvertToGenericDescriptor(functionPointer); - return DebuggerFunctionPointerFormattingHook(pointerDef->InstantiationArgument, typeOfFirstParameterIfInstanceDelegate); - } - } - } - } - - private static string DebuggerFunctionPointerFormattingHook(IntPtr functionPointer, RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate) - { - // This method will be hooked by the debugger and the debugger will cause it to return a description for the function pointer - throw new NotSupportedException(); - } } } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Enum.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Enum.NativeAot.cs index 7a4928b1cd03f..99787cad583fc 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Enum.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Enum.NativeAot.cs @@ -16,6 +16,7 @@ namespace System { public abstract partial class Enum : ValueType, IComparable, IFormattable, IConvertible { +#pragma warning disable IDE0060 internal static EnumInfo GetEnumInfo(Type enumType, bool getNames = true) { Debug.Assert(enumType != null); @@ -24,6 +25,7 @@ internal static EnumInfo GetEnumInfo(Type enumType, bool getNames = true) return ReflectionAugments.ReflectionCoreCallbacks.GetEnumInfo(enumType); } +#pragma warning restore private static object InternalBoxEnum(Type enumType, long value) { diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Environment.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Environment.NativeAot.cs index c5648c28885a3..81bb1f8231af6 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Environment.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Environment.NativeAot.cs @@ -43,7 +43,7 @@ public static void FailFast(string message) => public static void FailFast(string message, Exception exception) => RuntimeExceptionHelpers.FailFast(message, exception); - internal static void FailFast(string message, Exception exception, string errorSource) + internal static void FailFast(string message, Exception exception, string _ /*errorSource*/) { // TODO: errorSource originates from CoreCLR (See: https://github.com/dotnet/coreclr/pull/15895) // For now, we ignore errorSource but we should distinguish the way FailFast prints exception message using errorSource diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/IO/FileLoadException.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/IO/FileLoadException.NativeAot.cs index 4d90a89afafcc..9208efa9b9799 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/IO/FileLoadException.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/IO/FileLoadException.NativeAot.cs @@ -5,7 +5,7 @@ namespace System.IO { public partial class FileLoadException { - internal static string FormatFileLoadExceptionMessage(string? fileName, int hResult) + internal static string FormatFileLoadExceptionMessage(string? fileName, int _ /*hResult*/) { return fileName == null ? SR.IO_FileLoad : SR.Format(SR.IO_FileLoad_FileName, fileName); } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/InvokeUtils.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/InvokeUtils.cs index e4921170c2cd2..9756ce8c6b95e 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/InvokeUtils.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/InvokeUtils.cs @@ -244,7 +244,7 @@ private static Exception CreateChangeTypeException(EETypePtr srcEEType, EETypePt case CheckArgumentSemantics.SetFieldDirect: return CreateChangeTypeArgumentException(srcEEType, dstEEType); case CheckArgumentSemantics.ArraySet: - return CreateChangeTypeInvalidCastException(srcEEType, dstEEType); + return CreateChangeTypeInvalidCastException(); default: Debug.Fail("Unexpected CheckArgumentSemantics value: " + semantics); throw new InvalidOperationException(); @@ -259,7 +259,7 @@ internal static ArgumentException CreateChangeTypeArgumentException(EETypePtr sr return new ArgumentException(SR.Format(SR.Arg_ObjObjEx, Type.GetTypeFromHandle(new RuntimeTypeHandle(srcEEType)), destinationTypeName)); } - private static InvalidCastException CreateChangeTypeInvalidCastException(EETypePtr srcEEType, EETypePtr dstEEType) + private static InvalidCastException CreateChangeTypeInvalidCastException() { return new InvalidCastException(SR.InvalidCast_StoreArrayElement); } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/General/TypeUnifier.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/General/TypeUnifier.cs index 1a42512ea4afe..c118a02ec481b 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/General/TypeUnifier.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Reflection/Runtime/General/TypeUnifier.cs @@ -253,7 +253,7 @@ private sealed class ArrayTypeTable : ConcurrentUnifierWKeyed /// Get the currently registered managed object or creates a new managed object and registers it. /// @@ -541,6 +542,7 @@ private unsafe bool TryGetOrCreateObjectForComInstanceInternal( return true; } +#pragma warning restore IDE0060 private void RemoveRCWFromCache(IntPtr comPointer) { diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.NativeAot.cs index be773f9cd00e1..ed85c17e1dc5f 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/Marshal.NativeAot.cs @@ -197,10 +197,8 @@ public static unsafe void StructureToPtr(object structure, IntPtr ptr, bool fDel } } - private static void PrelinkCore(MethodInfo m) - { - // This method is effectively a no-op for NativeAOT, everything pre-generated. - } + // This method is effectively a no-op for NativeAOT, everything pre-generated. + static partial void PrelinkCore(MethodInfo m); internal static Delegate GetDelegateForFunctionPointerInternal(IntPtr ptr, Type t) { diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeLibrary.NativeAot.Unix.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeLibrary.NativeAot.Unix.cs index 74c1804da42ef..695b904825ea3 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeLibrary.NativeAot.Unix.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/NativeLibrary.NativeAot.Unix.cs @@ -9,7 +9,7 @@ public static partial class NativeLibrary { private const int LoadWithAlteredSearchPathFlag = 0; - private static IntPtr LoadLibraryHelper(string libraryName, int flags, ref LoadLibErrorTracker errorTracker) + private static IntPtr LoadLibraryHelper(string libraryName, int _ /*flags*/, ref LoadLibErrorTracker errorTracker) { // do the Dos/Unix conversion libraryName = libraryName.Replace('\\', '/'); diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/JitInfo.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/JitInfo.NativeAot.cs index 3d838c77b86d4..d5206c3c55841 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/JitInfo.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/JitInfo.NativeAot.cs @@ -9,6 +9,6 @@ public static partial class JitInfo public static long GetCompiledMethodCount(bool currentThread = false) => 0; - private static long GetCompilationTimeInTicks(bool currentThread = false) => 0; + private static long GetCompilationTimeInTicks(bool _ /*currentThread*/ = false) => 0; } } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.NativeAot.cs index d2477f75b10f9..1a854be55a5ed 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.NativeAot.cs @@ -18,6 +18,7 @@ public Assembly LoadFromAssemblyName(AssemblyName assemblyName) return Assembly.Load(assemblyName); } +#pragma warning disable IDE0060 private static IntPtr InitializeAssemblyLoadContext(IntPtr ptrAssemblyLoadContext, bool fRepresentsTPALoadContext, bool isCollectible) { return IntPtr.Zero; @@ -46,6 +47,7 @@ private static Assembly InternalLoadFromPath(string? assemblyPath, string? nativ // so it won't actually work properly when multiple assemblies with the same identity get loaded. return ReflectionAugments.ReflectionCoreCallbacks.Load(assemblyPath); } +#pragma warning restore IDE0060 #pragma warning disable CA1822 internal Assembly InternalLoad(ReadOnlySpan arrAssembly, ReadOnlySpan arrSymbols) diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.NativeAot.Unix.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.NativeAot.Unix.cs index 55d016d3ce418..2113b39fc354a 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.NativeAot.Unix.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.NativeAot.Unix.cs @@ -28,7 +28,7 @@ private void PlatformSpecificInitializeExistingThread() _stopped = new ManualResetEvent(false); } -#pragma warning disable CA1822 +#pragma warning disable CA1822, IDE0060 private ThreadPriority GetPriorityLive() { return ThreadPriority.Normal; @@ -38,7 +38,7 @@ private bool SetPriorityLive(ThreadPriority priority) { return true; } -#pragma warning restore CA1822 +#pragma warning restore CA1822, IDE0060 [UnmanagedCallersOnly] private static void OnThreadExit() diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/ThreadPool.NativeAot.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/ThreadPool.NativeAot.cs index 67b66bd0e1848..2fe7d1dd2c5d6 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/ThreadPool.NativeAot.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/ThreadPool.NativeAot.cs @@ -10,8 +10,6 @@ ** =============================================================================*/ -#pragma warning disable 0420 - using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.Versioning; @@ -20,6 +18,7 @@ namespace System.Threading { public static partial class ThreadPool { + [Conditional("unnecessary")] internal static void ReportThreadStatus(bool isWorking) { } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/ThreadPool.Windows.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/ThreadPool.Windows.cs index 150dcdd92523e..97217e7c615ef 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/ThreadPool.Windows.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/ThreadPool.Windows.cs @@ -357,7 +357,7 @@ public static void GetAvailableThreads(out int workerThreads, out int completion internal static void NotifyWorkItemProgress() => IncrementCompletedWorkItemCount(); [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static bool NotifyWorkItemComplete(object? threadLocalCompletionCountObject, int currentTimeMs) + internal static bool NotifyWorkItemComplete(object? threadLocalCompletionCountObject, int _ /*currentTimeMs*/) { ThreadInt64PersistentCounter.Increment(threadLocalCompletionCountObject); return true; diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/ValueType.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/ValueType.cs index 1b8333324d439..f51c4b333991e 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/ValueType.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/ValueType.cs @@ -109,7 +109,7 @@ private int GetHashCodeImpl() if (numFields == UseFastHelper) return FastGetValueTypeHashCodeHelper(this.GetEETypePtr(), ref this.GetRawData()); - return RegularGetValueTypeHashCode(this.GetEETypePtr(), ref this.GetRawData(), numFields); + return RegularGetValueTypeHashCode(ref this.GetRawData(), numFields); } private static int FastGetValueTypeHashCodeHelper(EETypePtr type, ref byte data) @@ -128,7 +128,7 @@ private static int FastGetValueTypeHashCodeHelper(EETypePtr type, ref byte data) return hashCode; } - private int RegularGetValueTypeHashCode(EETypePtr type, ref byte data, int numFields) + private int RegularGetValueTypeHashCode(ref byte data, int numFields) { int hashCode = 0; diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/GenericDictionaryCell.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/GenericDictionaryCell.cs index 181f525c0d078..6fc6d88706ac6 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/GenericDictionaryCell.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/GenericDictionaryCell.cs @@ -719,7 +719,7 @@ internal override unsafe void Prepare(TypeBuilder builder) case TypeLoaderEnvironment.MethodAddressType.Canonical: { bool methodRequestedIsCanonical = Method.IsCanonicalMethod(CanonicalFormKind.Specific); - bool requestedMethodNeedsDictionaryWhenCalledAsCanonical = NeedsDictionaryParameterToCallCanonicalVersion(Method); + bool requestedMethodNeedsDictionaryWhenCalledAsCanonical = NeedsDictionaryParameterToCallCanonicalVersion(); if (!requestedMethodNeedsDictionaryWhenCalledAsCanonical || methodRequestedIsCanonical) { @@ -731,7 +731,7 @@ internal override unsafe void Prepare(TypeBuilder builder) case TypeLoaderEnvironment.MethodAddressType.UniversalCanonical: { if (Method.IsCanonicalMethod(CanonicalFormKind.Universal) && - !NeedsDictionaryParameterToCallCanonicalVersion(Method) && + !NeedsDictionaryParameterToCallCanonicalVersion() && !UniversalGenericParameterLayout.MethodSignatureHasVarsNeedingCallingConventionConverter( Method.GetTypicalMethodDefinition().Signature)) { @@ -792,7 +792,7 @@ internal override unsafe void Prepare(TypeBuilder builder) Debug.Assert((_exactFunctionPointer != IntPtr.Zero) || (Method.FunctionPointer != IntPtr.Zero) || (Method.UsgFunctionPointer != IntPtr.Zero)); } - private bool NeedsDictionaryParameterToCallCanonicalVersion(MethodDesc method) + private bool NeedsDictionaryParameterToCallCanonicalVersion() { if (Method.HasInstantiation) return true; diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/LowLevelStringConverter.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/LowLevelStringConverter.cs index 7b90a25fae3e5..1bd1f93cce584 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/LowLevelStringConverter.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/LowLevelStringConverter.cs @@ -41,12 +41,12 @@ public static string ToStringInvariant(this ulong arg) return arg.LowLevelToString(); } - public static string ToStringInvariant(this float arg) + public static string ToStringInvariant(this float _) { return "FLOAT"; } - public static string ToStringInvariant(this double arg) + public static string ToStringInvariant(this double _) { return "DOUBLE"; } diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs index 97477b19b4c55..de0f97964cbce 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilder.cs @@ -223,7 +223,7 @@ public void PrepareMethod(MethodDesc method) ParseNativeLayoutInfo(genericMethod); } - private void InsertIntoNeedsTypeHandleList(TypeBuilderState state, TypeDesc type) + private void InsertIntoNeedsTypeHandleList(TypeDesc type) { if ((type is DefType) || (type is ArrayType) || (type is PointerType) || (type is ByRefType)) { @@ -259,7 +259,7 @@ internal void PrepareType(TypeDesc type) if (!hasTypeHandle) { - InsertIntoNeedsTypeHandleList(state, type); + InsertIntoNeedsTypeHandleList(type); } bool noExtraPreparation = false; // Set this to true for types which don't need other types to be prepared. I.e GenericTypeDefinitions @@ -1135,7 +1135,7 @@ public static DefType GetBaseTypeThatIsCorrectForMDArrays(TypeDesc type) return type.BaseType; } - private void FinishInterfaces(TypeDesc type, TypeBuilderState state) + private void FinishInterfaces(TypeBuilderState state) { DefType[] interfaces = state.RuntimeInterfaces; if (interfaces != null) @@ -1343,7 +1343,7 @@ private void FinishRuntimeType(TypeDesc type) FinishBaseTypeAndDictionaries(type, state); - FinishInterfaces(type, state); + FinishInterfaces(state); FinishClassConstructor(type, state); @@ -1362,7 +1362,7 @@ private void FinishRuntimeType(TypeDesc type) state.HalfBakedRuntimeTypeHandle.SetComponentSize(state.ComponentSize.Value); - FinishInterfaces(type, state); + FinishInterfaces(state); if (typeAsSzArrayType.IsSzArray && !typeAsSzArrayType.ElementType.IsPointer) { diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.FieldAccess.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.FieldAccess.cs index 00afbd995bd87..fac51333c6fd1 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.FieldAccess.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.FieldAccess.cs @@ -74,7 +74,6 @@ public static bool TryGetFieldAccessMetadata( fieldAccessMetadata = default(FieldAccessMetadata); if (TryGetFieldAccessMetadataFromFieldAccessMap( - metadataReader, runtimeTypeHandle, fieldHandle, CanonicalFormKind.Specific, @@ -84,7 +83,6 @@ public static bool TryGetFieldAccessMetadata( } if (TryGetFieldAccessMetadataFromFieldAccessMap( - metadataReader, runtimeTypeHandle, fieldHandle, CanonicalFormKind.Universal, @@ -110,14 +108,12 @@ public static bool TryGetFieldAccessMetadata( /// /// Try to look up field access info for given canon in metadata blobs for all available modules. /// - /// Metadata reader for the declaring type /// Declaring type for the method /// Field handle /// Canonical form to use /// Output - metadata information for field accessor construction /// true when found, false otherwise private static unsafe bool TryGetFieldAccessMetadataFromFieldAccessMap( - MetadataReader metadataReader, RuntimeTypeHandle declaringTypeHandle, FieldHandle fieldHandle, CanonicalFormKind canonFormKind, diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.SignatureParsing.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.SignatureParsing.cs index 4d13dbf569eb1..98739c47b2945 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.SignatureParsing.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.SignatureParsing.cs @@ -277,8 +277,7 @@ internal bool GetCallingConverterDataFromMethodSignature_NativeLayout(TypeSystem methodInstantiation, out hasThis, out parameters, - out parametersWithGenericDependentLayout, - null); + out parametersWithGenericDependentLayout); } internal bool GetCallingConverterDataFromMethodSignature_NativeLayout_Common( @@ -288,8 +287,7 @@ internal bool GetCallingConverterDataFromMethodSignature_NativeLayout_Common( Instantiation methodInstantiation, out bool hasThis, out TypeDesc[] parameters, - out bool[] parametersWithGenericDependentLayout, - NativeReader nativeReader) + out bool[] parametersWithGenericDependentLayout) { NativeLayoutInfoLoadContext nativeLayoutContext = new NativeLayoutInfoLoadContext(); diff --git a/src/coreclr/nativeaot/Test.CoreLib/src/Directory.Build.props b/src/coreclr/nativeaot/Test.CoreLib/src/Directory.Build.props new file mode 100644 index 0000000000000..8cd614967f4a7 --- /dev/null +++ b/src/coreclr/nativeaot/Test.CoreLib/src/Directory.Build.props @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs index 376de7408b6bb..62beee1b926e4 100644 --- a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs +++ b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs @@ -30,6 +30,8 @@ using ILCompiler.DependencyAnalysis.ReadyToRun; #endif +#pragma warning disable IDE0060 + namespace Internal.JitInterface { internal enum CompilationResult diff --git a/src/coreclr/tools/Common/TypeSystem/Common/CastingHelper.cs b/src/coreclr/tools/Common/TypeSystem/Common/CastingHelper.cs index d0f32078e97df..85f3799dfa180 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/CastingHelper.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/CastingHelper.cs @@ -363,7 +363,7 @@ private static bool CanCastToInterface(this TypeDesc thisType, TypeDesc otherTyp { if (!otherType.HasVariance) { - return thisType.CanCastToNonVariantInterface(otherType, protect); + return thisType.CanCastToNonVariantInterface(otherType); } else { @@ -384,7 +384,7 @@ private static bool CanCastToInterface(this TypeDesc thisType, TypeDesc otherTyp return false; } - private static bool CanCastToNonVariantInterface(this TypeDesc thisType, TypeDesc otherType, StackOverflowProtect protect) + private static bool CanCastToNonVariantInterface(this TypeDesc thisType, TypeDesc otherType) { if (otherType == thisType) { diff --git a/src/coreclr/tools/Common/TypeSystem/Common/ExplicitLayoutValidator.cs b/src/coreclr/tools/Common/TypeSystem/Common/ExplicitLayoutValidator.cs index cb4755c5af306..8e2eda382f468 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/ExplicitLayoutValidator.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/ExplicitLayoutValidator.cs @@ -58,7 +58,7 @@ public int CompareTo(FieldLayoutInterval other) private readonly MetadataType _typeBeingValidated; - private ExplicitLayoutValidator(MetadataType type, int typeSizeInBytes) + private ExplicitLayoutValidator(MetadataType type) { _typeBeingValidated = type; _pointerSize = type.Context.Target.PointerSize; @@ -67,8 +67,7 @@ private ExplicitLayoutValidator(MetadataType type, int typeSizeInBytes) public static void Validate(MetadataType type, ComputedInstanceFieldLayout layout) { - int typeSizeInBytes = layout.ByteCountUnaligned.AsInt; - ExplicitLayoutValidator validator = new ExplicitLayoutValidator(type, typeSizeInBytes); + ExplicitLayoutValidator validator = new ExplicitLayoutValidator(type); foreach (FieldAndOffset fieldAndOffset in layout.Offsets) { diff --git a/src/coreclr/tools/Common/TypeSystem/Common/MetadataFieldLayoutAlgorithm.cs b/src/coreclr/tools/Common/TypeSystem/Common/MetadataFieldLayoutAlgorithm.cs index 62d40846951fb..a2d2eaccdae46 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/MetadataFieldLayoutAlgorithm.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/MetadataFieldLayoutAlgorithm.cs @@ -375,7 +375,7 @@ protected ComputedInstanceFieldLayout ComputeExplicitFieldLayout(MetadataType ty return computedLayout; } - private static LayoutInt AlignUpInstanceFieldOffset(TypeDesc typeWithField, LayoutInt cumulativeInstanceFieldPos, LayoutInt alignment, TargetDetails target) + private static LayoutInt AlignUpInstanceFieldOffset(LayoutInt cumulativeInstanceFieldPos, LayoutInt alignment, TargetDetails target) { return LayoutInt.AlignUp(cumulativeInstanceFieldPos, alignment, target); } @@ -414,7 +414,7 @@ protected ComputedInstanceFieldLayout ComputeSequentialFieldLayout(MetadataType largestAlignmentRequirement = LayoutInt.Max(fieldSizeAndAlignment.Alignment, largestAlignmentRequirement); - cumulativeInstanceFieldPos = AlignUpInstanceFieldOffset(type, cumulativeInstanceFieldPos, fieldSizeAndAlignment.Alignment, type.Context.Target); + cumulativeInstanceFieldPos = AlignUpInstanceFieldOffset(cumulativeInstanceFieldPos, fieldSizeAndAlignment.Alignment, type.Context.Target); offsets[fieldOrdinal] = new FieldAndOffset(field, cumulativeInstanceFieldPos + offsetBias); cumulativeInstanceFieldPos = checked(cumulativeInstanceFieldPos + fieldSizeAndAlignment.Size); @@ -702,7 +702,7 @@ protected ComputedInstanceFieldLayout ComputeAutoFieldLayout(MetadataType type, if (!fieldLayoutAbiStable) layoutAbiStable = false; - cumulativeInstanceFieldPos = AlignUpInstanceFieldOffset(type, cumulativeInstanceFieldPos, fieldSizeAndAlignment.Alignment, context.Target); + cumulativeInstanceFieldPos = AlignUpInstanceFieldOffset(cumulativeInstanceFieldPos, fieldSizeAndAlignment.Alignment, context.Target); offsets[fieldOrdinal] = new FieldAndOffset(instanceValueClassFieldsArr[i], cumulativeInstanceFieldPos + offsetBias); cumulativeInstanceFieldPos = checked(cumulativeInstanceFieldPos + fieldSizeAndAlignment.Size); @@ -765,7 +765,7 @@ private static void PlaceInstanceField(FieldDesc field, bool hasLayout, int pack { var fieldSizeAndAlignment = ComputeFieldSizeAndAlignment(field.FieldType, hasLayout, packingSize, out bool _, out bool _, out bool _); - instanceFieldPos = AlignUpInstanceFieldOffset(field.OwningType, instanceFieldPos, fieldSizeAndAlignment.Alignment, field.Context.Target); + instanceFieldPos = AlignUpInstanceFieldOffset(instanceFieldPos, fieldSizeAndAlignment.Alignment, field.Context.Target); offsets[fieldOrdinal] = new FieldAndOffset(field, instanceFieldPos + offsetBias); instanceFieldPos = checked(instanceFieldPos + fieldSizeAndAlignment.Size); diff --git a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeILEmitter.cs b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeILEmitter.cs index 42c25c1eee965..57f724815fb8a 100644 --- a/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeILEmitter.cs +++ b/src/coreclr/tools/Common/TypeSystem/IL/Stubs/PInvokeILEmitter.cs @@ -134,7 +134,6 @@ private static Marshaller[] InitializeMarshallers(MethodDesc targetMethod, Inter { marshallers[i] = Marshaller.CreateDisabledMarshaller( parameterType, - parameterIndex, MarshallerType.Argument, direction, marshallers, diff --git a/src/coreclr/tools/Common/TypeSystem/Interop/IL/Marshaller.cs b/src/coreclr/tools/Common/TypeSystem/Interop/IL/Marshaller.cs index a7d62d1c422f2..7f67f92303014 100644 --- a/src/coreclr/tools/Common/TypeSystem/Interop/IL/Marshaller.cs +++ b/src/coreclr/tools/Common/TypeSystem/Interop/IL/Marshaller.cs @@ -336,7 +336,6 @@ public static Marshaller CreateMarshaller(TypeDesc parameterType, /// type of the parameter to marshal /// The created Marshaller public static Marshaller CreateDisabledMarshaller(TypeDesc parameterType, - int? parameterIndex, MarshallerType marshallerType, MarshalDirection direction, Marshaller[] marshallers, diff --git a/src/coreclr/tools/Common/TypeSystem/MetadataEmitter/TypeSystemMetadataEmitter.cs b/src/coreclr/tools/Common/TypeSystem/MetadataEmitter/TypeSystemMetadataEmitter.cs index 8499fa23d8046..198f0d645f819 100644 --- a/src/coreclr/tools/Common/TypeSystem/MetadataEmitter/TypeSystemMetadataEmitter.cs +++ b/src/coreclr/tools/Common/TypeSystem/MetadataEmitter/TypeSystemMetadataEmitter.cs @@ -28,7 +28,7 @@ internal class TypeSystemMetadataEmitter private BlobHandle _noArgsVoidReturnStaticMethodSigHandle; protected TypeSystemContext _typeSystemContext; - public TypeSystemMetadataEmitter(AssemblyName assemblyName, TypeSystemContext context, AssemblyFlags flags = default(AssemblyFlags), byte[] publicKeyArray = null, AssemblyHashAlgorithm hashAlgorithm = AssemblyHashAlgorithm.None) + public TypeSystemMetadataEmitter(AssemblyName assemblyName, TypeSystemContext context, AssemblyFlags flags = default(AssemblyFlags), byte[] publicKeyArray = null) { _typeSystemContext = context; _metadataBuilder = new MetadataBuilder(); diff --git a/src/coreclr/tools/ILVerification/ILImporter.Verify.cs b/src/coreclr/tools/ILVerification/ILImporter.Verify.cs index aefee9b9f9f73..675d420febb1a 100644 --- a/src/coreclr/tools/ILVerification/ILImporter.Verify.cs +++ b/src/coreclr/tools/ILVerification/ILImporter.Verify.cs @@ -9,6 +9,8 @@ using ILVerify; +#pragma warning disable IDE0060 + namespace Internal.IL { class VerificationException : Exception diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/FlowAnnotations.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/FlowAnnotations.cs index eaccfc76e196e..a203fa14ead6d 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/FlowAnnotations.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/FlowAnnotations.cs @@ -700,9 +700,9 @@ internal void ValidateMethodAnnotationsAreSame(MethodDesc method, MethodDesc bas if (methodAnnotations.ParameterAnnotations != null || baseMethodAnnotations.ParameterAnnotations != null) { if (methodAnnotations.ParameterAnnotations == null) - ValidateMethodParametersHaveNoAnnotations(baseMethodAnnotations.ParameterAnnotations!, method, baseMethod, method); + ValidateMethodParametersHaveNoAnnotations(baseMethodAnnotations.ParameterAnnotations!, baseMethod, method); else if (baseMethodAnnotations.ParameterAnnotations == null) - ValidateMethodParametersHaveNoAnnotations(methodAnnotations.ParameterAnnotations, method, baseMethod, method); + ValidateMethodParametersHaveNoAnnotations(methodAnnotations.ParameterAnnotations, baseMethod, method); else { if (methodAnnotations.ParameterAnnotations.Length != baseMethodAnnotations.ParameterAnnotations.Length) @@ -744,7 +744,7 @@ internal void ValidateMethodAnnotationsAreSame(MethodDesc method, MethodDesc bas } } - private void ValidateMethodParametersHaveNoAnnotations(DynamicallyAccessedMemberTypes[] parameterAnnotations, MethodDesc method, MethodDesc baseMethod, MethodDesc origin) + private void ValidateMethodParametersHaveNoAnnotations(DynamicallyAccessedMemberTypes[] parameterAnnotations, MethodDesc baseMethod, MethodDesc origin) { for (int parameterIndex = 0; parameterIndex < parameterAnnotations.Length; parameterIndex++) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HandleCallAction.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HandleCallAction.cs index 4fdb6c2f8b9f3..adc36464def26 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HandleCallAction.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/HandleCallAction.cs @@ -75,6 +75,7 @@ private partial bool TryGetBaseType(TypeProxy type, out TypeProxy? baseType) return false; } +#pragma warning disable IDE0060 private partial bool TryResolveTypeNameForCreateInstanceAndMark(in MethodProxy calledMethod, string assemblyName, string typeName, out TypeProxy resolvedType) { // TODO: niche APIs that we probably shouldn't even have added @@ -84,6 +85,7 @@ private partial bool TryResolveTypeNameForCreateInstanceAndMark(in MethodProxy c resolvedType = default; return false; } +#pragma warning restore IDE0060 private partial void MarkStaticConstructor(TypeProxy type) => _reflectionMarker.MarkStaticConstructor(_diagnosticContext.Origin, type.Type); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodBodyScanner.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodBodyScanner.cs index 0fa9c843faf71..feec94f6f3d72 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodBodyScanner.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/MethodBodyScanner.cs @@ -514,7 +514,7 @@ protected virtual void Scan(MethodIL methodBody, ref InterproceduralState interp case ILOpcode.ldloc_s: case ILOpcode.ldloca: case ILOpcode.ldloca_s: - ScanLdloc(methodBody, offset, opcode, opcode switch + ScanLdloc(opcode, opcode switch { ILOpcode.ldloc => reader.ReadILUInt16(), ILOpcode.ldloca => reader.ReadILUInt16(), @@ -533,7 +533,7 @@ protected virtual void Scan(MethodIL methodBody, ref InterproceduralState interp case ILOpcode.ldtoken: object obj = methodBody.GetObject(reader.ReadILToken()); - ScanLdtoken(methodBody, obj, currentStack); + ScanLdtoken(obj, currentStack); break; case ILOpcode.ldind_i: @@ -897,8 +897,6 @@ Stack currentStack } private static void ScanLdloc( - MethodIL methodBody, - int offset, ILOpcode operation, int index, Stack currentStack, @@ -919,7 +917,7 @@ private static void ScanLdloc( currentStack.Push(newSlot); } - private static void ScanLdtoken(MethodIL methodBody, object operand, Stack currentStack) + private static void ScanLdtoken(object operand, Stack currentStack) { if (operand is TypeDesc type) { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMarker.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMarker.cs index 79ee807c27d6e..f9b2615f62bdc 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMarker.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMarker.cs @@ -15,6 +15,7 @@ using DependencyList = ILCompiler.DependencyAnalysisFramework.DependencyNodeCore.DependencyList; #nullable enable +#pragma warning disable IDE0060 namespace ILCompiler.Dataflow { diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMethodBodyScanner.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMethodBodyScanner.cs index 3f075847110cd..d1477a7531606 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMethodBodyScanner.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/ReflectionMethodBodyScanner.cs @@ -207,7 +207,6 @@ public override bool HandleCall(MethodIL callingMethodBody, MethodDesc calledMet callingMethodBody, calledMethod, operation, - offset, instanceValue, arguments, diagnosticContext, @@ -219,7 +218,6 @@ public static bool HandleCall( MethodIL callingMethodBody, MethodDesc calledMethod, ILOpcode operation, - int offset, MultiValue instanceValue, ImmutableArray argumentValues, DiagnosticContext diagnosticContext, diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/TrimAnalysisMethodCallPattern.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/TrimAnalysisMethodCallPattern.cs index d58b9684280fe..fd3ee335f7e13 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/TrimAnalysisMethodCallPattern.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Dataflow/TrimAnalysisMethodCallPattern.cs @@ -84,7 +84,7 @@ public void MarkAndProduceDiagnostics(ReflectionMarker reflectionMarker, Logger logger.ShouldSuppressAnalysisWarningsForRequires(Origin.MemberDefinition, DiagnosticUtilities.RequiresDynamicCodeAttribute), logger.ShouldSuppressAnalysisWarningsForRequires(Origin.MemberDefinition, DiagnosticUtilities.RequiresAssemblyFilesAttribute), logger); - ReflectionMethodBodyScanner.HandleCall(MethodBody, CalledMethod, Operation, Offset, Instance, Arguments, + ReflectionMethodBodyScanner.HandleCall(MethodBody, CalledMethod, Operation, Instance, Arguments, diagnosticContext, reflectionMarker, out MultiValue _); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericVirtualMethodTableNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericVirtualMethodTableNode.cs index d7d54579f26b7..49844271e8107 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericVirtualMethodTableNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/GenericVirtualMethodTableNode.cs @@ -61,7 +61,7 @@ public static void GetGenericVirtualMethodImplementationDependencies(ref Depende dependencies.Add(new DependencyListEntry(factory.NativeLayout.PlacedSignatureVertex(openImplementationMethodNameAndSig), "gvm table implementation method signature")); } - private void AddGenericVirtualMethodImplementation(NodeFactory factory, MethodDesc callingMethod, MethodDesc implementationMethod) + private void AddGenericVirtualMethodImplementation(MethodDesc callingMethod, MethodDesc implementationMethod) { Debug.Assert(!callingMethod.OwningType.IsInterface); @@ -87,7 +87,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { foreach (var typeGVMEntryInfo in interestingEntry.ScanForGenericVirtualMethodEntries()) { - AddGenericVirtualMethodImplementation(factory, typeGVMEntryInfo.CallingMethod, typeGVMEntryInfo.ImplementationMethod); + AddGenericVirtualMethodImplementation(typeGVMEntryInfo.CallingMethod, typeGVMEntryInfo.ImplementationMethod); } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceGenericVirtualMethodTableNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceGenericVirtualMethodTableNode.cs index 1f99e62ed3dfa..a337a1c03e52c 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceGenericVirtualMethodTableNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/InterfaceGenericVirtualMethodTableNode.cs @@ -81,7 +81,7 @@ public static void GetGenericVirtualMethodImplementationDependencies(ref Depende } } - private void AddGenericVirtualMethodImplementation(NodeFactory factory, MethodDesc callingMethod, TypeDesc implementationType, MethodDesc implementationMethod, DefaultInterfaceMethodResolution resolution) + private void AddGenericVirtualMethodImplementation(MethodDesc callingMethod, TypeDesc implementationType, MethodDesc implementationMethod, DefaultInterfaceMethodResolution resolution) { Debug.Assert(callingMethod.OwningType.IsInterface); @@ -131,7 +131,7 @@ public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { foreach (var typeGVMEntryInfo in interestingEntry.ScanForInterfaceGenericVirtualMethodEntries()) { - AddGenericVirtualMethodImplementation(factory, typeGVMEntryInfo.CallingMethod, typeGVMEntryInfo.ImplementationType, typeGVMEntryInfo.ImplementationMethod, typeGVMEntryInfo.DefaultResolution); + AddGenericVirtualMethodImplementation(typeGVMEntryInfo.CallingMethod, typeGVMEntryInfo.ImplementationType, typeGVMEntryInfo.ImplementationMethod, typeGVMEntryInfo.DefaultResolution); } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NativeLayoutVertexNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NativeLayoutVertexNode.cs index b1a50857ce81c..be6528328420a 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NativeLayoutVertexNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/NativeLayoutVertexNode.cs @@ -412,7 +412,7 @@ public static NativeLayoutTypeSignatureVertexNode NewTypeSignatureVertexNode(Nod case Internal.TypeSystem.TypeFlags.SignatureTypeVariable: case Internal.TypeSystem.TypeFlags.SignatureMethodVariable: - return new NativeLayoutGenericVarSignatureVertexNode(factory, type); + return new NativeLayoutGenericVarSignatureVertexNode(type); // TODO Internal.TypeSystem.TypeFlags.FunctionPointer (Runtime parsing also not yet implemented) case Internal.TypeSystem.TypeFlags.FunctionPointer: @@ -425,7 +425,7 @@ public static NativeLayoutTypeSignatureVertexNode NewTypeSignatureVertexNode(Nod if (type.HasInstantiation && !type.IsGenericDefinition) return new NativeLayoutInstantiatedTypeSignatureVertexNode(factory, type); else - return new NativeLayoutEETypeSignatureVertexNode(factory, type); + return new NativeLayoutEETypeSignatureVertexNode(type); } } } @@ -476,7 +476,7 @@ public override Vertex WriteVertex(NodeFactory factory) private sealed class NativeLayoutGenericVarSignatureVertexNode : NativeLayoutTypeSignatureVertexNode { - public NativeLayoutGenericVarSignatureVertexNode(NodeFactory factory, TypeDesc type) : base(type) + public NativeLayoutGenericVarSignatureVertexNode(TypeDesc type) : base(type) { } public override IEnumerable GetStaticDependencies(NodeFactory context) @@ -541,7 +541,7 @@ public override Vertex WriteVertex(NodeFactory factory) private sealed class NativeLayoutEETypeSignatureVertexNode : NativeLayoutTypeSignatureVertexNode { - public NativeLayoutEETypeSignatureVertexNode(NodeFactory factory, TypeDesc type) : base(type) + public NativeLayoutEETypeSignatureVertexNode(TypeDesc type) : base(type) { Debug.Assert(!type.IsRuntimeDeterminedSubtype); Debug.Assert(!type.HasInstantiation || type.IsGenericDefinition); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VTableSliceNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VTableSliceNode.cs index 02975e52407d6..d33a12eba5c83 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VTableSliceNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VTableSliceNode.cs @@ -183,7 +183,7 @@ public override bool HasFixedSlots } } - public void AddEntry(NodeFactory factory, MethodDesc virtualMethod) + public void AddEntry(MethodDesc virtualMethod) { // GVMs are not emitted in the type's vtable. Debug.Assert(!virtualMethod.HasInstantiation); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VirtualMethodUseNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VirtualMethodUseNode.cs index f97208602afdd..efa665ae18c7f 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VirtualMethodUseNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/VirtualMethodUseNode.cs @@ -45,7 +45,7 @@ protected override void OnMarked(NodeFactory factory) // If the VTable slice is getting built on demand, the fact that the virtual method is used means // that the slot is used. var lazyVTableSlice = factory.VTable(_decl.OwningType) as LazilyBuiltVTableSliceNode; - lazyVTableSlice?.AddEntry(factory, _decl); + lazyVTableSlice?.AddEntry(_decl); } public override bool HasConditionalStaticDependencies => _decl.Context.SupportsUniversalCanon && _decl.OwningType.HasInstantiation && !_decl.OwningType.IsInterface; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Disassembler.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Disassembler.cs index e44fa04665bf0..a1eca3b55d193 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Disassembler.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Disassembler.cs @@ -123,11 +123,11 @@ public unsafe int Disassemble(byte[] bytes, int offset, out string instruction) public void Dispose() { - Dispose(true); + DisposeThis(); GC.SuppressFinalize(this); } - private void Dispose(bool disposing) + private void DisposeThis() { FinishDisasm(_handle); _handle = IntPtr.Zero; @@ -135,7 +135,7 @@ private void Dispose(bool disposing) ~CoreDisassembler() { - Dispose(false); + DisposeThis(); } } } diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logger.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logger.cs index 84a6782564427..755f98239e8c6 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logger.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/Logger.cs @@ -236,7 +236,7 @@ private static bool IsSuppressedOnElement(int id, TypeSystemEntity provider) return false; } - internal static bool IsWarningAsError(int code) + internal static bool IsWarningAsError(int _/*code*/) { // TODO: warnaserror return false; diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MstatObjectDumper.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MstatObjectDumper.cs index 3a9405c09888d..ed8cb6a14b30e 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MstatObjectDumper.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/MstatObjectDumper.cs @@ -59,7 +59,7 @@ protected override void DumpObjectNode(NameMangler mangler, ObjectNode node, Obj switch (node) { case EETypeNode eeType: - SerializeSimpleEntry(_types, eeType.Type, mangledName, objectData); + SerializeSimpleEntry(_types, eeType.Type, objectData); break; case IMethodBodyNode methodBody: var codeInfo = (INodeWithCodeInfo)node; @@ -77,7 +77,7 @@ protected override void DumpObjectNode(NameMangler mangler, ObjectNode node, Obj } } - private void SerializeSimpleEntry(InstructionEncoder encoder, TypeSystemEntity entity, string mangledName, ObjectData blob) + private void SerializeSimpleEntry(InstructionEncoder encoder, TypeSystemEntity entity, ObjectData blob) { encoder.OpCode(ILOpCode.Ldtoken); encoder.Token(_emitter.EmitMetadataHandleForTypeSystemEntity(entity)); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/ILImporter.Scanner.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/ILImporter.Scanner.cs index cb55f2e02feaf..1da1fa4a708c3 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/IL/ILImporter.Scanner.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/IL/ILImporter.Scanner.cs @@ -10,6 +10,8 @@ using Debug = System.Diagnostics.Debug; using DependencyList = ILCompiler.DependencyAnalysisFramework.DependencyNodeCore.DependencyList; +#pragma warning disable IDE0060 + namespace Internal.IL { // Implements an IL scanner that scans method bodies to be compiled by the code generation diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/IBC/MIbcProfileParser.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/IBC/MIbcProfileParser.cs index 96ce377152f54..b82f6f9e15219 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/IBC/MIbcProfileParser.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/IBC/MIbcProfileParser.cs @@ -237,7 +237,7 @@ public static ProfileData ParseMIbcFile(TypeSystemContext tsc, PEReader peReader } } - loadedMethodProfileData = loadedMethodProfileData.Concat(ReadMIbcGroup(tsc, (EcmaMethod)ilBody.GetObject(token))); + loadedMethodProfileData = loadedMethodProfileData.Concat(ReadMIbcGroup((EcmaMethod)ilBody.GetObject(token))); break; case ILOpcode.pop: mibcGroupName = ""; @@ -341,7 +341,7 @@ private enum MibcGroupParseState /// /// This format is designed to be extensible to hold more data as we add new per method profile data without breaking existing parsers. /// - private static IEnumerable ReadMIbcGroup(TypeSystemContext tsc, EcmaMethod method) + private static IEnumerable ReadMIbcGroup(EcmaMethod method) { EcmaMethodIL ilBody = EcmaMethodIL.Create(method); MetadataLoaderForPgoData metadataLoader = new MetadataLoaderForPgoData(ilBody); diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Interop/IL/Marshaller.ReadyToRun.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Interop/IL/Marshaller.ReadyToRun.cs index b7843dca9ea5f..33fd2eb6fba48 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Interop/IL/Marshaller.ReadyToRun.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Interop/IL/Marshaller.ReadyToRun.cs @@ -70,7 +70,6 @@ private static Marshaller[] GetMarshallers( { marshallers[i] = CreateDisabledMarshaller( parameterType, - parameterIndex, MarshallerType.Argument, MarshalDirection.Forward, marshallers, diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/TypeSystem/Mutable/MutableModule.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/TypeSystem/Mutable/MutableModule.cs index 8b72c5745aa88..dd5022aea9768 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/TypeSystem/Mutable/MutableModule.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/TypeSystem/Mutable/MutableModule.cs @@ -81,7 +81,7 @@ public ManagedBinaryEmitterForInternalUse(AssemblyName assemblyName, AssemblyHashAlgorithm hashAlgorithm, Func moduleToIndex, MutableModule mutableModule) - : base(assemblyName, typeSystemContext, assemblyFlags, publicKeyArray, hashAlgorithm) + : base(assemblyName, typeSystemContext, assemblyFlags, publicKeyArray) { _moduleToIndex = moduleToIndex; _mutableModule = mutableModule; diff --git a/src/coreclr/tools/aot/ILCompiler.RyuJit/JitInterface/CorInfoImpl.RyuJit.cs b/src/coreclr/tools/aot/ILCompiler.RyuJit/JitInterface/CorInfoImpl.RyuJit.cs index 5fa43d0d527bc..d46416744066f 100644 --- a/src/coreclr/tools/aot/ILCompiler.RyuJit/JitInterface/CorInfoImpl.RyuJit.cs +++ b/src/coreclr/tools/aot/ILCompiler.RyuJit/JitInterface/CorInfoImpl.RyuJit.cs @@ -21,6 +21,8 @@ using RyuJitCompilation = ILCompiler.Compilation; #endif +#pragma warning disable IDE0060 + namespace Internal.JitInterface { internal unsafe partial class CorInfoImpl diff --git a/src/coreclr/tools/aot/ILCompiler/ILCompilerRootCommand.cs b/src/coreclr/tools/aot/ILCompiler/ILCompilerRootCommand.cs index 483e94552f687..b7b11d8bcb1d9 100644 --- a/src/coreclr/tools/aot/ILCompiler/ILCompilerRootCommand.cs +++ b/src/coreclr/tools/aot/ILCompiler/ILCompilerRootCommand.cs @@ -138,9 +138,9 @@ internal sealed class ILCompilerRootCommand : RootCommand public Option RootedAssemblies { get; } = new(new[] { "--root" }, Array.Empty, "Fully generate given assembly"); public Option> ConditionallyRootedAssemblies { get; } = - new(new[] { "--conditionalroot" }, result => ILLinkify(result.Tokens, true), true, "Fully generate given assembly if it's used"); + new(new[] { "--conditionalroot" }, result => ILLinkify(result.Tokens), true, "Fully generate given assembly if it's used"); public Option> TrimmedAssemblies { get; } = - new(new[] { "--trim" }, result => ILLinkify(result.Tokens, true), true, "Trim the specified assembly"); + new(new[] { "--trim" }, result => ILLinkify(result.Tokens), true, "Trim the specified assembly"); public Option RootDefaultAssemblies { get; } = new(new[] { "--defaultrooting" }, "Root assemblies that are not marked [IsTrimmable]"); public Option TargetArchitecture { get; } = @@ -345,7 +345,7 @@ public static IEnumerable GetExtendedHelp(HelpContext _) }; } - private static IEnumerable ILLinkify(IReadOnlyList tokens, bool setDefaultToEmpty) + private static IEnumerable ILLinkify(IReadOnlyList tokens) { if (tokens.Count == 0) { diff --git a/src/coreclr/tools/aot/ILLink.Shared/.editorconfig b/src/coreclr/tools/aot/ILLink.Shared/.editorconfig new file mode 100644 index 0000000000000..c676015496927 --- /dev/null +++ b/src/coreclr/tools/aot/ILLink.Shared/.editorconfig @@ -0,0 +1,2 @@ +# IDE0060: Remove unused parameter +dotnet_diagnostic.IDE0060.severity = silent diff --git a/src/coreclr/tools/aot/ILLink.Shared/Directory.Build.props b/src/coreclr/tools/aot/ILLink.Shared/Directory.Build.props new file mode 100644 index 0000000000000..ea6a629563c48 --- /dev/null +++ b/src/coreclr/tools/aot/ILLink.Shared/Directory.Build.props @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/libraries/Common/src/Interop/Interop.Ldap.cs b/src/libraries/Common/src/Interop/Interop.Ldap.cs index 478f5121c4996..d933cf98f2ed1 100644 --- a/src/libraries/Common/src/Interop/Interop.Ldap.cs +++ b/src/libraries/Common/src/Interop/Interop.Ldap.cs @@ -192,7 +192,7 @@ internal static unsafe class PinningMarshaller public static ref int GetPinnableReference(BerVal managed) => ref (managed is null ? ref Unsafe.NullRef() : ref managed.bv_len); // All usages in our currently supported scenarios will always go through GetPinnableReference - public static int* ConvertToUnmanaged(BerVal managed) => throw new UnreachableException(); + public static int* ConvertToUnmanaged(BerVal _) => throw new UnreachableException(); } #endif } diff --git a/src/libraries/Common/src/Interop/Linux/OpenLdap/Interop.Ber.cs b/src/libraries/Common/src/Interop/Linux/OpenLdap/Interop.Ber.cs index 20c2f5bb78d88..d5f6895a2e7d8 100644 --- a/src/libraries/Common/src/Interop/Linux/OpenLdap/Interop.Ber.cs +++ b/src/libraries/Common/src/Interop/Linux/OpenLdap/Interop.Ber.cs @@ -194,6 +194,7 @@ public static int ber_scanf_ptr(SafeBerHandle berElement, string format, ref Int [LibraryImport(Libraries.OpenLdap, EntryPoint = "ber_get_stringal")] private static partial int ber_get_stringal(SafeBerHandle berElement, ref IntPtr value); +#pragma warning disable IDE0060 public static int ber_printf_berarray(SafeBerHandle berElement, string format, IntPtr value, nuint tag) { Debug.Assert(format == "v" || format == "V"); @@ -207,5 +208,6 @@ public static int ber_scanf_multibytearray(SafeBerHandle berElement, string form // V and v are not supported on Unix yet. return -1; } +#pragma warning restore IDE0060 } } diff --git a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs index 902ddce42c37f..58bdd29eef23e 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs @@ -134,7 +134,7 @@ private static SslProtocols CalculateEffectiveProtocols(SslAuthenticationOptions } } - if (CipherSuitesPolicyPal.ShouldOptOutOfLowerThanTls13(sslAuthenticationOptions.CipherSuitesPolicy, sslAuthenticationOptions.EncryptionPolicy)) + if (CipherSuitesPolicyPal.ShouldOptOutOfLowerThanTls13(sslAuthenticationOptions.CipherSuitesPolicy)) { if (!CipherSuitesPolicyPal.WantsTls13(protocols)) { @@ -662,6 +662,7 @@ private static void QueryUniqueChannelBinding(SafeSslHandle context, SafeChannel bindingHandle.SetCertHashLength(certHashLength); } +#pragma warning disable IDE0060 [UnmanagedCallersOnly] private static int VerifyClientCertificate(int preverify_ok, IntPtr x509_ctx_ptr) { @@ -672,6 +673,7 @@ private static int VerifyClientCertificate(int preverify_ok, IntPtr x509_ctx_ptr const int OpenSslSuccess = 1; return OpenSslSuccess; } +#pragma warning restore IDE0060 [UnmanagedCallersOnly] private static unsafe int AlpnServerSelectCallback(IntPtr ssl, byte** outp, byte* outlen, byte* inp, uint inlen, IntPtr arg) @@ -774,7 +776,7 @@ private static unsafe void RemoveSessionCallback(IntPtr ctx, IntPtr session) IntPtr name = Ssl.SessionGetHostname(session); Debug.Assert(name != IntPtr.Zero); - ctxHandle.RemoveSession(name, session); + ctxHandle.RemoveSession(name); } private static int BioRead(SafeBioHandle bio, byte[] buffer, int count) diff --git a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtx.cs b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtx.cs index 4ed5c1881328e..2a69e63149f24 100644 --- a/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtx.cs +++ b/src/libraries/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.SslCtx.cs @@ -158,7 +158,7 @@ internal bool TryAddSession(IntPtr namePtr, IntPtr session) return false; } - internal void RemoveSession(IntPtr namePtr, IntPtr session) + internal void RemoveSession(IntPtr namePtr) { Debug.Assert(_sslSessions != null); diff --git a/src/libraries/Common/src/System/IO/TempFileCollection.cs b/src/libraries/Common/src/System/IO/TempFileCollection.cs index 36db27afbcb7a..6107d8d1bb8a9 100644 --- a/src/libraries/Common/src/System/IO/TempFileCollection.cs +++ b/src/libraries/Common/src/System/IO/TempFileCollection.cs @@ -47,6 +47,7 @@ void IDisposable.Dispose() GC.SuppressFinalize(this); } +#pragma warning disable IDE0060 #if CODEDOM protected virtual #else @@ -56,6 +57,7 @@ void Dispose(bool disposing) { SafeDelete(); } +#pragma warning restore IDE0060 ~TempFileCollection() { diff --git a/src/libraries/Common/src/System/Net/Http/aspnetcore/Http3/QPack/QPackDecoder.cs b/src/libraries/Common/src/System/Net/Http/aspnetcore/Http3/QPack/QPackDecoder.cs index 394cc1aee72a5..47fc89aaa5d9d 100644 --- a/src/libraries/Common/src/System/Net/Http/aspnetcore/Http3/QPack/QPackDecoder.cs +++ b/src/libraries/Common/src/System/Net/Http/aspnetcore/Http3/QPack/QPackDecoder.cs @@ -223,10 +223,10 @@ private void DecodeInternal(ReadOnlySpan data, IHttpStreamHeadersHandler h ParseHeaderValue(data, ref currentIndex, handler); break; case State.PostBaseIndex: - ParsePostBaseIndex(data, ref currentIndex, handler); + ParsePostBaseIndex(data, ref currentIndex); break; case State.HeaderNameIndexPostBase: - ParseHeaderNameIndexPostBase(data, ref currentIndex, handler); + ParseHeaderNameIndexPostBase(data, ref currentIndex); break; default: // Can't happen @@ -253,7 +253,7 @@ private void DecodeInternal(ReadOnlySpan data, IHttpStreamHeadersHandler h } } - private void ParseHeaderNameIndexPostBase(ReadOnlySpan data, ref int currentIndex, IHttpStreamHeadersHandler handler) + private void ParseHeaderNameIndexPostBase(ReadOnlySpan data, ref int currentIndex) { if (TryDecodeInteger(data, ref currentIndex, out int intResult)) { @@ -261,11 +261,11 @@ private void ParseHeaderNameIndexPostBase(ReadOnlySpan data, ref int curre } } - private void ParsePostBaseIndex(ReadOnlySpan data, ref int currentIndex, IHttpStreamHeadersHandler handler) + private void ParsePostBaseIndex(ReadOnlySpan data, ref int currentIndex) { - if (TryDecodeInteger(data, ref currentIndex, out int intResult)) + if (TryDecodeInteger(data, ref currentIndex, out _)) { - OnPostBaseIndex(intResult, handler); + OnPostBaseIndex(); } } @@ -494,14 +494,14 @@ private void ParseCompressedHeaders(ReadOnlySpan data, ref int currentInde break; case 3: // Indexed Header Field With Post-Base Index prefixInt = ~PostBaseIndexMask & b; - if (_integerDecoder.BeginTryDecode((byte)prefixInt, PostBaseIndexPrefix, out intResult)) + if (_integerDecoder.BeginTryDecode((byte)prefixInt, PostBaseIndexPrefix, out _)) { - OnPostBaseIndex(intResult, handler); + OnPostBaseIndex(); } else { _state = State.PostBaseIndex; - ParsePostBaseIndex(data, ref currentIndex, handler); + ParsePostBaseIndex(data, ref currentIndex); } break; default: // Literal Header Field With Post-Base Name Reference (at least 4 zeroes, maybe more) @@ -513,7 +513,7 @@ private void ParseCompressedHeaders(ReadOnlySpan data, ref int currentInde else { _state = State.HeaderNameIndexPostBase; - ParseHeaderNameIndexPostBase(data, ref currentIndex, handler); + ParseHeaderNameIndexPostBase(data, ref currentIndex); } break; } @@ -710,7 +710,7 @@ private void OnIndexedHeaderName(int index) _state = State.HeaderValueLength; } - private static void OnIndexedHeaderNamePostBase(int index) + private static void OnIndexedHeaderNamePostBase(int _ /*index*/) { ThrowDynamicTableNotSupported(); // TODO update with postbase index @@ -718,7 +718,7 @@ private static void OnIndexedHeaderNamePostBase(int index) // _state = State.HeaderValueLength; } - private static void OnPostBaseIndex(int intResult, IHttpStreamHeadersHandler handler) + private static void OnPostBaseIndex() { ThrowDynamicTableNotSupported(); // TODO diff --git a/src/libraries/Common/src/System/Net/NTAuthentication.Managed.cs b/src/libraries/Common/src/System/Net/NTAuthentication.Managed.cs index 38203cdf1d1ac..5b8eca333cdf3 100644 --- a/src/libraries/Common/src/System/Net/NTAuthentication.Managed.cs +++ b/src/libraries/Common/src/System/Net/NTAuthentication.Managed.cs @@ -1013,7 +1013,7 @@ private unsafe byte[] CreateSpNegoNegotiateMessage(ReadOnlySpan ntlmNegoti return null; } - internal NegotiateAuthenticationStatusCode Wrap(ReadOnlySpan input, IBufferWriter outputWriter, bool requestEncryption, out bool isEncrypted) + internal NegotiateAuthenticationStatusCode Wrap(ReadOnlySpan input, IBufferWriter outputWriter, bool _/*requestEncryption*/, out bool isEncrypted) { if (_clientSeal == null) { @@ -1084,7 +1084,7 @@ internal NegotiateAuthenticationStatusCode UnwrapInPlace(Span input, out i return NegotiateAuthenticationStatusCode.Completed; } -#pragma warning disable CA1822 +#pragma warning disable CA1822, IDE0060 internal int Encrypt(ReadOnlySpan buffer, [NotNull] ref byte[]? output) { throw new PlatformNotSupportedException(); @@ -1106,6 +1106,6 @@ internal int Decrypt(Span payload, out int newOffset) internal bool IsValidContext => true; internal string? ClientSpecifiedSpn => _spn; -#pragma warning restore CA1822 +#pragma warning restore CA1822, IDE0060 } } diff --git a/src/libraries/Common/src/System/Net/NetworkInformation/InterfaceInfoPal.Browser.cs b/src/libraries/Common/src/System/Net/NetworkInformation/InterfaceInfoPal.Browser.cs index d5d50a2aa3367..46ccc26122da7 100644 --- a/src/libraries/Common/src/System/Net/NetworkInformation/InterfaceInfoPal.Browser.cs +++ b/src/libraries/Common/src/System/Net/NetworkInformation/InterfaceInfoPal.Browser.cs @@ -5,7 +5,7 @@ namespace System.Net.NetworkInformation { internal static class InterfaceInfoPal { - public static uint InterfaceNameToIndex(string interfaceName) + public static uint InterfaceNameToIndex(string _/*interfaceName*/) { // zero means "unknown" return 0; diff --git a/src/libraries/Common/src/System/Net/Security/CertificateValidation.OSX.cs b/src/libraries/Common/src/System/Net/Security/CertificateValidation.OSX.cs index ccd50c95b8c94..fbb5a80f9612e 100644 --- a/src/libraries/Common/src/System/Net/Security/CertificateValidation.OSX.cs +++ b/src/libraries/Common/src/System/Net/Security/CertificateValidation.OSX.cs @@ -14,7 +14,7 @@ internal static class CertificateValidation private static readonly IdnMapping s_idnMapping = new IdnMapping(); // WARNING: This function will do the verification using OpenSSL. If the intention is to use OS function, caller should use CertificatePal interface. - internal static SslPolicyErrors BuildChainAndVerifyProperties(X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, bool isServer, string? hostName, IntPtr certificateBuffer, int bufferLength = 0) + internal static SslPolicyErrors BuildChainAndVerifyProperties(X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, bool _ /*isServer*/, string? hostName, IntPtr certificateBuffer, int bufferLength = 0) { SslPolicyErrors errors = chain.Build(remoteCertificate) ? SslPolicyErrors.None : diff --git a/src/libraries/Common/src/System/Net/Security/CertificateValidation.Unix.cs b/src/libraries/Common/src/System/Net/Security/CertificateValidation.Unix.cs index 169a3c72719bb..02af97bde7486 100644 --- a/src/libraries/Common/src/System/Net/Security/CertificateValidation.Unix.cs +++ b/src/libraries/Common/src/System/Net/Security/CertificateValidation.Unix.cs @@ -12,10 +12,12 @@ internal static class CertificateValidation { private static readonly IdnMapping s_idnMapping = new IdnMapping(); +#pragma warning disable IDE0060 internal static SslPolicyErrors BuildChainAndVerifyProperties(X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, bool isServer, string? hostName, IntPtr certificateBuffer, int bufferLength) => BuildChainAndVerifyProperties(chain, remoteCertificate, checkCertName, isServer, hostName); +#pragma warning restore IDE0060 - internal static SslPolicyErrors BuildChainAndVerifyProperties(X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, bool isServer, string? hostName) + internal static SslPolicyErrors BuildChainAndVerifyProperties(X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, bool _ /*isServer*/, string? hostName) { SslPolicyErrors errors = chain.Build(remoteCertificate) ? SslPolicyErrors.None : diff --git a/src/libraries/Common/src/System/Net/Security/CertificateValidation.Windows.cs b/src/libraries/Common/src/System/Net/Security/CertificateValidation.Windows.cs index 9efcb10f106d9..34dc3358e1e2b 100644 --- a/src/libraries/Common/src/System/Net/Security/CertificateValidation.Windows.cs +++ b/src/libraries/Common/src/System/Net/Security/CertificateValidation.Windows.cs @@ -13,8 +13,10 @@ namespace System.Net { internal static partial class CertificateValidation { +#pragma warning disable IDE0060 internal static SslPolicyErrors BuildChainAndVerifyProperties(X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, bool isServer, string? hostName, IntPtr certificateBuffer, int bufferLength) => BuildChainAndVerifyProperties(chain, remoteCertificate, checkCertName, isServer, hostName); +#pragma warning restore IDE0060 internal static SslPolicyErrors BuildChainAndVerifyProperties(X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, bool isServer, string? hostName) { diff --git a/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs b/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs index 702167758da69..c978c80697f85 100644 --- a/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs +++ b/src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs @@ -29,7 +29,7 @@ internal static partial class NegotiateStreamPal // defined in winerror.h private const int NTE_FAIL = unchecked((int)0x80090020); - internal static string QueryContextClientSpecifiedSpn(SafeDeleteContext securityContext) + internal static string QueryContextClientSpecifiedSpn(SafeDeleteContext _ /*securityContext*/) { throw new PlatformNotSupportedException(SR.net_nego_server_not_supported); } @@ -296,6 +296,7 @@ internal static SecurityStatusPal InitializeSecurityContext( return status; } +#pragma warning disable IDE0060 internal static SecurityStatusPal AcceptSecurityContext( SafeFreeCredentials? credentialsHandle, ref SafeDeleteContext? securityContext, @@ -387,6 +388,7 @@ internal static SecurityStatusPal AcceptSecurityContext( negoContext.SetGssContext(contextHandle); } } +#pragma warning restore IDE0060 // https://www.gnu.org/software/gss/reference/gss.pdf (page 25) private static SecurityStatusPalErrorCode GetErrorCode(Interop.NetSecurityNative.GssApiException exception) @@ -434,11 +436,13 @@ internal static Win32Exception CreateExceptionFromError(SecurityStatusPal status return new Win32Exception(NTE_FAIL, (statusCode.Exception != null) ? statusCode.Exception.Message : statusCode.ErrorCode.ToString()); } +#pragma warning disable IDE0060 internal static int QueryMaxTokenSize(string package) { // This value is not used on Unix return 0; } +#pragma warning restore IDE0060 internal static SafeFreeCredentials AcquireDefaultCredential(string package, bool isServer) { @@ -486,12 +490,14 @@ internal static SafeFreeCredentials AcquireCredentialsHandle(string package, boo } } +#pragma warning disable IDE0060 internal static SecurityStatusPal CompleteAuthToken( ref SafeDeleteContext? securityContext, ReadOnlySpan incomingBlob) { return new SecurityStatusPal(SecurityStatusPalErrorCode.OK); } +#pragma warning restore IDE0060 internal static int Encrypt( SafeDeleteContext securityContext, diff --git a/src/libraries/Common/src/System/Net/Security/SafeCredentialReference.cs b/src/libraries/Common/src/System/Net/Security/SafeCredentialReference.cs index a8479c3bda893..217427d391854 100644 --- a/src/libraries/Common/src/System/Net/Security/SafeCredentialReference.cs +++ b/src/libraries/Common/src/System/Net/Security/SafeCredentialReference.cs @@ -36,11 +36,11 @@ private SafeCredentialReference(SafeFreeCredentials target) public void Dispose() { - Dispose(true); + DisposeInternal(); GC.SuppressFinalize(this); } - private void Dispose(bool disposing) + private void DisposeInternal() { SafeFreeCredentials? target = Target; target?.DangerousRelease(); @@ -49,7 +49,7 @@ private void Dispose(bool disposing) ~SafeCredentialReference() { - Dispose(false); + DisposeInternal(); } } diff --git a/src/libraries/Common/src/System/Security/Cryptography/Asn1/AsnXml.targets b/src/libraries/Common/src/System/Security/Cryptography/Asn1/AsnXml.targets index 9f72a36835ca0..940c73ca57237 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/Asn1/AsnXml.targets +++ b/src/libraries/Common/src/System/Security/Cryptography/Asn1/AsnXml.targets @@ -3,6 +3,7 @@ <_AsnXmlDiffCmd>%24%28command -v diff%29 -q -a <_AsnXmlDiffCmd Condition="$([MSBuild]::IsOsPlatform('windows')) == 'true'">$(SystemRoot)\System32\fc.exe /a + <_AsnXmlDiffCmd Condition="$([MSBuild]::IsOsPlatform('osx')) == 'true'">diff diff --git a/src/libraries/Common/src/System/Security/Cryptography/Asn1/DssParms.xml b/src/libraries/Common/src/System/Security/Cryptography/Asn1/DssParms.xml index 687bf3d41bcaa..c90460d601488 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/Asn1/DssParms.xml +++ b/src/libraries/Common/src/System/Security/Cryptography/Asn1/DssParms.xml @@ -2,7 +2,8 @@ + namespace="System.Security.Cryptography.Asn1" + rebind="false"> $([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) - - $(NoWarn);CA1823 + SR.PlatformNotSupported_Registry - + - - - - - - - diff --git a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.FileSystem.cs b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.FileSystem.cs deleted file mode 100644 index f91463fb46cd6..0000000000000 --- a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.FileSystem.cs +++ /dev/null @@ -1,121 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using Microsoft.Win32.SafeHandles; -using System; -using System.Diagnostics.CodeAnalysis; - -namespace Microsoft.Win32 -{ - public sealed partial class RegistryKey : MarshalByRefObject, IDisposable - { - private static void ClosePerfDataKey() - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - private static void FlushCore() - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - private static RegistryKey CreateSubKeyInternalCore(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - private static void DeleteSubKeyCore(string subkey, bool throwOnMissingSubKey) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - private static void DeleteSubKeyTreeCore(string subkey) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - private static void DeleteValueCore(string name, bool throwOnMissingValue) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - private static RegistryKey OpenBaseKeyCore(RegistryHive hKey, RegistryView view) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - private static RegistryKey OpenRemoteBaseKeyCore(RegistryHive hKey, string machineName, RegistryView view) - { - throw new PlatformNotSupportedException(SR.Security_RegistryPermission); // remote stores not supported on Unix - } - - private static RegistryKey InternalOpenSubKeyCore(string name, RegistryKeyPermissionCheck permissionCheck, int rights) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - private static RegistryKey InternalOpenSubKeyCore(string name, bool writable) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - internal static RegistryKey InternalOpenSubKeyWithoutSecurityChecksCore(string name, bool writable) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - private static SafeRegistryHandle SystemKeyHandle - { - get - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - } - - private static int InternalSubKeyCountCore() - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - private static string[] InternalGetSubKeyNamesCore(int subkeys) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - private static int InternalValueCountCore() - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - private static string[] GetValueNamesCore(int values) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - [return: NotNullIfNotNull(nameof(defaultValue))] - private static object InternalGetValueCore(string? name, object? defaultValue, bool doNotExpand) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - private static RegistryValueKind GetValueKindCore(string? name) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - private static void SetValueCore(string? name, object value, RegistryValueKind valueKind) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - private static int GetRegistryKeyAccess(bool isWritable) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - - private static int GetRegistryKeyAccess(RegistryKeyPermissionCheck mode) - { - throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); - } - } -} diff --git a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs index e857a8c865aeb..2d6f85015a8c4 100644 --- a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs +++ b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs @@ -397,7 +397,7 @@ public RegistrySecurity GetAccessControl() public RegistrySecurity GetAccessControl(AccessControlSections includeSections) { EnsureNotDisposed(); - return new RegistrySecurity(Handle, Name, includeSections); + return new RegistrySecurity(Handle, includeSections); } public void SetAccessControl(RegistrySecurity registrySecurity) @@ -405,7 +405,7 @@ public void SetAccessControl(RegistrySecurity registrySecurity) EnsureWriteable(); ArgumentNullException.ThrowIfNull(registrySecurity); - registrySecurity.Persist(Handle, Name); + registrySecurity.Persist(Handle); } /// Retrieves the count of subkeys. diff --git a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.FileSystem.cs b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.FileSystem.cs deleted file mode 100644 index d6d4f1d0e11e2..0000000000000 --- a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.FileSystem.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System.Runtime.InteropServices; - -namespace Microsoft.Win32.SafeHandles -{ - public sealed partial class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid - { - // TODO: implement this if necessary - protected override bool ReleaseHandle() => true; - } -} diff --git a/src/libraries/Microsoft.Win32.Registry/src/System/Security/AccessControl/RegistrySecurity.FileSystem.cs b/src/libraries/Microsoft.Win32.Registry/src/System/Security/AccessControl/RegistrySecurity.FileSystem.cs deleted file mode 100644 index eccc96c8f4b09..0000000000000 --- a/src/libraries/Microsoft.Win32.Registry/src/System/Security/AccessControl/RegistrySecurity.FileSystem.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -using System.Runtime.InteropServices; - -namespace System.Security.AccessControl -{ - public sealed partial class RegistrySecurity : NativeObjectSecurity - { - private static Exception _HandleErrorCodeCore(int errorCode, string? name, SafeHandle? handle, object? context) - { - // TODO: Implement this - throw new PlatformNotSupportedException(); - } - } -} diff --git a/src/libraries/Microsoft.Win32.Registry/src/System/Security/AccessControl/RegistrySecurity.Windows.cs b/src/libraries/Microsoft.Win32.Registry/src/System/Security/AccessControl/RegistrySecurity.Windows.cs index f16e03965ed18..f2ccfe1f326d2 100644 --- a/src/libraries/Microsoft.Win32.Registry/src/System/Security/AccessControl/RegistrySecurity.Windows.cs +++ b/src/libraries/Microsoft.Win32.Registry/src/System/Security/AccessControl/RegistrySecurity.Windows.cs @@ -8,7 +8,7 @@ namespace System.Security.AccessControl { public sealed partial class RegistrySecurity : NativeObjectSecurity { - private static Exception? _HandleErrorCodeCore(int errorCode, string? name, SafeHandle? handle, object? context) + private static Exception? _HandleErrorCodeCore(int errorCode) { Exception? exception = null; @@ -19,7 +19,7 @@ public sealed partial class RegistrySecurity : NativeObjectSecurity break; case Interop.Errors.ERROR_INVALID_NAME: - exception = new ArgumentException(SR.Arg_RegInvalidKeyName, nameof(name)); + exception = new ArgumentException(SR.Arg_RegInvalidKeyName, "name"); break; case Interop.Errors.ERROR_INVALID_HANDLE: diff --git a/src/libraries/Microsoft.Win32.Registry/src/System/Security/AccessControl/RegistrySecurity.cs b/src/libraries/Microsoft.Win32.Registry/src/System/Security/AccessControl/RegistrySecurity.cs index 23c046b17b22f..001c296103173 100644 --- a/src/libraries/Microsoft.Win32.Registry/src/System/Security/AccessControl/RegistrySecurity.cs +++ b/src/libraries/Microsoft.Win32.Registry/src/System/Security/AccessControl/RegistrySecurity.cs @@ -89,14 +89,14 @@ public RegistrySecurity() { } - internal RegistrySecurity(SafeRegistryHandle hKey, string name, AccessControlSections includeSections) + internal RegistrySecurity(SafeRegistryHandle hKey, AccessControlSections includeSections) : base(true, ResourceType.RegistryKey, hKey, includeSections, _HandleErrorCode, null) { } private static Exception? _HandleErrorCode(int errorCode, string? name, SafeHandle? handle, object? context) { - return _HandleErrorCodeCore(errorCode, name, handle, context); + return _HandleErrorCodeCore(errorCode); } public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) @@ -135,7 +135,7 @@ internal AccessControlSections GetAccessControlSectionsFromChanges() return persistRules; } - internal void Persist(SafeRegistryHandle hKey, string keyName) + internal void Persist(SafeRegistryHandle hKey) { WriteLock(); diff --git a/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs b/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs index da545994e8e76..dadf7d5af116b 100644 --- a/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs +++ b/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs @@ -222,7 +222,7 @@ private int Run(string[] args) private static void GenerateFile(List typeNames, string defaultNamespace, string assemblyName, bool proxyOnly, bool silent, bool verbose, bool force, string outputDirectory, bool parsableerrors) { - Assembly assembly = LoadAssembly(assemblyName, true); + Assembly assembly = LoadAssembly(assemblyName); Type[] types; if (typeNames == null || typeNames.Count == 0) @@ -473,7 +473,7 @@ private static void ImportType(Type type, string defaultNamespace, List Output.Write("base"); + private void GenerateBaseReferenceExpression() => Output.Write("base"); private void GenerateBinaryOperatorExpression(CodeBinaryOperatorExpression e) { @@ -344,8 +344,8 @@ private void GenerateEvents(CodeTypeDeclaration e) GenerateCommentStatements(_currentMember.Comments); CodeMemberEvent imp = (CodeMemberEvent)current; if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); - GenerateEvent(imp, e); - if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); + GenerateEvent(imp); + if (imp.LinePragma != null) GenerateLinePragmaEnd(); if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); @@ -374,7 +374,7 @@ private void GenerateFields(CodeTypeDeclaration e) CodeMemberField imp = (CodeMemberField)current; if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); GenerateField(imp); - if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); + if (imp.LinePragma != null) GenerateLinePragmaEnd(); if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); @@ -445,7 +445,7 @@ private void GenerateSnippetCompileUnit(CodeSnippetCompileUnit e) if (e.LinePragma != null) GenerateLinePragmaStart(e.LinePragma); Output.WriteLine(e.Value); - if (e.LinePragma != null) GenerateLinePragmaEnd(e.LinePragma); + if (e.LinePragma != null) GenerateLinePragmaEnd(); if (e.EndDirectives.Count > 0) { @@ -605,7 +605,7 @@ private void GenerateStatement(CodeStatement e) if (e.LinePragma != null) { - GenerateLinePragmaEnd(e.LinePragma); + GenerateLinePragmaEnd(); } if (e.EndDirectives.Count > 0) { @@ -627,7 +627,7 @@ private void GenerateNamespaceImports(CodeNamespace e) { if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); GenerateNamespaceImport(imp); - if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); + if (imp.LinePragma != null) GenerateLinePragmaEnd(); } } @@ -802,10 +802,10 @@ private void AppendEscapedChar(StringBuilder b, char value) } } - private void GeneratePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e) => + private void GeneratePropertySetValueReferenceExpression() => Output.Write("value"); - private void GenerateThisReferenceExpression(CodeThisReferenceExpression e) => + private void GenerateThisReferenceExpression() => Output.Write("this"); private void GenerateExpressionStatement(CodeExpressionStatement e) @@ -1086,14 +1086,14 @@ private void GenerateLinePragmaStart(CodeLinePragma e) Output.WriteLine(); } - private void GenerateLinePragmaEnd(CodeLinePragma e) + private void GenerateLinePragmaEnd() { Output.WriteLine(); Output.WriteLine("#line default"); Output.WriteLine("#line hidden"); } - private void GenerateEvent(CodeMemberEvent e, CodeTypeDeclaration c) + private void GenerateEvent(CodeMemberEvent e) { if (IsCurrentDelegate || IsCurrentEnum) return; @@ -1124,7 +1124,7 @@ private void GenerateExpression(CodeExpression e) } else if (e is CodeBaseReferenceExpression) { - GenerateBaseReferenceExpression((CodeBaseReferenceExpression)e); + GenerateBaseReferenceExpression(); } else if (e is CodeBinaryOperatorExpression) { @@ -1200,11 +1200,11 @@ private void GenerateExpression(CodeExpression e) } else if (e is CodePropertySetValueReferenceExpression) { - GeneratePropertySetValueReferenceExpression((CodePropertySetValueReferenceExpression)e); + GeneratePropertySetValueReferenceExpression(); } else if (e is CodeThisReferenceExpression) { - GenerateThisReferenceExpression((CodeThisReferenceExpression)e); + GenerateThisReferenceExpression(); } else if (e is CodeTypeReferenceExpression) { @@ -1284,7 +1284,7 @@ private void GenerateParameterDeclarationExpression(CodeParameterDeclarationExpr OutputTypeNamePair(e.Type, e.Name); } - private void GenerateEntryPointMethod(CodeEntryPointMethod e, CodeTypeDeclaration c) + private void GenerateEntryPointMethod(CodeEntryPointMethod e) { if (e.CustomAttributes.Count > 0) { @@ -1323,13 +1323,13 @@ private void GenerateMethods(CodeTypeDeclaration e) if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); if (current is CodeEntryPointMethod) { - GenerateEntryPointMethod((CodeEntryPointMethod)current, e); + GenerateEntryPointMethod((CodeEntryPointMethod)current); } else { - GenerateMethod(imp, e); + GenerateMethod(imp); } - if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); + if (imp.LinePragma != null) GenerateLinePragmaEnd(); if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); @@ -1338,7 +1338,7 @@ private void GenerateMethods(CodeTypeDeclaration e) } } - private void GenerateMethod(CodeMemberMethod e, CodeTypeDeclaration c) + private void GenerateMethod(CodeMemberMethod e) { if (!(IsCurrentClass || IsCurrentStruct || IsCurrentInterface)) return; @@ -1418,8 +1418,8 @@ private void GenerateProperties(CodeTypeDeclaration e) GenerateCommentStatements(_currentMember.Comments); CodeMemberProperty imp = (CodeMemberProperty)current; if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); - GenerateProperty(imp, e); - if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); + GenerateProperty(imp); + if (imp.LinePragma != null) GenerateLinePragmaEnd(); if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); @@ -1428,7 +1428,7 @@ private void GenerateProperties(CodeTypeDeclaration e) } } - private void GenerateProperty(CodeMemberProperty e, CodeTypeDeclaration c) + private void GenerateProperty(CodeMemberProperty e) { if (!(IsCurrentClass || IsCurrentStruct || IsCurrentInterface)) return; @@ -1730,8 +1730,8 @@ private void GenerateConstructors(CodeTypeDeclaration e) GenerateCommentStatements(_currentMember.Comments); CodeConstructor imp = (CodeConstructor)current; if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); - GenerateConstructor(imp, e); - if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); + GenerateConstructor(imp); + if (imp.LinePragma != null) GenerateLinePragmaEnd(); if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); @@ -1740,7 +1740,7 @@ private void GenerateConstructors(CodeTypeDeclaration e) } } - private void GenerateConstructor(CodeConstructor e, CodeTypeDeclaration c) + private void GenerateConstructor(CodeConstructor e) { if (!(IsCurrentClass || IsCurrentStruct)) return; @@ -1860,8 +1860,8 @@ private void GenerateType(CodeTypeDeclaration e) // Nested types clobber the current class, so reset it. _currentClass = e; - GenerateTypeEnd(e); - if (e.LinePragma != null) GenerateLinePragmaEnd(e.LinePragma); + GenerateTypeEnd(); + if (e.LinePragma != null) GenerateLinePragmaEnd(); if (e.EndDirectives.Count > 0) { @@ -1974,13 +1974,13 @@ private void GenerateTypeMember(CodeTypeMember member, CodeTypeDeclaration decla } else if (member is CodeMemberProperty) { - GenerateProperty((CodeMemberProperty)member, declaredType); + GenerateProperty((CodeMemberProperty)member); } else if (member is CodeMemberMethod) { if (member is CodeConstructor) { - GenerateConstructor((CodeConstructor)member, declaredType); + GenerateConstructor((CodeConstructor)member); } else if (member is CodeTypeConstructor) { @@ -1988,16 +1988,16 @@ private void GenerateTypeMember(CodeTypeMember member, CodeTypeDeclaration decla } else if (member is CodeEntryPointMethod) { - GenerateEntryPointMethod((CodeEntryPointMethod)member, declaredType); + GenerateEntryPointMethod((CodeEntryPointMethod)member); } else { - GenerateMethod((CodeMemberMethod)member, declaredType); + GenerateMethod((CodeMemberMethod)member); } } else if (member is CodeMemberEvent) { - GenerateEvent((CodeMemberEvent)member, declaredType); + GenerateEvent((CodeMemberEvent)member); } else if (member is CodeSnippetTypeMember) { @@ -2020,7 +2020,7 @@ private void GenerateTypeMember(CodeTypeMember member, CodeTypeDeclaration decla if (member.LinePragma != null) { - GenerateLinePragmaEnd(member.LinePragma); + GenerateLinePragmaEnd(); } if (member.EndDirectives.Count > 0) @@ -2049,7 +2049,7 @@ private void GenerateTypeConstructors(CodeTypeDeclaration e) CodeTypeConstructor imp = (CodeTypeConstructor)current; if (imp.LinePragma != null) GenerateLinePragmaStart(imp.LinePragma); GenerateTypeConstructor(imp); - if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); + if (imp.LinePragma != null) GenerateLinePragmaEnd(); if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); @@ -2091,7 +2091,7 @@ private void GenerateSnippetMembers(CodeTypeDeclaration e) // Restore the indent Indent = savedIndent; - if (imp.LinePragma != null) GenerateLinePragmaEnd(imp.LinePragma); + if (imp.LinePragma != null) GenerateLinePragmaEnd(); if (_currentMember.EndDirectives.Count > 0) { GenerateDirectives(_currentMember.EndDirectives); @@ -2378,7 +2378,7 @@ private void OutputTypeAttributes(CodeTypeDeclaration e) } } - private void GenerateTypeEnd(CodeTypeDeclaration e) + private void GenerateTypeEnd() { if (!IsCurrentDelegate) { @@ -2549,10 +2549,10 @@ private void GenerateNamespaceImport(CodeNamespaceImport e) Output.WriteLine(';'); } - private void GenerateAttributeDeclarationsStart(CodeAttributeDeclarationCollection attributes) => + private void GenerateAttributeDeclarationsStart() => Output.Write('['); - private void GenerateAttributeDeclarationsEnd(CodeAttributeDeclarationCollection attributes) => + private void GenerateAttributeDeclarationsEnd() => Output.Write(']'); private void GenerateAttributes(CodeAttributeDeclarationCollection attributes) => @@ -2581,7 +2581,7 @@ private void GenerateAttributes(CodeAttributeDeclarationCollection attributes, s continue; } - GenerateAttributeDeclarationsStart(attributes); + GenerateAttributeDeclarationsStart(); if (prefix != null) { Output.Write(prefix); @@ -2609,7 +2609,7 @@ private void GenerateAttributes(CodeAttributeDeclarationCollection attributes, s } Output.Write(')'); - GenerateAttributeDeclarationsEnd(attributes); + GenerateAttributeDeclarationsEnd(); if (inLine) { Output.Write(' '); diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs index 78a7efb0c8381..ed73caf55325d 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs @@ -65,7 +65,6 @@ internal void ValidateIdentifiers(CodeObject e) private void ValidateTypeMember(CodeTypeMember e) { - ValidateCommentStatements(e.Comments); ValidateCodeDirectives(e.StartDirectives); ValidateCodeDirectives(e.EndDirectives); @@ -132,7 +131,6 @@ private void ValidateNamespaces(CodeCompileUnit e) private void ValidateNamespace(CodeNamespace e) { - ValidateCommentStatements(e.Comments); ValidateNamespaceStart(e); ValidateNamespaceImports(e); ValidateTypes(e); @@ -317,8 +315,6 @@ private void ValidateProperty(CodeMemberProperty e) private void ValidateMemberMethod(CodeMemberMethod e) { - ValidateCommentStatements(e.Comments); - ValidateTypeParameters(e.TypeParameters); ValidateTypeReferences(e.ImplementationTypes); @@ -374,7 +370,6 @@ private void ValidateMethod(CodeMemberMethod e) private void ValidateTypeStart(CodeTypeDeclaration e) { - ValidateCommentStatements(e.Comments); if (e.CustomAttributes.Count > 0) { ValidateAttributes(e.CustomAttributes); @@ -395,18 +390,6 @@ private void ValidateTypeStart(CodeTypeDeclaration e) } } - private static void ValidateCommentStatements(CodeCommentStatementCollection e) - { - foreach (CodeCommentStatement comment in e) - { - ValidateCommentStatement(comment); - } - } - - private static void ValidateCommentStatement(CodeCommentStatement e) - { - } - private void ValidateStatement(CodeStatement e) { if (e is null) @@ -419,7 +402,7 @@ private void ValidateStatement(CodeStatement e) if (e is CodeCommentStatement) { - ValidateCommentStatement((CodeCommentStatement)e); + // nothing } else if (e is CodeMethodReturnStatement) { diff --git a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilderOfT.cs b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilderOfT.cs index ace4c8b7a8838..f607ec0f79ff6 100644 --- a/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilderOfT.cs +++ b/src/libraries/System.ComponentModel.Composition.Registration/src/System/ComponentModel/Composition/Registration/PartBuilderOfT.cs @@ -29,12 +29,12 @@ public bool VerifyPropertyInfo(PropertyInfo pi) return pi == _propertyInfo; } - public void ConfigureImport(PropertyInfo propertyInfo, ImportBuilder importBuilder) + public void ConfigureImport(PropertyInfo _, ImportBuilder importBuilder) { _configureImport?.Invoke(importBuilder); } - public void ConfigureExport(PropertyInfo propertyInfo, ExportBuilder exportBuilder) + public void ConfigureExport(PropertyInfo _, ExportBuilder exportBuilder) { _configureExport?.Invoke(exportBuilder); } @@ -80,7 +80,7 @@ public ConstructorExpressionAdapter(Expression> ParseSelectConstructor(selectConstructor); } - public ConstructorInfo SelectConstructor(ConstructorInfo[] constructorInfos) + public ConstructorInfo SelectConstructor(ConstructorInfo[] _) { return _constructorInfo; } diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewGenerator.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewGenerator.cs index 8c81b20d1ad7c..47640c87d9387 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewGenerator.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/MetadataViewGenerator.cs @@ -76,7 +76,7 @@ internal static class MetadataViewGenerator private static readonly ConstructorInfo ObjectCtor = typeof(object).GetConstructor(Type.EmptyTypes)!; // Must be called with _lock held - private static ModuleBuilder GetProxyModuleBuilder(bool requiresCritical) + private static ModuleBuilder GetProxyModuleBuilder() { if (transparentProxyModuleBuilder == null) { @@ -184,9 +184,8 @@ private static void GenerateLocalAssignmentFromFlag(this ILGenerator IL, LocalBu Type? proxyType; TypeBuilder proxyTypeBuilder; Type[] interfaces = { viewType }; - bool requiresCritical = false; - var proxyModuleBuilder = GetProxyModuleBuilder(requiresCritical); + var proxyModuleBuilder = GetProxyModuleBuilder(); proxyTypeBuilder = proxyModuleBuilder.DefineType( $"_proxy_{viewType.FullName}_{Guid.NewGuid()}", TypeAttributes.Public, diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ExtendedPropertyDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ExtendedPropertyDescriptor.cs index c835b2ffd185b..62e6476237e5f 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ExtendedPropertyDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ExtendedPropertyDescriptor.cs @@ -80,7 +80,7 @@ public override bool CanResetValue(object comp) /// /// Retrieves the data type of the property. /// - public override Type PropertyType => _extenderInfo.ExtenderGetType(_provider); + public override Type PropertyType => _extenderInfo.ExtenderGetType(); /// /// Retrieves the display name of the property. This is the name that will diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs index f1656f7658786..2a6ad44ebc26e 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectPropertyDescriptor.cs @@ -536,7 +536,7 @@ internal bool ExtenderCanResetValue(IExtenderProvider provider, object component internal Type? ExtenderGetReceiverType() => _receiverType; - internal Type ExtenderGetType(IExtenderProvider provider) => PropertyType; + internal Type ExtenderGetType() => PropertyType; internal object? ExtenderGetValue(IExtenderProvider? provider, object? component) { diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.ReflectedTypeData.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.ReflectedTypeData.cs index 310c8e3008923..11449f7489ffc 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.ReflectedTypeData.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.ReflectedTypeData.cs @@ -149,7 +149,7 @@ internal AttributeCollection GetAttributes() /// /// Retrieves the class name for our type. /// - internal string? GetClassName(object? instance) => _type.FullName; + internal string? GetClassName() => _type.FullName; /// /// Retrieves the component name from the site. diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs index 02787cb44f4a5..300573f322049 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/ReflectTypeDescriptionProvider.cs @@ -351,7 +351,7 @@ internal AttributeCollection GetAttributes([DynamicallyAccessedMembers(Dynamical internal string? GetClassName([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type) { ReflectedTypeData td = GetTypeData(type, true)!; - return td.GetClassName(null); + return td.GetClassName(); } /// @@ -465,7 +465,7 @@ internal EventDescriptorCollection GetEvents([DynamicallyAccessedMembers(Dynamic /// Retrieves custom extender attributes. We don't support /// extender attributes, so we always return an empty collection. /// - internal static AttributeCollection GetExtendedAttributes(object instance) + internal static AttributeCollection GetExtendedAttributes() { return AttributeCollection.Empty; } @@ -510,7 +510,7 @@ internal TypeConverter GetExtendedConverter(object instance) /// /// Return the default property. /// - internal static PropertyDescriptor? GetExtendedDefaultProperty(object instance) + internal static PropertyDescriptor? GetExtendedDefaultProperty() { return null; // extender properties are never the default. } @@ -527,7 +527,7 @@ internal TypeConverter GetExtendedConverter(object instance) /// /// Retrieves the events for this type. /// - internal static EventDescriptorCollection GetExtendedEvents(object instance) + internal static EventDescriptorCollection GetExtendedEvents() { return EventDescriptorCollection.Empty; } @@ -790,9 +790,9 @@ private static IExtenderProvider[] GetExtenders(ICollection components, object i /// /// Retrieves the owner for a property. /// - internal static object GetExtendedPropertyOwner(object instance, PropertyDescriptor? pd) + internal static object GetExtendedPropertyOwner(object instance) { - return GetPropertyOwner(instance.GetType(), instance, pd); + return GetPropertyOwner(instance.GetType(), instance); } ////////////////////////////////////////////////////////// @@ -872,7 +872,7 @@ internal PropertyDescriptorCollection GetProperties([DynamicallyAccessedMembers( /// /// Retrieves the owner for a property. /// - internal static object GetPropertyOwner(Type type, object instance, PropertyDescriptor? pd) + internal static object GetPropertyOwner(Type type, object instance) { return TypeDescriptor.GetAssociation(type, instance); } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs index 7b1fdc0cf643d..8d88809fc74e4 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/TypeDescriptor.cs @@ -664,7 +664,7 @@ public static AttributeCollection GetAttributes(object component, bool noCustomT if (extDesc != null) { ICollection extResults = extDesc.GetAttributes(); - results = PipelineMerge(PIPELINE_ATTRIBUTES, results, extResults, component, null); + results = PipelineMerge(PIPELINE_ATTRIBUTES, results, extResults, null); } } else @@ -682,7 +682,7 @@ public static AttributeCollection GetAttributes(object component, bool noCustomT if (extDesc != null) { ICollection extResults = extDesc.GetAttributes(); - results = PipelineMerge(PIPELINE_ATTRIBUTES, results, extResults, component, cache); + results = PipelineMerge(PIPELINE_ATTRIBUTES, results, extResults, cache); } results = PipelineFilter(PIPELINE_ATTRIBUTES, results, component, cache); @@ -1077,13 +1077,13 @@ public static EventDescriptorCollection GetEvents(object component, Attribute[]? if (extDesc != null) { ICollection extResults = extDesc.GetEvents(attributes); - results = PipelineMerge(PIPELINE_EVENTS, results, extResults, component, null); + results = PipelineMerge(PIPELINE_EVENTS, results, extResults, null); } } else { results = PipelineFilter(PIPELINE_EVENTS, results, component, null); - results = PipelineAttributeFilter(PIPELINE_EVENTS, results, attributes, component, null); + results = PipelineAttributeFilter(PIPELINE_EVENTS, results, attributes, null); } } else @@ -1095,11 +1095,11 @@ public static EventDescriptorCollection GetEvents(object component, Attribute[]? if (extDesc != null) { ICollection extResults = extDesc.GetEvents(attributes); - results = PipelineMerge(PIPELINE_EVENTS, results, extResults, component, cache); + results = PipelineMerge(PIPELINE_EVENTS, results, extResults, cache); } results = PipelineFilter(PIPELINE_EVENTS, results, component, cache); - results = PipelineAttributeFilter(PIPELINE_EVENTS, results, attributes, component, cache); + results = PipelineAttributeFilter(PIPELINE_EVENTS, results, attributes, cache); } if (!(results is EventDescriptorCollection evts)) @@ -1317,13 +1317,13 @@ private static PropertyDescriptorCollection GetPropertiesImpl(object component, if (extDesc != null) { ICollection extResults = noAttributes ? extDesc.GetProperties() : extDesc.GetProperties(attributes); - results = PipelineMerge(PIPELINE_PROPERTIES, results, extResults, component, null); + results = PipelineMerge(PIPELINE_PROPERTIES, results, extResults, null); } } else { results = PipelineFilter(PIPELINE_PROPERTIES, results, component, null); - results = PipelineAttributeFilter(PIPELINE_PROPERTIES, results, attributes, component, null); + results = PipelineAttributeFilter(PIPELINE_PROPERTIES, results, attributes, null); } } else @@ -1335,11 +1335,11 @@ private static PropertyDescriptorCollection GetPropertiesImpl(object component, if (extDesc != null) { ICollection extResults = noAttributes ? extDesc.GetProperties() : extDesc.GetProperties(attributes); - results = PipelineMerge(PIPELINE_PROPERTIES, results, extResults, component, cache); + results = PipelineMerge(PIPELINE_PROPERTIES, results, extResults, cache); } results = PipelineFilter(PIPELINE_PROPERTIES, results, component, cache); - results = PipelineAttributeFilter(PIPELINE_PROPERTIES, results, attributes, component, cache); + results = PipelineAttributeFilter(PIPELINE_PROPERTIES, results, attributes, cache); } if (!(results is PropertyDescriptorCollection props)) @@ -1648,7 +1648,7 @@ private static void NodeRemove(object key, TypeDescriptionProvider provider) /// user-defined filter. /// [RequiresUnreferencedCode(AttributeCollection.FilterRequiresUnreferencedCodeMessage)] - private static ICollection PipelineAttributeFilter(int pipelineType, ICollection members, Attribute[]? filter, object instance, IDictionary? cache) + private static ICollection PipelineAttributeFilter(int pipelineType, ICollection members, Attribute[]? filter, IDictionary? cache) { Debug.Assert(pipelineType != PIPELINE_ATTRIBUTES, "PipelineAttributeFilter is not supported for attributes"); @@ -1958,7 +1958,7 @@ private static ICollection PipelineInitialize(int pipelineType, ICollection memb /// merges extended metdata with primary metadata, and stores it in /// the cache if it is available. /// - private static ICollection PipelineMerge(int pipelineType, ICollection primary, ICollection secondary, object instance, IDictionary? cache) + private static ICollection PipelineMerge(int pipelineType, ICollection primary, ICollection secondary, IDictionary? cache) { // If there is no secondary collection, there is nothing to merge. if (secondary == null || secondary.Count == 0) @@ -3160,7 +3160,7 @@ AttributeCollection ICustomTypeDescriptor.GetAttributes() TypeDescriptionProvider p = _node.Provider; if (p is ReflectTypeDescriptionProvider) { - return ReflectTypeDescriptionProvider.GetExtendedAttributes(_instance); + return ReflectTypeDescriptionProvider.GetExtendedAttributes(); } ICustomTypeDescriptor desc = p.GetExtendedTypeDescriptor(_instance); @@ -3269,7 +3269,7 @@ TypeConverter ICustomTypeDescriptor.GetConverter() TypeDescriptionProvider p = _node.Provider; if (p is ReflectTypeDescriptionProvider) { - return ReflectTypeDescriptionProvider.GetExtendedDefaultProperty(_instance); + return ReflectTypeDescriptionProvider.GetExtendedDefaultProperty(); } ICustomTypeDescriptor desc = p.GetExtendedTypeDescriptor(_instance); @@ -3311,7 +3311,7 @@ EventDescriptorCollection ICustomTypeDescriptor.GetEvents() TypeDescriptionProvider p = _node.Provider; if (p is ReflectTypeDescriptionProvider) { - return ReflectTypeDescriptionProvider.GetExtendedEvents(_instance); + return ReflectTypeDescriptionProvider.GetExtendedEvents(); } ICustomTypeDescriptor desc = p.GetExtendedTypeDescriptor(_instance); @@ -3337,7 +3337,7 @@ EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[]? attribute // are accessed through our pipeline code, which always filters before // returning. So any filter we do here is redundant. Note that we do // pass a valid filter to a custom descriptor so it can optimize if it wants. - EventDescriptorCollection events = ReflectTypeDescriptionProvider.GetExtendedEvents(_instance); + EventDescriptorCollection events = ReflectTypeDescriptionProvider.GetExtendedEvents(); return events; } @@ -3411,7 +3411,7 @@ object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor? pd) if (p is ReflectTypeDescriptionProvider) { - return ReflectTypeDescriptionProvider.GetExtendedPropertyOwner(_instance, pd); + return ReflectTypeDescriptionProvider.GetExtendedPropertyOwner(_instance); } ICustomTypeDescriptor desc = p.GetExtendedTypeDescriptor(_instance); @@ -3753,7 +3753,7 @@ public PropertyDescriptorCollection GetProperties(Attribute[]? attributes) object? owner; if (p is ReflectTypeDescriptionProvider) { - owner = ReflectTypeDescriptionProvider.GetPropertyOwner(_objectType, _instance!, pd); + owner = ReflectTypeDescriptionProvider.GetPropertyOwner(_objectType, _instance!); } else { diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilderOfT.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilderOfT.cs index 73d2c5b77cfbe..66a4713a8cc2b 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilderOfT.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/PartConventionBuilderOfT.cs @@ -88,12 +88,12 @@ public bool VerifyPropertyInfo(PropertyInfo pi) return pi == _propertyInfo; } - public void ConfigureImport(PropertyInfo propertyInfo, ImportConventionBuilder importBuilder) + public void ConfigureImport(PropertyInfo _, ImportConventionBuilder importBuilder) { _configureImport?.Invoke(importBuilder); } - public void ConfigureExport(PropertyInfo propertyInfo, ExportConventionBuilder exportBuilder) + public void ConfigureExport(PropertyInfo _, ExportConventionBuilder exportBuilder) { _configureExport?.Invoke(exportBuilder); } @@ -139,7 +139,7 @@ public ConstructorExpressionAdapter(Expression constructorInfos) + public ConstructorInfo SelectConstructor(IEnumerable _) { return _constructorInfo; } diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredExport.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredExport.cs index be99829e46c95..ea5b1a54a6120 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredExport.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredExport.cs @@ -38,7 +38,7 @@ public ExportDescriptorPromise GetExportDescriptorPromise( () => Part.GetDependencies(definitionAccessor), deps => { - var activator = Part.GetActivator(definitionAccessor, deps); + var activator = Part.GetActivator(deps); return GetExportDescriptor(activator); }); } diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredPart.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredPart.cs index 6fc4defe9b684..206483b25db40 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredPart.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/DiscoveredPart.cs @@ -161,7 +161,7 @@ private ConstructorInfo GetConstructorInfoFromGenericType(TypeInfo type) return constructor; } - public CompositeActivator GetActivator(DependencyAccessor definitionAccessor, IEnumerable dependencies) + public CompositeActivator GetActivator(IEnumerable dependencies) { if (_partActivator != null) return _partActivator; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs index b27a4d2dc5d06..112527d7bdddc 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs @@ -709,15 +709,6 @@ private object GetPropertyValue(string propertyName) } } - /// - /// Returns true if this is a clickonce deployed app. - /// - internal static bool IsClickOnceDeployed(AppDomain appDomain) - { - // Always false for .NET Core - return false; - } - /// /// Only those settings class properties that have a SettingAttribute on them are /// treated as settings. This routine filters out other properties. diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs index 0bc12a813e0a7..844b5568827d4 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/BaseConfigurationRecord.cs @@ -1936,7 +1936,7 @@ private void ScanFactoriesRecursive(XmlUtil xmlUtil, string parentConfigKey, Has case SectionAllowDefinitionAttribute: try { - allowDefinition = AllowDefinitionToEnum(xmlUtil.Reader.Value, xmlUtil); + allowDefinition = AllowDefinitionToEnum(xmlUtil); } catch (ConfigurationException ce) { @@ -2114,7 +2114,7 @@ internal static ConfigurationAllowExeDefinition AllowExeDefinitionToEnum(string xmlUtil), }; - internal static ConfigurationAllowDefinition AllowDefinitionToEnum(string allowDefinition, XmlUtil xmlUtil) => + internal static ConfigurationAllowDefinition AllowDefinitionToEnum(XmlUtil xmlUtil) => xmlUtil.Reader.Value switch { AllowDefinitionEverywhere => ConfigurationAllowDefinition.Everywhere, @@ -2450,7 +2450,7 @@ private void ScanSectionsRecursive( string rawXml = null; string configSource = null; string configSourceStreamName = null; - object configSourceStreamVersion = null; + object configSourceStreamVersion; string protectionProviderName = null; OverrideMode sectionLockMode = OverrideMode.Inherit; OverrideMode sectionChildLockMode = OverrideMode.Inherit; @@ -2662,7 +2662,7 @@ private void ScanSectionsRecursive( SectionXmlInfo sectionXmlInfo = new SectionXmlInfo( configKey, _configPath, targetConfigPath, locationSubPath, fileName, lineNumber, ConfigStreamInfo.StreamVersion, rawXml, - configSource, configSourceStreamName, configSourceStreamVersion, + configSource, configSourceStreamName, protectionProviderName, overrideMode, skipInChildApps); if (locationSubPath == null) @@ -3313,11 +3313,11 @@ private void ValidateUniqueConfigSource( } } - ValidateUniqueChildConfigSource(configKey, configSourceStreamName, configSourceArg, errorInfo); + ValidateUniqueChildConfigSource(configSourceStreamName, configSourceArg, errorInfo); } protected void ValidateUniqueChildConfigSource( - string configKey, string configSourceStreamName, string configSourceArg, IConfigErrorInfo errorInfo) + string configSourceStreamName, string configSourceArg, IConfigErrorInfo errorInfo) { // Detect if a parent config file is using the same config source stream. BaseConfigurationRecord current = IsLocationConfig ? _parent._parent : _parent; @@ -3379,7 +3379,7 @@ internal void HlClearResultRecursive(string configKey, bool forceEvaluatation) SectionXmlInfo sectionXmlInfo = new SectionXmlInfo( configKey, _configPath, _configPath, null, ConfigStreamInfo.StreamName, 0, null, null, - null, null, null, + null, null, null, OverrideModeSetting.s_locationDefault, false); SectionInput fileInput = new SectionInput(sectionXmlInfo, null); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs index de966e6160743..55122172ea4a4 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs @@ -555,7 +555,7 @@ internal void ChangeConfigSource( if (newConfigSourceStreamName != null) { // Ensure that no parent is using the same config source stream - ValidateUniqueChildConfigSource(sectionInformation.ConfigKey, newConfigSourceStreamName, newConfigSource, + ValidateUniqueChildConfigSource(newConfigSourceStreamName, newConfigSource, null); StreamInfo streamInfo = (StreamInfo)_streamInfoUpdates[newConfigSourceStreamName]; @@ -1842,7 +1842,7 @@ private void UpdateRecords() SectionXmlInfo sectionXmlInfo = new SectionXmlInfo( sectionRecord.ConfigKey, definitionConfigPath, _configPath, _locationSubPath, ConfigStreamInfo.StreamName, 0, ConfigStreamInfo.StreamVersion, null, - configSource, configSourceStreamName, configSourceStreamVersion, + configSource, configSourceStreamName, configSection.SectionInformation.ProtectionProviderName, configSection.SectionInformation.OverrideModeSetting, !configSection.SectionInformation.InheritInChildApplications); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/RuntimeConfigurationRecord.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/RuntimeConfigurationRecord.cs index 9f9ae18faecfe..086b06a076e3b 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/RuntimeConfigurationRecord.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/RuntimeConfigurationRecord.cs @@ -44,7 +44,7 @@ protected override object CreateSection(bool inputIsTrusted, FactoryRecord facto RuntimeConfigurationFactory factory = (RuntimeConfigurationFactory)factoryRecord.Factory; // Use the factory to create a section. - object config = factory.CreateSection(inputIsTrusted, this, factoryRecord, sectionRecord, parentConfig, + object config = factory.CreateSection(this, factoryRecord, sectionRecord, parentConfig, reader); return config; @@ -135,7 +135,7 @@ private static void CheckForLockAttributes(string sectionName, XmlNode xmlNode) if (xmlNode.NodeType == XmlNodeType.Element) CheckForLockAttributes(sectionName, child); } - internal object CreateSection(bool inputIsTrusted, RuntimeConfigurationRecord configRecord, + internal object CreateSection(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, object parentConfig, ConfigXmlReader reader) { object config; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionXmlInfo.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionXmlInfo.cs index a21c498d5d151..5449a74e9f46a 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionXmlInfo.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionXmlInfo.cs @@ -12,7 +12,7 @@ internal sealed class SectionXmlInfo : IConfigErrorInfo internal SectionXmlInfo( string configKey, string definitionConfigPath, string targetConfigPath, string subPath, string filename, int lineNumber, object streamVersion, - string rawXml, string configSource, string configSourceStreamName, object configSourceStreamVersion, + string rawXml, string configSource, string configSourceStreamName, string protectionProviderName, OverrideModeSetting overrideMode, bool skipInChildApps) { ConfigKey = configKey; diff --git a/src/libraries/System.Console/src/System/ConsolePal.Android.cs b/src/libraries/System.Console/src/System/ConsolePal.Android.cs index 4cecdac6eceaa..7894b5e2022c2 100644 --- a/src/libraries/System.Console/src/System/ConsolePal.Android.cs +++ b/src/libraries/System.Console/src/System/ConsolePal.Android.cs @@ -5,6 +5,8 @@ using System.Text; using System.Runtime.InteropServices; +#pragma warning disable IDE0060 + namespace System { internal sealed unsafe class LogcatStream : CachedConsoleStream diff --git a/src/libraries/System.Console/src/System/ConsolePal.Unix.cs b/src/libraries/System.Console/src/System/ConsolePal.Unix.cs index 428fcbab0e701..543f15e71c85c 100644 --- a/src/libraries/System.Console/src/System/ConsolePal.Unix.cs +++ b/src/libraries/System.Console/src/System/ConsolePal.Unix.cs @@ -83,8 +83,8 @@ static SyncTextReader EnsureInitialized() SyncTextReader reader = SyncTextReader.GetSynchronizedTextReader( new StdInReader( - encoding: Console.InputEncoding, - bufferSize: InteractiveBufferSize)); + encoding: Console.InputEncoding + )); // Don't overwrite a set reader. // The reader doesn't own resources, so we don't need to dispose @@ -219,11 +219,6 @@ public static void Beep() } } - public static void Beep(int frequency, int duration) - { - throw new PlatformNotSupportedException(); - } - public static void Clear() { if (!Console.IsOutputRedirected) @@ -312,11 +307,6 @@ public static int BufferHeight set { throw new PlatformNotSupportedException(); } } - public static void SetBufferSize(int width, int height) - { - throw new PlatformNotSupportedException(); - } - public static int LargestWindowWidth { get { return WindowWidth; } @@ -385,11 +375,6 @@ private static void GetWindowSize(out int width, out int height) } } - public static void SetWindowPosition(int left, int top) - { - throw new PlatformNotSupportedException(); - } - public static void SetWindowSize(int width, int height) { lock (Console.Out) @@ -683,16 +668,6 @@ static void TransferBytes(ReadOnlySpan src, StdInReader dst) } } - public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop) - { - throw new PlatformNotSupportedException(); - } - - public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor) - { - throw new PlatformNotSupportedException(); - } - /// /// Gets whether the specified file descriptor was redirected. /// It's considered redirected if it doesn't refer to a terminal. @@ -737,6 +712,27 @@ private static Encoding GetConsoleEncoding() Encoding.Default; } +#pragma warning disable IDE0060 + public static void Beep(int frequency, int duration) + { + throw new PlatformNotSupportedException(); + } + + public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop) + { + throw new PlatformNotSupportedException(); + } + + public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor) + { + throw new PlatformNotSupportedException(); + } + + public static void SetBufferSize(int width, int height) + { + throw new PlatformNotSupportedException(); + } + public static void SetConsoleInputEncoding(Encoding enc) { // No-op. @@ -749,6 +745,13 @@ public static void SetConsoleOutputEncoding(Encoding enc) // There is no good way to set the terminal console encoding. } + public static void SetWindowPosition(int left, int top) + { + throw new PlatformNotSupportedException(); + } + +#pragma warning restore IDE0060 + /// /// Refreshes the foreground and background colors in use by the terminal by resetting /// the colors and then reissuing commands for both foreground and background, if necessary. diff --git a/src/libraries/System.Console/src/System/ConsolePal.WebAssembly.cs b/src/libraries/System.Console/src/System/ConsolePal.WebAssembly.cs index 0594f0f393063..abab79436cac1 100644 --- a/src/libraries/System.Console/src/System/ConsolePal.WebAssembly.cs +++ b/src/libraries/System.Console/src/System/ConsolePal.WebAssembly.cs @@ -7,6 +7,7 @@ using System.Runtime.InteropServices.JavaScript; #pragma warning disable CS0612 // using obsolete members until we finish https://github.com/dotnet/runtime/pull/66304/ +#pragma warning disable IDE0060 namespace System { diff --git a/src/libraries/System.Console/src/System/ConsolePal.iOS.cs b/src/libraries/System.Console/src/System/ConsolePal.iOS.cs index 8794d55aeff86..cd3cead0de067 100644 --- a/src/libraries/System.Console/src/System/ConsolePal.iOS.cs +++ b/src/libraries/System.Console/src/System/ConsolePal.iOS.cs @@ -6,6 +6,8 @@ using System.IO; using System.Text; +#pragma warning disable IDE0060 + namespace System { internal sealed class NSLogStream : CachedConsoleStream diff --git a/src/libraries/System.Console/src/System/IO/StdInReader.cs b/src/libraries/System.Console/src/System/IO/StdInReader.cs index 7b0105c9de087..1f4b416793510 100644 --- a/src/libraries/System.Console/src/System/IO/StdInReader.cs +++ b/src/libraries/System.Console/src/System/IO/StdInReader.cs @@ -29,7 +29,7 @@ internal sealed class StdInReader : TextReader private int _startIndex; // First unprocessed index in the buffer; private int _endIndex; // Index after last unprocessed index in the buffer; - internal StdInReader(Encoding encoding, int bufferSize) + internal StdInReader(Encoding encoding) { _encoding = encoding; _unprocessedBufferToBeRead = new char[encoding.GetMaxCharCount(BytesToBeRead)]; diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs index 58ad998034ae1..a96dd1b7b8db1 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs @@ -558,7 +558,7 @@ private DbCommand? DeleteCommand } } - private void BuildCache(bool closeConnection, DataRow? dataRow, bool useColumnsForParameterNames) + private void BuildCache(bool closeConnection, bool useColumnsForParameterNames) { // Don't bother building the cache if it's done already; wait for // the user to call RefreshSchema first. @@ -1008,7 +1008,7 @@ bool isUpdate { DbSchemaRow row = schemaRows[i]; - if ((null == row) || (0 == row.BaseColumnName.Length) || !IncludeInWhereClause(row, isUpdate)) + if ((null == row) || (0 == row.BaseColumnName.Length) || !IncludeInWhereClause(row)) { continue; } @@ -1320,7 +1320,7 @@ public DbCommand GetInsertCommand(bool useColumnsForParameterNames) internal DbCommand GetInsertCommand(DataRow? dataRow, bool useColumnsForParameterNames) { - BuildCache(true, dataRow, useColumnsForParameterNames); + BuildCache(true, useColumnsForParameterNames); BuildInsertCommand(GetTableMapping(dataRow), dataRow); return InsertCommand!; } @@ -1337,7 +1337,7 @@ public DbCommand GetUpdateCommand(bool useColumnsForParameterNames) internal DbCommand GetUpdateCommand(DataRow? dataRow, bool useColumnsForParameterNames) { - BuildCache(true, dataRow, useColumnsForParameterNames); + BuildCache(true, useColumnsForParameterNames); BuildUpdateCommand(GetTableMapping(dataRow), dataRow); return UpdateCommand!; } @@ -1354,7 +1354,7 @@ public DbCommand GetDeleteCommand(bool useColumnsForParameterNames) internal DbCommand GetDeleteCommand(DataRow? dataRow, bool useColumnsForParameterNames) { - BuildCache(true, dataRow, useColumnsForParameterNames); + BuildCache(true, useColumnsForParameterNames); BuildDeleteCommand(GetTableMapping(dataRow), dataRow); return DeleteCommand!; } @@ -1415,7 +1415,7 @@ private static bool IncludeInUpdateSet(DbSchemaRow row) return (!row.IsAutoIncrement && !row.IsRowVersion && !row.IsHidden && !row.IsReadOnly); } - private bool IncludeInWhereClause(DbSchemaRow row, bool isUpdate) + private bool IncludeInWhereClause(DbSchemaRow row) { bool flag = IncrementWhereCount(row); if (flag && row.IsHidden) @@ -1598,7 +1598,7 @@ private void RowUpdatingHandlerBuilder(RowUpdatingEventArgs rowUpdatingEvent) { // the Update method will close the connection if command was null and returned command.Connection is same as SelectCommand.Connection DataRow datarow = rowUpdatingEvent.Row; - BuildCache(false, datarow, false); + BuildCache(false, false); DbCommand? command; switch (rowUpdatingEvent.StatementType) diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaRow.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaRow.cs index 621f41a8b312d..867a04197d1a3 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaRow.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DBSchemaRow.cs @@ -29,7 +29,7 @@ internal static DbSchemaRow[] GetSortedSchemaRows(DataTable dataTable, bool retu DbSchemaTable schemaTable = new DbSchemaTable(dataTable, returnProviderSpecificTypes); - DataRow[] dataRows = SelectRows(dataTable, returnProviderSpecificTypes); + DataRow[] dataRows = SelectRows(dataTable); Debug.Assert(null != dataRows, "GetSchemaRows: unexpected null dataRows"); DbSchemaRow[] schemaRows = new DbSchemaRow[dataRows.Length]; @@ -43,7 +43,7 @@ internal static DbSchemaRow[] GetSortedSchemaRows(DataTable dataTable, bool retu [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Filter expression is null.")] - private static DataRow[] SelectRows(DataTable dataTable, bool returnProviderSpecificTypes) + private static DataRow[] SelectRows(DataTable dataTable) { const DataViewRowState rowStates = DataViewRowState.Unchanged | DataViewRowState.Added | DataViewRowState.ModifiedCurrent; return dataTable.Select(null, "ColumnOrdinal ASC", rowStates); diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs index 2794c43440932..a399e812a406b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataAdapter.cs @@ -410,7 +410,7 @@ protected virtual DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType, bool restoreNullConnection = (null == command.Connection); try { - IDbConnection activeConnection = DbDataAdapter.GetConnection3(this, command, ADP.FillSchema); + IDbConnection activeConnection = DbDataAdapter.GetConnection3(command, ADP.FillSchema); ConnectionState originalState = ConnectionState.Open; try @@ -616,7 +616,7 @@ private int FillInternal(DataSet? dataset, DataTable[]? datatables, int startRec bool restoreNullConnection = (null == command.Connection); try { - IDbConnection activeConnection = DbDataAdapter.GetConnection3(this, command, ADP.Fill); + IDbConnection activeConnection = DbDataAdapter.GetConnection3(command, ADP.Fill); ConnectionState originalState = ConnectionState.Open; // the default is MissingSchemaAction.Add, the user must explicitly @@ -1215,7 +1215,7 @@ protected virtual int Update(DataRow[] dataRows, DataTableMapping tableMapping) } else if (null != dataCommand) { - IDbConnection connection = DbDataAdapter.GetConnection4(this, dataCommand, statementType, isCommandFromRowUpdating); + IDbConnection connection = DbDataAdapter.GetConnection4(dataCommand, statementType, isCommandFromRowUpdating); ConnectionState state = UpdateConnectionOpen(connection, statementType, connections, connectionStates, useSelectConnectionState); if (ConnectionState.Open == state) { @@ -1599,7 +1599,7 @@ private int UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandIn switch (rowUpdatedEvent.Status) { case UpdateStatus.Continue: - cumulativeDataRowsAffected = UpdatedRowStatusContinue(rowUpdatedEvent, batchCommands, commandCount); + cumulativeDataRowsAffected = UpdatedRowStatusContinue(batchCommands, commandCount); break; // return to foreach DataRow case UpdateStatus.ErrorsOccurred: cumulativeDataRowsAffected = UpdatedRowStatusErrors(rowUpdatedEvent, batchCommands, commandCount); @@ -1614,7 +1614,7 @@ private int UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandIn return cumulativeDataRowsAffected; } - private int UpdatedRowStatusContinue(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, int commandCount) + private int UpdatedRowStatusContinue(BatchCommandInfo[] batchCommands, int commandCount) { Debug.Assert(null != batchCommands, "null batchCommands?"); int cumulativeDataRowsAffected = 0; @@ -1692,7 +1692,7 @@ private int UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCom } else { - affected = UpdatedRowStatusContinue(rowUpdatedEvent, batchCommands, commandCount); + affected = UpdatedRowStatusContinue(batchCommands, commandCount); } if (!ContinueUpdateOnError) { @@ -1766,7 +1766,7 @@ private static IDbConnection GetConnection1(DbDataAdapter adapter) return connection; } - private static IDbConnection GetConnection3(DbDataAdapter adapter, IDbCommand command, string method) + private static IDbConnection GetConnection3(IDbCommand command, string method) { Debug.Assert(null != command, "GetConnection3: null command"); Debug.Assert(!string.IsNullOrEmpty(method), "missing method name"); @@ -1778,7 +1778,7 @@ private static IDbConnection GetConnection3(DbDataAdapter adapter, IDbCommand co return connection; } - private static IDbConnection GetConnection4(DbDataAdapter adapter, IDbCommand command, StatementType statementType, bool isCommandFromRowUpdating) + private static IDbConnection GetConnection4(IDbCommand command, StatementType statementType, bool isCommandFromRowUpdating) { Debug.Assert(null != command, "GetConnection4: null command"); IDbConnection? connection = command.Connection; diff --git a/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs b/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs index 1c59093b2bbb5..ac3674f6604f1 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs @@ -1362,7 +1362,7 @@ public virtual MappingType ColumnMapping internal void CheckColumnConstraint(DataRow row, DataRowAction action) { - if (DataTable.UpdatingCurrent(row, action)) + if (DataTable.UpdatingCurrent(action)) { CheckNullable(row); CheckMaxLength(row); @@ -1472,7 +1472,7 @@ internal int Compare(int record1, int record2) return _storage.Compare(record1, record2); } - internal bool CompareValueTo(int record1, object value, bool checkType) + internal bool CompareValueToChecked(int record1, object value) { // this method is used to make sure value and exact type match. int valuesMatch = CompareValueTo(record1, value); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataException.cs b/src/libraries/System.Data.Common/src/System/Data/DataException.cs index d41f5a7a66588..4068e1aa8f4af 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataException.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataException.cs @@ -314,7 +314,6 @@ internal static Exception TraceExceptionWithoutRethrow(Exception e) } internal static Exception _Argument(string error) => TraceExceptionAsReturnValue(new ArgumentException(error)); - internal static Exception _Argument(string paramName, string error) => TraceExceptionAsReturnValue(new ArgumentException(error)); internal static Exception _Argument(string error, Exception? innerException) => TraceExceptionAsReturnValue(new ArgumentException(error, innerException)); private static Exception _ArgumentNull(string paramName, string msg) => TraceExceptionAsReturnValue(new ArgumentNullException(paramName, msg)); internal static Exception _ArgumentOutOfRange(string paramName, string msg) => TraceExceptionAsReturnValue(new ArgumentOutOfRangeException(paramName, msg)); @@ -349,7 +348,7 @@ private static void ThrowDataException(string error, Exception? innerException) public static Exception ArgumentNull(string paramName) => _ArgumentNull(paramName, SR.Format(SR.Data_ArgumentNull, paramName)); public static Exception ArgumentOutOfRange(string paramName) => _ArgumentOutOfRange(paramName, SR.Format(SR.Data_ArgumentOutOfRange, paramName)); public static Exception BadObjectPropertyAccess(string error) => _InvalidOperation(SR.Format(SR.DataConstraint_BadObjectPropertyAccess, error)); - public static Exception ArgumentContainsNull(string paramName) => _Argument(paramName, SR.Format(SR.Data_ArgumentContainsNull, paramName)); + public static Exception ArgumentContainsNull(string paramName) => TraceExceptionAsReturnValue(new ArgumentException(SR.Data_ArgumentContainsNull, paramName)); public static Exception TypeNotAllowed(Type type) => _InvalidOperation(SR.Format(SR.Data_TypeNotAllowed, type.AssemblyQualifiedName)); // diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRowView.cs b/src/libraries/System.Data.Common/src/System/Data/DataRowView.cs index 453049522da43..f2d8c97d7edec 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRowView.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRowView.cs @@ -255,7 +255,7 @@ public void EndEdit() [RequiresUnreferencedCode("PropertyDescriptor's PropertyType cannot be statically discovered. The public parameterless constructor or the 'Default' static field may be trimmed from the Attribute's Type.")] PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[]? attributes) => - (_dataView.Table != null ? _dataView.Table.GetPropertyDescriptorCollection(attributes) : s_zeroPropertyDescriptorCollection); + (_dataView.Table != null ? _dataView.Table.GetPropertyDescriptorCollection() : s_zeroPropertyDescriptorCollection); object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor? pd) => this; #endregion diff --git a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs index f08e12b978d15..66ba6a7950da7 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs @@ -235,7 +235,7 @@ protected void GetSerializationData(SerializationInfo info, StreamingContext con } } - DeserializeDataSetData(info, context, remotingFormat); + DeserializeDataSetData(info, remotingFormat); } @@ -330,7 +330,7 @@ private void SerializeDataSet(SerializationInfo info, StreamingContext context, if (SchemaSerializationMode == SchemaSerializationMode.IncludeSchema) { //DataSet public state properties - SerializeDataSetProperties(info, context); + SerializeDataSetProperties(info); //Tables Count info.AddValue("DataSet.Tables.Count", Tables.Count); @@ -350,28 +350,28 @@ private void SerializeDataSet(SerializationInfo info, StreamingContext context, //Constraints for (int i = 0; i < Tables.Count; i++) { - Tables[i].SerializeConstraints(info, context, i, true); + Tables[i].SerializeConstraints(info, i, true); } //Relations - SerializeRelations(info, context); + SerializeRelations(info); //Expression Columns for (int i = 0; i < Tables.Count; i++) { - Tables[i].SerializeExpressionColumns(info, context, i); + Tables[i].SerializeExpressionColumns(info, i); } } else { //Serialize DataSet public properties. - SerializeDataSetProperties(info, context); + SerializeDataSetProperties(info); } //Rows for (int i = 0; i < Tables.Count; i++) { - Tables[i].SerializeTableData(info, context, i); + Tables[i].SerializeTableData(info, i); } } else @@ -397,7 +397,7 @@ internal void DeserializeDataSet(SerializationInfo info, StreamingContext contex // deserialize schema DeserializeDataSetSchema(info, context, remotingFormat, schemaSerializationMode); // deserialize data - DeserializeDataSetData(info, context, remotingFormat); + DeserializeDataSetData(info, remotingFormat); } // Deserialize schema. @@ -410,7 +410,7 @@ private void DeserializeDataSetSchema(SerializationInfo info, StreamingContext c if (schemaSerializationMode == SchemaSerializationMode.IncludeSchema) { //DataSet public state properties - DeserializeDataSetProperties(info, context); + DeserializeDataSetProperties(info); //Tables Count int tableCount = info.GetInt32("DataSet.Tables.Count"); @@ -431,22 +431,22 @@ private void DeserializeDataSetSchema(SerializationInfo info, StreamingContext c //Constraints for (int i = 0; i < tableCount; i++) { - Tables[i].DeserializeConstraints(info, context, /* table index */i, /* serialize all constraints */ true); // + Tables[i].DeserializeConstraints(info, /* table index */i, /* serialize all constraints */ true); // } //Relations - DeserializeRelations(info, context); + DeserializeRelations(info); //Expression Columns for (int i = 0; i < tableCount; i++) { - Tables[i].DeserializeExpressionColumns(info, context, i); + Tables[i].DeserializeExpressionColumns(info, i); } } else { //DeSerialize DataSet public properties.[Locale, CaseSensitive and EnforceConstraints] - DeserializeDataSetProperties(info, context); + DeserializeDataSetProperties(info); } } else @@ -463,13 +463,13 @@ private void DeserializeDataSetSchema(SerializationInfo info, StreamingContext c // Deserialize all data. [RequiresDynamicCode(RequiresDynamicCodeMessage)] [RequiresUnreferencedCode(RequiresUnreferencedCodeMessage)] - private void DeserializeDataSetData(SerializationInfo info, StreamingContext context, SerializationFormat remotingFormat) + private void DeserializeDataSetData(SerializationInfo info, SerializationFormat remotingFormat) { if (remotingFormat != SerializationFormat.Xml) { for (int i = 0; i < Tables.Count; i++) { - Tables[i].DeserializeTableData(info, context, i); + Tables[i].DeserializeTableData(info, i); } } else @@ -484,7 +484,7 @@ private void DeserializeDataSetData(SerializationInfo info, StreamingContext con } // Serialize just the dataset properties - private void SerializeDataSetProperties(SerializationInfo info, StreamingContext context) + private void SerializeDataSetProperties(SerializationInfo info) { //DataSet basic properties info.AddValue("DataSet.DataSetName", DataSetName); @@ -501,7 +501,7 @@ private void SerializeDataSetProperties(SerializationInfo info, StreamingContext } // DeSerialize dataset properties - private void DeserializeDataSetProperties(SerializationInfo info, StreamingContext context) + private void DeserializeDataSetProperties(SerializationInfo info) { //DataSet basic properties _dataSetName = info.GetString("DataSet.DataSetName")!; @@ -522,7 +522,7 @@ private void DeserializeDataSetProperties(SerializationInfo info, StreamingConte // Gets relation info from the dataset. // ***Schema for Serializing ArrayList of Relations*** // Relations -> [relationName]->[parentTableIndex, parentcolumnIndexes]->[childTableIndex, childColumnIndexes]->[Nested]->[extendedProperties] - private void SerializeRelations(SerializationInfo info, StreamingContext context) + private void SerializeRelations(SerializationInfo info) { ArrayList relationList = new ArrayList(); @@ -558,7 +558,7 @@ private void SerializeRelations(SerializationInfo info, StreamingContext context // Adds relations to the dataset. // ***Schema for Serializing ArrayList of Relations*** // Relations -> [relationName]->[parentTableIndex, parentcolumnIndexes]->[childTableIndex, childColumnIndexes]->[Nested]->[extendedProperties] - private void DeserializeRelations(SerializationInfo info, StreamingContext context) + private void DeserializeRelations(SerializationInfo info) { ArrayList relationList = (ArrayList)info.GetValue("DataSet.Relations", typeof(ArrayList))!; @@ -1676,7 +1676,7 @@ internal void ReadXmlSchema(XmlReader? reader, bool denyResolving) if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI == Keywords.XSDNS) { // load XSD schema and exit - ReadXSDSchema(reader, denyResolving); + ReadXSDSchema(reader); return; } @@ -1720,7 +1720,7 @@ internal void ReadXmlSchema(XmlReader? reader, bool denyResolving) if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI == Keywords.XSDNS) { // load XSD schema and exit - ReadXSDSchema(reader, denyResolving); + ReadXSDSchema(reader); return; } @@ -1782,7 +1782,7 @@ internal static void ReadEndElement(XmlReader reader) } [RequiresUnreferencedCode(RequiresUnreferencedCodeMessage)] - internal void ReadXSDSchema(XmlReader reader, bool denyResolving) + internal void ReadXSDSchema(XmlReader reader) { XmlSchemaSet sSet = new XmlSchemaSet(); @@ -1827,7 +1827,7 @@ internal void ReadXDRSchema(XmlReader reader) XmlDocument xdoc = new XmlDocument(); // we may need this to infer the schema XmlNode schNode = xdoc.ReadNode(reader)!; xdoc.AppendChild(schNode); - XDRSchema schema = new XDRSchema(this, false); + XDRSchema schema = new XDRSchema(this); DataSetName = xdoc.DocumentElement!.LocalName; schema.LoadSchema((XmlElement)schNode, this); } @@ -2088,7 +2088,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, bool denyResolving) if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI == Keywords.XSDNS) { // load XSD schema and exit - ReadXSDSchema(reader, denyResolving); + ReadXSDSchema(reader); return XmlReadMode.ReadSchema; //since the top level element is a schema return } @@ -2146,7 +2146,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, bool denyResolving) if (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI == Keywords.XSDNS) { // load XSD schema and exit - ReadXSDSchema(reader, denyResolving); + ReadXSDSchema(reader); fSchemaFound = true; continue; } @@ -2622,7 +2622,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol if ((mode != XmlReadMode.IgnoreSchema) && (mode != XmlReadMode.InferSchema) && (mode != XmlReadMode.InferTypedSchema)) { - ReadXSDSchema(reader, denyResolving); + ReadXSDSchema(reader); } else { @@ -2684,7 +2684,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol if ((mode != XmlReadMode.IgnoreSchema) && (mode != XmlReadMode.InferSchema) && (mode != XmlReadMode.InferTypedSchema)) { - ReadXSDSchema(reader, denyResolving); + ReadXSDSchema(reader); fSchemaFound = true; } else diff --git a/src/libraries/System.Data.Common/src/System/Data/DataSetUtil.cs b/src/libraries/System.Data.Common/src/System/Data/DataSetUtil.cs index fd125f1cd9bbf..0fff3918a0e24 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataSetUtil.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataSetUtil.cs @@ -15,45 +15,34 @@ internal static void CheckArgumentNull(T argumentValue, string argumentName) } } - private static T TraceException(string trace, T e) - { - Debug.Assert(null != e, "TraceException: null Exception"); - return e; - } - - private static T TraceExceptionAsReturnValue(T e) - { - return TraceException(" '%ls'\n", e); - } - internal static ArgumentException Argument(string message) { - return TraceExceptionAsReturnValue(new ArgumentException(message)); + return new ArgumentException(message); } internal static ArgumentNullException ArgumentNull(string message) { - return TraceExceptionAsReturnValue(new ArgumentNullException(message)); + return new ArgumentNullException(message); } internal static ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName) { - return TraceExceptionAsReturnValue(new ArgumentOutOfRangeException(parameterName, message)); + return new ArgumentOutOfRangeException(parameterName, message); } internal static InvalidCastException InvalidCast(string message) { - return TraceExceptionAsReturnValue(new InvalidCastException(message)); + return new InvalidCastException(message); } internal static InvalidOperationException InvalidOperation(string message) { - return TraceExceptionAsReturnValue(new InvalidOperationException(message)); + return new InvalidOperationException(message); } internal static NotSupportedException NotSupported(string message) { - return TraceExceptionAsReturnValue(new NotSupportedException(message)); + return new NotSupportedException(message); } internal static ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value) diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs index 6e11ea51ca92c..1fa2b52ec5a6f 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs @@ -216,7 +216,7 @@ protected DataTable(SerializationInfo info, StreamingContext context) : this() throw ExceptionBuilder.SerializationFormatBinaryNotSupported(); } - DeserializeDataTable(info, context, isSingleTable, remotingFormat); + DeserializeDataTable(info, isSingleTable, remotingFormat); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", @@ -225,12 +225,12 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte { SerializationFormat remotingFormat = RemotingFormat; bool isSingleTable = context.Context != null ? Convert.ToBoolean(context.Context, CultureInfo.InvariantCulture) : true; - SerializeDataTable(info, context, isSingleTable, remotingFormat); + SerializeDataTable(info, isSingleTable, remotingFormat); } // Serialize the table schema and data. [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - private void SerializeDataTable(SerializationInfo info, StreamingContext context, bool isSingleTable, SerializationFormat remotingFormat) + private void SerializeDataTable(SerializationInfo info, bool isSingleTable, SerializationFormat remotingFormat) { info.AddValue("DataTable.RemotingVersion", new Version(2, 0)); @@ -243,10 +243,10 @@ private void SerializeDataTable(SerializationInfo info, StreamingContext context if (remotingFormat != SerializationFormat.Xml) { //Binary - SerializeTableSchema(info, context, isSingleTable); + SerializeTableSchema(info, isSingleTable); if (isSingleTable) { - SerializeTableData(info, context, 0); + SerializeTableData(info, 0); } } else @@ -294,15 +294,15 @@ private void SerializeDataTable(SerializationInfo info, StreamingContext context // Deserialize the table schema and data. [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - internal void DeserializeDataTable(SerializationInfo info, StreamingContext context, bool isSingleTable, SerializationFormat remotingFormat) + internal void DeserializeDataTable(SerializationInfo info, bool isSingleTable, SerializationFormat remotingFormat) { if (remotingFormat != SerializationFormat.Xml) { //Binary - DeserializeTableSchema(info, context, isSingleTable); + DeserializeTableSchema(info, isSingleTable); if (isSingleTable) { - DeserializeTableData(info, context, 0); + DeserializeTableData(info, 0); ResetIndexes(); } } @@ -336,7 +336,7 @@ internal void DeserializeDataTable(SerializationInfo info, StreamingContext cont // Serialize the columns [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - internal void SerializeTableSchema(SerializationInfo info, StreamingContext context, bool isSingleTable) + internal void SerializeTableSchema(SerializationInfo info, bool isSingleTable) { //DataTable basic properties info.AddValue("DataTable.TableName", TableName); @@ -407,13 +407,13 @@ internal void SerializeTableSchema(SerializationInfo info, StreamingContext cont //Constraints if (isSingleTable) { - SerializeConstraints(info, context, 0, false); + SerializeConstraints(info, 0, false); } } // Deserialize all the Columns [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - internal void DeserializeTableSchema(SerializationInfo info, StreamingContext context, bool isSingleTable) + internal void DeserializeTableSchema(SerializationInfo info, bool isSingleTable) { //DataTable basic properties _tableName = info.GetString("DataTable.TableName")!; @@ -499,7 +499,7 @@ internal void DeserializeTableSchema(SerializationInfo info, StreamingContext co //Constraints if (isSingleTable) { - DeserializeConstraints(info, context, /*table index */ 0, /* serialize all constraints */false); // since single table, send table index as 0, meanwhile passing + DeserializeConstraints(info, /*table index */ 0, /* serialize all constraints */false); // since single table, send table index as 0, meanwhile passing // false for 'allConstraints' means, handle all the constraint related to the table } } @@ -508,7 +508,7 @@ internal void DeserializeTableSchema(SerializationInfo info, StreamingContext co // ***Schema for Serializing ArrayList of Constraints*** // Unique Constraint - ["U"]->[constraintName]->[columnIndexes]->[IsPrimaryKey]->[extendedProperties] // Foriegn Key Constraint - ["F"]->[constraintName]->[parentTableIndex, parentcolumnIndexes]->[childTableIndex, childColumnIndexes]->[AcceptRejectRule, UpdateRule, DeleteRule]->[extendedProperties] - internal void SerializeConstraints(SerializationInfo info, StreamingContext context, int serIndex, bool allConstraints) + internal void SerializeConstraints(SerializationInfo info, int serIndex, bool allConstraints) { if (allConstraints) { @@ -580,7 +580,7 @@ internal void SerializeConstraints(SerializationInfo info, StreamingContext cont // ***Schema for Serializing ArrayList of Constraints*** // Unique Constraint - ["U"]->[constraintName]->[columnIndexes]->[IsPrimaryKey]->[extendedProperties] // Foriegn Key Constraint - ["F"]->[constraintName]->[parentTableIndex, parentcolumnIndexes]->[childTableIndex, childColumnIndexes]->[AcceptRejectRule, UpdateRule, DeleteRule]->[extendedProperties] - internal void DeserializeConstraints(SerializationInfo info, StreamingContext context, int serIndex, bool allConstraints) + internal void DeserializeConstraints(SerializationInfo info, int serIndex, bool allConstraints) { ArrayList constraintList = (ArrayList)info.GetValue(string.Format(CultureInfo.InvariantCulture, "DataTable_{0}.Constraints", serIndex), typeof(ArrayList))!; @@ -651,7 +651,7 @@ internal void DeserializeConstraints(SerializationInfo info, StreamingContext co } // Serialize the expressions on the table - Marked internal so that DataSet deserializer can call into this - internal void SerializeExpressionColumns(SerializationInfo info, StreamingContext context, int serIndex) + internal void SerializeExpressionColumns(SerializationInfo info, int serIndex) { int colCount = Columns.Count; for (int i = 0; i < colCount; i++) @@ -662,7 +662,7 @@ internal void SerializeExpressionColumns(SerializationInfo info, StreamingContex // Deserialize the expressions on the table - Marked internal so that DataSet deserializer can call into this [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - internal void DeserializeExpressionColumns(SerializationInfo info, StreamingContext context, int serIndex) + internal void DeserializeExpressionColumns(SerializationInfo info, int serIndex) { int colCount = Columns.Count; for (int i = 0; i < colCount; i++) @@ -677,7 +677,7 @@ internal void DeserializeExpressionColumns(SerializationInfo info, StreamingCont // Serialize all the Rows. [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - internal void SerializeTableData(SerializationInfo info, StreamingContext context, int serIndex) + internal void SerializeTableData(SerializationInfo info, int serIndex) { //Cache all the column count, row count int colCount = Columns.Count; @@ -763,7 +763,7 @@ internal void SerializeTableData(SerializationInfo info, StreamingContext contex // Deserialize all the Rows. [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - internal void DeserializeTableData(SerializationInfo info, StreamingContext context, int serIndex) + internal void DeserializeTableData(SerializationInfo info, int serIndex) { bool enforceConstraintsOrg = _enforceConstraints; bool inDataLoadOrg = _inDataLoad; @@ -3930,7 +3930,7 @@ internal static void SilentlySetValue(DataRow dr, DataColumn dc, DataRowVersion } else { - equalValues = dc.CompareValueTo(record, newValue, true); + equalValues = dc.CompareValueToChecked(record, newValue); } // if expression has changed @@ -4105,7 +4105,7 @@ internal void RollbackRow(DataRow row) { try { - if (UpdatingCurrent(eRow, eAction) && (IsTypedDataTable || (null != _onRowChangedDelegate))) + if (UpdatingCurrent(eAction) && (IsTypedDataTable || (null != _onRowChangedDelegate))) { args = OnRowChanged(args, eRow, eAction); } @@ -4128,7 +4128,7 @@ internal void RollbackRow(DataRow row) private DataRowChangeEventArgs? RaiseRowChanging(DataRowChangeEventArgs? args, DataRow eRow, DataRowAction eAction) { - if (UpdatingCurrent(eRow, eAction) && (IsTypedDataTable || (null != _onRowChangingDelegate))) + if (UpdatingCurrent(eAction) && (IsTypedDataTable || (null != _onRowChangingDelegate))) { eRow._inChangingEvent = true; @@ -4811,7 +4811,7 @@ internal DataRow UpdatingAdd(object?[] values) return Rows.Add(values); } - internal static bool UpdatingCurrent(DataRow row, DataRowAction action) + internal static bool UpdatingCurrent(DataRowAction action) { return (action == DataRowAction.Add || action == DataRowAction.Change || action == DataRowAction.Rollback || action == DataRowAction.ChangeOriginal || @@ -4892,7 +4892,7 @@ internal void UpdatePropertyDescriptorCollectionCache() /// additional properties. The returned array of properties will be /// filtered by the given set of attributes. /// - internal PropertyDescriptorCollection GetPropertyDescriptorCollection(Attribute[]? attributes) + internal PropertyDescriptorCollection GetPropertyDescriptorCollection() { if (_propertyDescriptorCollectionCache == null) { @@ -6370,7 +6370,7 @@ private void ReadXmlDiffgram(XmlReader reader) } [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - internal void ReadXSDSchema(XmlReader reader, bool denyResolving) + internal void ReadXSDSchema(XmlReader reader) { XmlSchemaSet sSet = new XmlSchemaSet(); while (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI == Keywords.XSDNS) diff --git a/src/libraries/System.Data.Common/src/System/Data/DataView.cs b/src/libraries/System.Data.Common/src/System/Data/DataView.cs index 1fe9fe049922a..f42a833dc34fa 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataView.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataView.cs @@ -1181,7 +1181,7 @@ PropertyDescriptorCollection System.ComponentModel.ITypedList.GetItemProperties( { if (listAccessors == null || listAccessors.Length == 0) { - return _table.GetPropertyDescriptorCollection(null); + return _table.GetPropertyDescriptorCollection(); } else { @@ -1194,7 +1194,7 @@ PropertyDescriptorCollection System.ComponentModel.ITypedList.GetItemProperties( DataTable? foundTable = dataSet.FindTable(_table, listAccessors, 0); if (foundTable != null) { - return foundTable.GetPropertyDescriptorCollection(null); + return foundTable.GetPropertyDescriptorCollection(); } } } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataViewManager.cs b/src/libraries/System.Data.Common/src/System/Data/DataViewManager.cs index 46b7d8b32dfe3..4ab7dd2def292 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataViewManager.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataViewManager.cs @@ -296,7 +296,7 @@ PropertyDescriptorCollection System.ComponentModel.ITypedList.GetItemProperties( DataTable? table = dataSet.FindTable(null, listAccessors, 0); if (table != null) { - return table.GetPropertyDescriptorCollection(null); + return table.GetPropertyDescriptorCollection(); } } return new PropertyDescriptorCollection(null); diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs index 9b0654bdadb8a..11aa6c3dc27d3 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/BinaryNode.cs @@ -323,7 +323,7 @@ private object EvalBinaryOp(int op, ExpressionNode left, ExpressionNode right, D if (leftIsSqlType || rightIsSqlType) { - resultType = ResultSqlType(leftStorage, rightStorage, (left is ConstNode), (right is ConstNode), op); + resultType = ResultSqlType(leftStorage, rightStorage, op); } else { @@ -1369,7 +1369,7 @@ internal static StorageType ResultType(StorageType left, StorageType right, bool return result; } - internal static StorageType ResultSqlType(StorageType left, StorageType right, bool lc, bool rc, int op) + internal static StorageType ResultSqlType(StorageType left, StorageType right, int op) { int leftPrecedence = (int)GetPrecedence(left); if (leftPrecedence == (int)DataTypePrecedence.Error) diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/DataExpression.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/DataExpression.cs index 94d13b5c0b4c9..0d36491d7ed85 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/DataExpression.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/DataExpression.cs @@ -147,7 +147,7 @@ internal object Evaluate(DataRow? row, DataRowVersion version) catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { ExceptionBuilder.TraceExceptionForCapture(e); - throw ExprException.DatavalueConversion(result, _dataType!, e); + throw ExprException.DatavalueConversion(result, _dataType!); } } } @@ -270,11 +270,11 @@ internal static bool ToBoolean(object value) catch (Exception e) when (ADP.IsCatchableExceptionType(e)) { ExceptionBuilder.TraceExceptionForCapture(e); - throw ExprException.DatavalueConversion(value, typeof(bool), e); + throw ExprException.DatavalueConversion(value, typeof(bool)); } } - throw ExprException.DatavalueConversion(value, typeof(bool), null); + throw ExprException.DatavalueConversion(value, typeof(bool)); } } } diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/FilterException.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/FilterException.cs index 87bd7dfb13e70..13d8f9b8b0fc3 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/FilterException.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/FilterException.cs @@ -78,12 +78,6 @@ private static EvaluateException _Eval(string error) ExceptionBuilder.TraceExceptionAsReturnValue(e); return e; } - private static EvaluateException _Eval(string error, Exception? innerException) - { - EvaluateException e = new EvaluateException(error/*, innerException*/); - ExceptionBuilder.TraceExceptionAsReturnValue(e); - return e; - } public static Exception InvokeArgument() { @@ -167,9 +161,9 @@ public static Exception DatatypeConversion(Type type1, Type type2) return _Eval(SR.Format(SR.Expr_DatatypeConversion, type1.ToString(), type2.ToString())); } - public static Exception DatavalueConversion(object value, Type type, Exception? innerException) + public static Exception DatavalueConversion(object value, Type type) { - return _Eval(SR.Format(SR.Expr_DatavalueConversion, value.ToString(), type.ToString()), innerException); + return _Eval(SR.Format(SR.Expr_DatavalueConversion, value.ToString(), type.ToString())); } public static Exception InvalidName(string name) diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs index 3da0280967889..4ecff90a667fe 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs @@ -17,11 +17,6 @@ public struct SqlBinary : INullable, IComparable, IXmlSerializable, IEquatable /// Initializes a new instance of the class with a binary object to be stored. /// @@ -42,8 +37,9 @@ public SqlBinary(byte[]? value) /// /// Initializes a new instance of the class with a binary object to be stored. This constructor will not copy the value. /// - internal SqlBinary(byte[]? value, bool ignored) + private SqlBinary(byte[]? value, bool copy) { + Debug.Assert(!copy); // if value is null, this generates a SqlBinary.Null _value = value; } @@ -466,13 +462,13 @@ public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) public static SqlBinary WrapBytes(byte[] bytes) { - return new SqlBinary(bytes, ignored: true); + return new SqlBinary(bytes, copy: false); } /// /// Represents a null value that can be assigned to the property of an /// instance of the class. /// - public static readonly SqlBinary Null = new SqlBinary(true); + public static readonly SqlBinary Null = new SqlBinary(null, copy: false); } // SqlBinary } // namespace System.Data.SqlTypes diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs index 84a5abeb54fc0..536b7aaeffb9e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs @@ -27,7 +27,7 @@ public struct SqlByte : INullable, IComparable, IXmlSerializable, IEquatable 0) diff --git a/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs b/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs index cab47a7f1d10a..f3fbd40388ac3 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs @@ -22,7 +22,7 @@ internal void LoadDiffGram(DataSet ds, XmlReader dataTextReader) _dataSet = ds; while (reader.LocalName == Keywords.SQL_BEFORE && reader.NamespaceURI == Keywords.DFFNS) { - ProcessDiffs(ds, reader); + ProcessDiffs(reader); reader.Read(); // now the reader points to the error section } @@ -58,7 +58,7 @@ internal void LoadDiffGram(DataTable dt, XmlReader dataTextReader) while (reader.LocalName == Keywords.SQL_BEFORE && reader.NamespaceURI == Keywords.DFFNS) { - ProcessDiffs(_tables, reader); + ProcessDiffs(reader); reader.Read(); // now the reader points to the error section } @@ -122,7 +122,7 @@ internal void ProcessDiffs(DataSet ds, XmlReader ssync) } [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - internal void ProcessDiffs(ArrayList tableList, XmlReader ssync) + internal void ProcessDiffs(XmlReader ssync) { DataTable? tableBefore; DataRow? row; diff --git a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs index b5347a026375b..0faa0202d5609 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs @@ -410,7 +410,7 @@ private static void SetExtProperties(object instance, XmlAttributeCollection att }// SetExtProperties [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - internal void HandleRefTableProperties(ArrayList RefTables, XmlSchemaElement element) + internal void HandleRefTableProperties(XmlSchemaElement element) { string typeName = GetInstanceName(element); DataTable? table = _ds!.Tables.GetTable(XmlConvert.DecodeName(typeName), element.QualifiedName.Namespace); @@ -782,7 +782,7 @@ public void LoadSchema(XmlSchemaSet schemaSet, DataSet ds) string typeName = GetInstanceName(element); if (_refTables.Contains(element.QualifiedName.Namespace + ":" + typeName)) { - HandleRefTableProperties(_refTables, element); + HandleRefTableProperties(element); continue; } diff --git a/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs b/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs index 8a392bd24a415..560a22913cc1e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs @@ -1364,12 +1364,12 @@ private bool ProcessXsdSchema() { // Have to load schema. if (_isTableLevel) { // Loading into the DataTable ? - _dataTable!.ReadXSDSchema(_dataReader, false); // Invoke ReadXSDSchema on a table + _dataTable!.ReadXSDSchema(_dataReader); // Invoke ReadXSDSchema on a table _nodeToSchemaMap = new XmlToDatasetMap(_dataReader.NameTable, _dataTable); } // Rebuild XML to DataSet map with new schema. else { // Loading into the DataSet ? - _dataSet!.ReadXSDSchema(_dataReader, false); // Invoke ReadXSDSchema on a DataSet + _dataSet!.ReadXSDSchema(_dataReader); // Invoke ReadXSDSchema on a DataSet _nodeToSchemaMap = new XmlToDatasetMap(_dataReader.NameTable, _dataSet); } // Rebuild XML to DataSet map with new schema. } diff --git a/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs b/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs index dcf011d57f4bf..ee1b300f3f430 100644 --- a/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs +++ b/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs @@ -107,7 +107,7 @@ internal static void AddExtendedProperties(PropertyCollection? props, XmlElement } [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - internal void AddXdoProperties(object? instance, XmlElement root, XmlDocument xd) + internal void AddXdoProperties(object? instance, XmlElement root) { if (instance == null) { @@ -123,13 +123,13 @@ internal void AddXdoProperties(object? instance, XmlElement root, XmlDocument xd for (int i = 0; i < pds.Count; i++) { - AddXdoProperty(pds[i], instance, root, xd); + AddXdoProperty(pds[i], instance, root); } return; } [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - internal void AddXdoProperty(PropertyDescriptor pd, object instance, XmlElement root, XmlDocument xd) + internal void AddXdoProperty(PropertyDescriptor pd, object instance, XmlElement root) { Type type = pd.PropertyType; bool bisDataColumn = false; @@ -374,7 +374,7 @@ private static bool HaveExtendedProperties(DataSet ds) return false; }// HaveExtendedProperties - internal void WriteSchemaRoot(XmlDocument xd, XmlElement rootSchema, string targetNamespace) + internal void WriteSchemaRoot(XmlElement rootSchema, string targetNamespace) { /* if (_ds != null) @@ -597,11 +597,11 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT } if (_ds != null) { - WriteSchemaRoot(xd, rootSchema, _ds.Namespace); + WriteSchemaRoot(rootSchema, _ds.Namespace); } else { - WriteSchemaRoot(xd, rootSchema, _dt.Namespace); + WriteSchemaRoot(rootSchema, _dt.Namespace); } // register the root element and associated NS @@ -665,7 +665,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT // probably we need to throw an exception FillDataSetElement(xd, ds, dt); rootSchema.AppendChild(_dsElement); - AddXdoProperties(_ds, _dsElement, xd); + AddXdoProperties(_ds, _dsElement); AddExtendedProperties(ds!._extendedProperties, _dsElement); @@ -687,7 +687,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT // DataSet properties if (_ds != null) { - AddXdoProperties(_ds, _dsElement, xd); + AddXdoProperties(_ds, _dsElement); AddExtendedProperties(_ds._extendedProperties, _dsElement); } @@ -747,7 +747,7 @@ internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet? ds, DataT } else { - AppendChildWithoutRef(rootSchema, top[i].Namespace, el, Keywords.XSD_ELEMENT); + AppendChildWithoutRef(top[i].Namespace, el); XmlElement node = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS); node.SetAttribute(Keywords.REF, ((string)_prefixes[top[i].Namespace]!) + ':' + top[i].EncodedTableName); dsCompositor.AppendChild(node); @@ -955,7 +955,7 @@ internal XmlElement SchemaTree(XmlDocument xd, DataTable dt) XmlElement rootSchema = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SCHEMA, Keywords.XSDNS); _sRoot = rootSchema; - WriteSchemaRoot(xd, rootSchema, dt.Namespace); + WriteSchemaRoot(rootSchema, dt.Namespace); _ = FillDataSetElement(xd, null, dt); @@ -1218,7 +1218,7 @@ internal XmlElement GetSchema(string NamespaceURI) if (schemaEl == null) { schemaEl = _dc!.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SCHEMA, Keywords.XSDNS); - WriteSchemaRoot(_dc, schemaEl, NamespaceURI); + WriteSchemaRoot(schemaEl, NamespaceURI); if (!string.IsNullOrEmpty(NamespaceURI)) { string prefix = Keywords.APP + Convert.ToString(++_prefixCount, CultureInfo.InvariantCulture); @@ -1440,7 +1440,7 @@ internal XmlElement HandleColumn(DataColumn col, XmlDocument dc, XmlElement sche } if (col.GetType() != typeof(DataColumn)) - AddXdoProperties(col, root, dc); + AddXdoProperties(col, root); else AddColumnProperties(col, root); @@ -1556,7 +1556,7 @@ internal static string TranslateRule(Rule rule) => _ => null!, }; - internal void AppendChildWithoutRef(XmlElement node, string Namespace, XmlElement el, string refString) + internal void AppendChildWithoutRef(string Namespace, XmlElement el) { XmlElement schNode = GetSchema(Namespace); if (FindTypeNode(schNode, el.GetAttribute(Keywords.NAME)) == null) @@ -1779,7 +1779,7 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche root.SetAttribute(Keywords.MSD_LOCALE, Keywords.MSDNS, table.Locale.ToString()); } - AddXdoProperties(table, root, dc); + AddXdoProperties(table, root); DataColumnCollection columns = table.Columns; @@ -1860,7 +1860,7 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche XmlElement sc = dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SIMPLECONTENT, Keywords.XSDNS); if (colTxt.GetType() != typeof(DataColumn)) - AddXdoProperties(colTxt, sc, dc); + AddXdoProperties(colTxt, sc); else AddColumnProperties(colTxt, sc); AddExtendedProperties(colTxt._extendedProperties, sc); diff --git a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs index 34f07589703d4..9a25f941465dd 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs @@ -637,7 +637,7 @@ private void Foliate(XmlElement element) // Foliate rowElement region if there are DataPointers that points into it [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - private void FoliateIfDataPointers(DataRow row, XmlElement rowElement) + private void FoliateIfDataPointers(XmlElement rowElement) { if (!IsFoliated(rowElement) && HasPointers(rowElement)) { @@ -763,7 +763,7 @@ private void ForceFoliation(XmlBoundElement node, ElementState newState) } //Determine best radical insert position for inserting column elements - private XmlNode? GetColumnInsertAfterLocation(DataRow row, DataColumn col, XmlBoundElement rowElement) + private XmlNode? GetColumnInsertAfterLocation(DataColumn col, XmlBoundElement rowElement) { XmlNode? prev = null; XmlNode? node; @@ -864,7 +864,7 @@ private ArrayList GetNestedChildRelations(DataRow row) return DataSetMapper.GetRowFromElement(e); } - private XmlNode? GetRowInsertBeforeLocation(DataRow row, XmlElement rowElement, XmlNode parentElement) + private XmlNode? GetRowInsertBeforeLocation(DataRow row, XmlNode parentElement) { DataRow refRow = row; int i; @@ -1572,7 +1572,7 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r XmlElement newElem = new XmlBoundElement(string.Empty, col.EncodedColumnName, col.Namespace, this); newElem.AppendChild(CreateTextNode(col.ConvertObjectToXml(value))); - XmlNode? elemBefore = GetColumnInsertAfterLocation(row, col, rowElement); + XmlNode? elemBefore = GetColumnInsertAfterLocation(col, rowElement); if (elemBefore != null) { rowElement.InsertAfter(newElem, elemBefore); @@ -1665,7 +1665,7 @@ private void OnColumnValuesChanged(DataRow row, XmlBoundElement rowElement) } [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - private void OnDeleteRow(DataRow row, XmlBoundElement rowElement) + private void OnDeleteRow(XmlBoundElement rowElement) { // IgnoreXmlEvents s/b on since we are manipulating the XML tree and we not want this to reflect in ROM view. Debug.Assert(_ignoreXmlEvents); @@ -1679,7 +1679,7 @@ private void OnDeleteRow(DataRow row, XmlBoundElement rowElement) } [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - private void OnDeletingRow(DataRow row, XmlBoundElement rowElement) + private void OnDeletingRow(XmlBoundElement rowElement) { // Note that this function is being called even if ignoreDataSetEvents == true. @@ -2032,7 +2032,7 @@ private void OnRowChanged(object sender, DataRowChangeEventArgs args) break; case DataRowAction.Delete: - OnDeleteRow(row, rowElement); + OnDeleteRow(rowElement); break; case DataRowAction.Rollback: @@ -2082,7 +2082,7 @@ private void OnRowChanging(object sender, DataRowChangeEventArgs args) DataRow row = args.Row; if (args.Action == DataRowAction.Delete && row.Element != null) { - OnDeletingRow(row, row.Element); + OnDeletingRow(row.Element); return; } @@ -2166,7 +2166,7 @@ private void OnRowChanging(object sender, DataRowChangeEventArgs args) { // Foliate only for non-hidden columns (since hidden cols are not represented in XML) if (c.ColumnMapping != MappingType.Hidden) - FoliateIfDataPointers(row, rowElement); + FoliateIfDataPointers(rowElement); } if (!IsSame(c, nRec1, nRec2)) _columnChangeList.Add(c); @@ -2272,7 +2272,7 @@ private void OnUndeleteRow(DataRow row, XmlElement rowElement) else parent = GetElementFromRow(parentRowInRelation); - if ((refRow = GetRowInsertBeforeLocation(row, rowElement, parent)) != null) + if ((refRow = GetRowInsertBeforeLocation(row, parent)) != null) parent.InsertBefore(rowElement, refRow); else parent.AppendChild(rowElement); @@ -2760,7 +2760,7 @@ private void OnNodeInsertedInFragment(XmlNode node) else { ArrayList rowElemList = new ArrayList(); - OnNonRowElementInsertedInFragment(node, be, rowElemList); + OnNonRowElementInsertedInFragment(be, rowElemList); // Set nested parent for the 1st level subregions (they should already be associated w/ Deleted or Detached rows) while (rowElemList.Count > 0) { @@ -2918,7 +2918,7 @@ private void OnNonRowElementInsertedInTree(XmlNode node, XmlBoundElement rowElem // A non-row-elem was inserted into disconnected tree (fragment) from oldParent==null state (i.e. was disconnected) [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - private void OnNonRowElementInsertedInFragment(XmlNode node, XmlBoundElement rowElement, ArrayList rowElemList) + private void OnNonRowElementInsertedInFragment(XmlBoundElement rowElement, ArrayList rowElemList) { // non-row-elem is being inserted DataRow? row = rowElement.Row; diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs index 70354e2947d53..b4b5e8ca98723 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbConnectionPool.cs @@ -22,7 +22,7 @@ private enum State private sealed class PendingGetConnection { - public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource completion, DbConnectionOptions? userOptions) + public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource completion) { DueTime = dueTime; Owner = owner; @@ -31,7 +31,6 @@ public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSour public long DueTime { get; private set; } public DbConnection Owner { get; private set; } public TaskCompletionSource Completion { get; private set; } - public DbConnectionOptions? UserOptions { get; private set; } } @@ -626,7 +625,7 @@ private void WaitForPendingOpen() { bool allowCreate = true; bool onlyOneCheckConnection = false; - timeout = !TryGetConnection(next.Owner, delay, allowCreate, onlyOneCheckConnection, next.UserOptions, out connection); + timeout = !TryGetConnection(next.Owner, delay, allowCreate, onlyOneCheckConnection, null, out connection); } catch (Exception e) { @@ -699,8 +698,7 @@ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource completion, DbConnectionOptions? userOptions) + public PendingGetConnection(long dueTime, DbConnection owner, TaskCompletionSource completion) { DueTime = dueTime; Owner = owner; @@ -1066,8 +1066,7 @@ internal bool TryGetConnection(DbConnection owningObject, TaskCompletionSource { _endInstrumentMeasurements(instrument); - RemoveInstrumentState(instrument, (InstrumentState)cookie!); + RemoveInstrumentState(instrument); } }; _listener.SetMeasurementEventCallback((i, m, l, c) => ((InstrumentState)c!).Update((double)m, l)); @@ -218,7 +218,7 @@ public void Dispose() _listener.Dispose(); } - private void RemoveInstrumentState(Instrument instrument, InstrumentState state) + private void RemoveInstrumentState(Instrument instrument) { _instrumentStates.TryRemove(instrument, out _); } diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs index 272d5d722d1e0..ae43e819f34ae 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLog.cs @@ -320,7 +320,7 @@ public static void CreateEventSource(EventSourceCreationData sourceData) } logKey = eventKey.CreateSubKey(logName); - SetSpecialLogRegValues(logKey, logName); + SetSpecialLogRegValues(logKey); // A source with the same name as the log has to be created // by default. It is the behavior expected by EventLog API. sourceLogKey = logKey.CreateSubKey(logName); @@ -331,7 +331,7 @@ public static void CreateEventSource(EventSourceCreationData sourceData) { if (!createLogKey) { - SetSpecialLogRegValues(logKey, logName); + SetSpecialLogRegValues(logKey); } sourceKey = logKey.CreateSubKey(source); @@ -768,7 +768,7 @@ public void RegisterDisplayName(string resourceFile, long resourceId) _underlyingEventLog.RegisterDisplayName(resourceFile, resourceId); } - private static void SetSpecialLogRegValues(RegistryKey logKey, string logName) + private static void SetSpecialLogRegValues(RegistryKey logKey) { // Set all the default values for this log. AutoBackupLogfiles only makes sense in // Win2000 SP4, WinXP SP1, and Win2003, but it should alright elsewhere. diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs index 8c998fba98162..62a7909762e1f 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogInternal.cs @@ -522,7 +522,7 @@ private void Close(string currentMachineName) boolFlags[Flag_sourceVerified] = false; } - private void CompletionCallback(object context) + private void CompletionCallback() { if (boolFlags[Flag_disposed]) { @@ -1182,7 +1182,7 @@ private static void StaticCompletionCallback(object context, bool wasSignaled) { try { - interestedComponents[i]?.CompletionCallback(null); + interestedComponents[i]?.CompletionCallback(); } catch (ObjectDisposedException) { diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/NativeWrapper.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/NativeWrapper.cs index 7f1fb58085a80..9d83f3fb3661d 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/NativeWrapper.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/NativeWrapper.cs @@ -116,7 +116,6 @@ public static EventLogHandle EvtOpenProviderMetadata( EventLogHandle session, string ProviderId, string logFilePath, - int locale, int flags) { // ignore locale and pass 0 instead: that way, the thread locale will be retrieved in the API layer diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.cs index 6be68d1aaa275..01e201c2bfe08 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/Reader/ProviderMetadata.cs @@ -63,7 +63,7 @@ internal ProviderMetadata(string providerName, EventLogSession session, CultureI _cultureInfo = targetCultureInfo; _logFilePath = logFilePath; - _handle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, _providerName, _logFilePath, 0, 0); + _handle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, _providerName, _logFilePath, 0); _syncObject = new object(); } @@ -205,7 +205,7 @@ public IList LogLinks { if (_defaultProviderHandle.IsInvalid) { - _defaultProviderHandle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, null, null, 0, 0); + _defaultProviderHandle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, null, null, 0); } channelRefDisplayName = NativeWrapper.EvtFormatMessage(_defaultProviderHandle, unchecked((uint)channelRefMessageId)); @@ -358,7 +358,7 @@ internal object GetProviderListProperty(EventLogHandle providerHandle, UnsafeNat { if (_defaultProviderHandle.IsInvalid) { - _defaultProviderHandle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, null, null, 0, 0); + _defaultProviderHandle = NativeWrapper.EvtOpenProviderMetadata(_session.Handle, null, null, 0); } generalDisplayName = objectTypeName switch diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs index a18ddeea87b99..9f200fac46edb 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs @@ -69,14 +69,8 @@ public PerformanceCounter() /// Creates the Performance Counter Object /// public PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName) + : this(categoryName, counterName, instanceName, machineName, skipInit: false) { - MachineName = machineName; - CategoryName = categoryName; - CounterName = counterName; - InstanceName = instanceName; - _isReadOnly = true; - Initialize(); - GC.SuppressFinalize(this); } internal PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName, bool skipInit) @@ -86,7 +80,11 @@ internal PerformanceCounter(string categoryName, string counterName, string inst CounterName = counterName; InstanceName = instanceName; _isReadOnly = true; - _initialized = true; + if (skipInit) + _initialized = true; + else + Initialize(); + GC.SuppressFinalize(this); } diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstanceCounterDataSet.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstanceCounterDataSet.cs index 8e07cd6913381..55d3351386c8b 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstanceCounterDataSet.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSetInstanceCounterDataSet.cs @@ -145,7 +145,7 @@ internal CounterSetInstanceCounterDataSet(CounterSetInstance thisInst) (void*)(_dataBlock + CounterOffset * sizeof(long))); if (Status != (uint)Interop.Errors.ERROR_SUCCESS) { - Dispose(true); + DisposeCore(); // ERROR_INVALID_PARAMETER or ERROR_NOT_FOUND throw Status switch @@ -162,16 +162,16 @@ internal CounterSetInstanceCounterDataSet(CounterSetInstance thisInst) public void Dispose() { - Dispose(true); + DisposeCore(); GC.SuppressFinalize(this); } ~CounterSetInstanceCounterDataSet() { - Dispose(false); + DisposeCore(); } - private void Dispose(bool disposing) + private void DisposeCore() { if (Interlocked.Exchange(ref _disposed, 1) == 0) { diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.ConfigureTerminalForChildProcesses.iOS.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.ConfigureTerminalForChildProcesses.iOS.cs index 3d9f85f7a4301..44821b211d492 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.ConfigureTerminalForChildProcesses.iOS.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.ConfigureTerminalForChildProcesses.iOS.cs @@ -1,8 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -using System.Threading; - namespace System.Diagnostics { public partial class Process @@ -10,11 +8,12 @@ public partial class Process /// These methods are used on other Unix systems to track how many children use the terminal, /// and update the terminal configuration when necessary. + [Conditional("unnecessary")] internal static void ConfigureTerminalForChildProcesses(int increment, bool configureConsole = true) - { } + { + } - private static unsafe void SetDelayedSigChildConsoleConfigurationHandler() - { } + static partial void SetDelayedSigChildConsoleConfigurationHandler(); private static bool AreChildrenUsingTerminal => false; } diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs index e25aa2bf9fd88..ca59d944dc970 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs @@ -241,11 +241,13 @@ private void GetWorkingSetLimits(out IntPtr minWorkingSet, out IntPtr maxWorking /// The new maximum working set limit, or null not to change it. /// The resulting minimum working set limit after any changes applied. /// The resulting maximum working set limit after any changes applied. +#pragma warning disable IDE0060 private static void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr resultingMin, out IntPtr resultingMax) { // RLIMIT_RSS with setrlimit not supported on Linux > 2.4.30. throw new PlatformNotSupportedException(SR.MinimumWorkingSetNotSupported); } +#pragma warning restore IDE0060 /// Gets the path to the executable for the process, or null if it could not be retrieved. /// The pid for the target process, or -1 for the current process. diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs index f8fab2d86d03f..e361c42a9438f 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs @@ -1060,7 +1060,7 @@ private static unsafe bool TryGetPasswd(string name, byte* buf, int bufLen, out public bool Responding => true; - private static bool WaitForInputIdleCore(int milliseconds) => throw new InvalidOperationException(SR.InputIdleUnknownError); + private static bool WaitForInputIdleCore(int _ /*milliseconds*/) => throw new InvalidOperationException(SR.InputIdleUnknownError); private static unsafe void EnsureInitialized() { diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.iOS.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.iOS.cs index 69deadae2a31c..b94531f135685 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.iOS.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.iOS.cs @@ -9,6 +9,7 @@ namespace System.Diagnostics { public partial class Process : IDisposable { +#pragma warning disable IDE0060 [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [SupportedOSPlatform("maccatalyst")] @@ -110,6 +111,8 @@ private static void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out throw new PlatformNotSupportedException(); } +#pragma warning restore IDE0060 + /// Gets execution path private static string GetPathToOpenFile() { diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.iOS.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.iOS.cs index e40cfac70a6a0..766c2dae22bd7 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.iOS.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.iOS.cs @@ -7,6 +7,7 @@ namespace System.Diagnostics { internal static partial class ProcessManager { +#pragma warning disable IDE0060 /// Gets the IDs of all processes on the current machine. public static int[] GetProcessIds() { @@ -36,5 +37,6 @@ private static ProcessInfo CreateProcessInfo(int pid) { throw new PlatformNotSupportedException(); } +#pragma warning restore IDE0060 } } diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System.DirectoryServices.AccountManagement.csproj b/src/libraries/System.DirectoryServices.AccountManagement/src/System.DirectoryServices.AccountManagement.csproj index 8152e3c7f051e..e809ad6f73725 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System.DirectoryServices.AccountManagement.csproj +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System.DirectoryServices.AccountManagement.csproj @@ -7,7 +7,7 @@ - $(NoWarn);CA1845;CA1846;IDE0059;CA1822 + $(NoWarn);CA1845;CA1846;IDE0059;IDE0060;CA1822 annotations true true diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/Interop/LdapPal.Linux.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/Interop/LdapPal.Linux.cs index e2fd327a91f8c..15b3cd86effaf 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/Interop/LdapPal.Linux.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/Interop/LdapPal.Linux.cs @@ -12,7 +12,7 @@ internal static class LdapPal internal static int AddDirectoryEntry(ConnectionHandle ldapHandle, string dn, IntPtr attrs, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber) => Interop.Ldap.ldap_add(ldapHandle, dn, attrs, servercontrol, clientcontrol, ref messageNumber); - internal static int CompareDirectoryEntries(ConnectionHandle ldapHandle, string dn, string attributeName, string strValue, BerVal binaryValue, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber) => + internal static int CompareDirectoryEntries(ConnectionHandle ldapHandle, string dn, string attributeName, string _ /*strValue*/, BerVal binaryValue, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber) => Interop.Ldap.ldap_compare(ldapHandle, dn, attributeName, binaryValue, servercontrol, clientcontrol, ref messageNumber); internal static void FreeDirectoryControl(IntPtr control) => Interop.Ldap.ldap_control_free(control); @@ -167,7 +167,7 @@ internal static int StartTls(ConnectionHandle ldapHandle, ref int serverReturnVa } // openldap doesn't have a ldap_stop_tls function. Returning true as no-op for Linux. - internal static byte StopTls(ConnectionHandle ldapHandle) => 1; + internal static byte StopTls(ConnectionHandle _/*ldapHandle*/) => 1; internal static void FreeValue(IntPtr referral) => Interop.Ldap.ldap_value_free(referral); @@ -177,12 +177,13 @@ internal static int StartTls(ConnectionHandle ldapHandle, ref int serverReturnVa internal static IntPtr StringToPtr(string s) => Marshal.StringToHGlobalAnsi(s); +#pragma warning disable IDE0060 /// /// Function that will be sent to the Sasl interactive bind procedure which will resolve all Sasl challenges /// that get passed in by using the defaults that we get passed in. /// /// The connection handle to the LDAP server. - /// Flags that control the interaction used to retrieve any necessary Sasl authentication parameters + /// /// Pointer to the defaults structure that was sent to sasl_interactive_bind /// Pointer to the challenge we need to resolve /// @@ -231,5 +232,6 @@ internal static int SaslInteractionProcedure(IntPtr ldapHandle, uint flags, IntP return 0; } +#pragma warning restore IDE0060 } } diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/Interop/LdapPal.Windows.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/Interop/LdapPal.Windows.cs index f914f707883b6..a0f6133f66bbb 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/Interop/LdapPal.Windows.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/Interop/LdapPal.Windows.cs @@ -34,7 +34,7 @@ internal static int ExtendedDirectoryOperation(ConnectionHandle ldapHandle, stri internal static IntPtr GetDistinguishedName(ConnectionHandle ldapHandle, IntPtr result) => Interop.Ldap.ldap_get_dn(ldapHandle, result); - internal static int GetLastErrorFromConnection(ConnectionHandle ldapHandle) => Interop.Ldap.LdapGetLastError(); + internal static int GetLastErrorFromConnection(ConnectionHandle _ /*ldapHandle*/) => Interop.Ldap.LdapGetLastError(); internal static int GetIntOption(ConnectionHandle ldapHandle, LdapOption option, ref int outValue) => Interop.Ldap.ldap_get_option_int(ldapHandle, option, ref outValue); diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.Linux.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.Linux.cs index 96661bd33a7b4..e1cfffebb531f 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.Linux.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.Linux.cs @@ -7,7 +7,7 @@ namespace System.DirectoryServices.Protocols { public partial class LdapSessionOptions { - private static void PALCertFreeCRLContext(IntPtr certPtr) { /* No op */ } + static partial void PALCertFreeCRLContext(IntPtr certPtr); private bool _secureSocketLayer; diff --git a/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj b/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj index 83a118e940de0..1192d4326ff2f 100644 --- a/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj +++ b/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj @@ -6,7 +6,7 @@ - $(NoWarn);CA1845;CA1846;IDE0059;CA1822 + $(NoWarn);CA1845;CA1846;IDE0059;IDE0060;CA1822 true true true diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphics.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphics.cs index 256d3fa1b7af8..f7bcdf448c400 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphics.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphics.cs @@ -38,7 +38,7 @@ public void Dispose() { if (_context != null) { - _context.ReleaseBuffer(this); + _context.ReleaseBuffer(); if (DisposeContext) { diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.cs index 2559c26e1440e..22e9eb0b9b3a5 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.cs @@ -120,7 +120,7 @@ private BufferedGraphics AllocBuffer(Graphics? targetGraphics, IntPtr targetDC, IntPtr destDc = targetGraphics.GetHdc(); try { - surface = CreateBuffer(destDc, -_targetLoc.X, -_targetLoc.Y, targetRectangle.Width, targetRectangle.Height); + surface = CreateBuffer(destDc, targetRectangle.Width, targetRectangle.Height); } finally { @@ -129,7 +129,7 @@ private BufferedGraphics AllocBuffer(Graphics? targetGraphics, IntPtr targetDC, } else { - surface = CreateBuffer(targetDC, -_targetLoc.X, -_targetLoc.Y, targetRectangle.Width, targetRectangle.Height); + surface = CreateBuffer(targetDC, targetRectangle.Width, targetRectangle.Height); } _buffer = new BufferedGraphics(surface, this, targetGraphics, targetDC, _targetLoc, _virtualSize); @@ -311,7 +311,7 @@ private unsafe bool FillColorTable(IntPtr hdc, IntPtr hpal, ref Interop.Gdi32.BI /// /// Returns a Graphics object representing a buffer. /// - private Graphics CreateBuffer(IntPtr src, int offsetX, int offsetY, int width, int height) + private Graphics CreateBuffer(IntPtr src, int width, int height) { // Create the compat DC. _busy = BufferBusyDisposing; @@ -518,7 +518,7 @@ public void Invalidate() /// /// Returns a Graphics object representing a buffer. /// - internal void ReleaseBuffer(BufferedGraphics buffer) + internal void ReleaseBuffer() { _buffer = null; if (_invalidateWhenFree) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.cs index c591fe883880d..c0918a7b84991 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.cs @@ -66,10 +66,10 @@ public object Clone() { Gdip.CheckStatus(Gdip.GdipClonePath(new HandleRef(this, _nativePath), out IntPtr clonedPath)); - return new GraphicsPath(clonedPath, 0); + return new GraphicsPath(clonedPath); } - private GraphicsPath(IntPtr nativePath, int extra) + private GraphicsPath(IntPtr nativePath) { if (nativePath == IntPtr.Zero) throw new ArgumentNullException(nameof(nativePath)); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/Matrix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/Matrix.cs index ffaa33fb55252..0a90b2da9ea8b 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/Matrix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/Matrix.cs @@ -82,11 +82,11 @@ public unsafe Matrix(Rectangle rect, Point[] plgpts) public void Dispose() { - Dispose(true); + DisposeInternal(); GC.SuppressFinalize(this); } - private void Dispose(bool disposing) + private void DisposeInternal() { if (NativeMatrix != IntPtr.Zero) { @@ -98,7 +98,7 @@ private void Dispose(bool disposing) } } - ~Matrix() => Dispose(false); + ~Matrix() => DisposeInternal(); public Matrix Clone() { diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/GraphicsContext.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/GraphicsContext.cs index c1587d0e383a6..bc37013170fbe 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/GraphicsContext.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/GraphicsContext.cs @@ -20,15 +20,6 @@ public GraphicsContext(Graphics g) /// Disposes this and all contexts up the stack. /// public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Disposes this and all contexts up the stack. - /// - public void Dispose(bool disposing) { // Dispose all contexts up the stack since they are relative to this one and its state will be invalid. Next?.Dispose(); @@ -36,6 +27,8 @@ public void Dispose(bool disposing) Clip?.Dispose(); Clip = null; + + GC.SuppressFinalize(this); } /// diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/BitmapData.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/BitmapData.cs index 759ff7b1b158a..f9502ca98e2eb 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/BitmapData.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/BitmapData.cs @@ -119,7 +119,7 @@ internal static unsafe class PinningMarshaller public static ref int GetPinnableReference(BitmapData managed) => ref (managed is null ? ref Unsafe.NullRef() : ref managed.GetPinnableReference()); // All usages in our currently supported scenarios will always go through GetPinnableReference - public static int* ConvertToUnmanaged(BitmapData managed) => throw new UnreachableException(); + public static int* ConvertToUnmanaged(BitmapData _) => throw new UnreachableException(); } #endif } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ColorMatrix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ColorMatrix.cs index 75d090894f463..7859deb26cb7d 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ColorMatrix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/ColorMatrix.cs @@ -406,7 +406,7 @@ internal static unsafe class PinningMarshaller public static ref float GetPinnableReference(ColorMatrix managed) => ref (managed is null ? ref Unsafe.NullRef() : ref managed.GetPinnableReference()); // All usages in our currently supported scenarios will always go through GetPinnableReference - public static float* ConvertToUnmanaged(ColorMatrix managed) => throw new UnreachableException(); + public static float* ConvertToUnmanaged(ColorMatrix _) => throw new UnreachableException(); } #endif } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/EncoderParameter.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/EncoderParameter.cs index fab0dda234379..910de3f82e2bf 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/EncoderParameter.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/EncoderParameter.cs @@ -16,7 +16,7 @@ public sealed unsafe class EncoderParameter : IDisposable ~EncoderParameter() { - Dispose(false); + DisposeInternal(); } /// @@ -69,12 +69,12 @@ public int NumberOfValues public void Dispose() { - Dispose(true); + DisposeInternal(); GC.KeepAlive(this); GC.SuppressFinalize(this); } - private void Dispose(bool disposing) + private void DisposeInternal() { if (_parameterValue != IntPtr.Zero) Marshal.FreeHGlobal(_parameterValue); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/MetafileHeaderEmf.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/MetafileHeaderEmf.cs index b28b757f9493d..fc4be30cd6162 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/MetafileHeaderEmf.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/MetafileHeaderEmf.cs @@ -44,7 +44,7 @@ internal static unsafe class PinningMarshaller public static ref byte GetPinnableReference(MetafileHeaderEmf managed) => ref (managed is null ? ref Unsafe.NullRef() : ref managed.GetPinnableReference()); // All usages in our currently supported scenarios will always go through GetPinnableReference - public static byte* ConvertToUnmanaged(MetafileHeaderEmf managed) => throw new UnreachableException(); + public static byte* ConvertToUnmanaged(MetafileHeaderEmf _) => throw new UnreachableException(); } #endif } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/WmfPlaceableFileHeader.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/WmfPlaceableFileHeader.cs index f9d3baa6557ee..a6761674c0ecc 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/WmfPlaceableFileHeader.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/WmfPlaceableFileHeader.cs @@ -116,7 +116,7 @@ internal static unsafe class PinningMarshaller public static ref int GetPinnableReference(WmfPlaceableFileHeader managed) => ref (managed is null ? ref Unsafe.NullRef() : ref managed.GetPinnableReference()); // All usages in our currently supported scenarios will always go through GetPinnableReference - public static int* ConvertToUnmanaged(WmfPlaceableFileHeader managed) => throw new UnreachableException(); + public static int* ConvertToUnmanaged(WmfPlaceableFileHeader _) => throw new UnreachableException(); } #endif } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs index 3a414f075b579..55a880becb59e 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs @@ -234,7 +234,7 @@ public bool IsPlotter { get { - return GetDeviceCaps(Interop.Gdi32.DeviceCapability.TECHNOLOGY, Interop.Gdi32.DeviceTechnology.DT_RASPRINTER) == Interop.Gdi32.DeviceTechnology.DT_PLOTTER; + return GetDeviceCaps(Interop.Gdi32.DeviceCapability.TECHNOLOGY) == Interop.Gdi32.DeviceTechnology.DT_PLOTTER; } } @@ -792,7 +792,7 @@ private static string GetOutputPort() } } - private int GetDeviceCaps(Interop.Gdi32.DeviceCapability capability, int defaultValue) + private int GetDeviceCaps(Interop.Gdi32.DeviceCapability capability) { using (DeviceContext dc = CreateInformationContext(DefaultPageSettings)) { diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarEntry.Windows.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarEntry.Windows.cs index 8b0c5ff4a04d2..17d4868171998 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarEntry.Windows.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarEntry.Windows.cs @@ -9,6 +9,7 @@ namespace System.Formats.Tar // Windows specific methods for the TarEntry class. public abstract partial class TarEntry { +#pragma warning disable IDE0060 // Throws on Windows. Block devices are not supported on this platform. private void ExtractAsBlockDevice(string destinationFileName) { @@ -38,5 +39,6 @@ private void ExtractAsHardLink(string targetFilePath, string hardLinkFilePath) Debug.Assert(!string.IsNullOrEmpty(hardLinkFilePath)); Interop.Kernel32.CreateHardLink(hardLinkFilePath, targetFilePath); } +#pragma warning restore IDE0060 } } diff --git a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHelpers.Windows.cs b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHelpers.Windows.cs index 6569ff237dbf9..7aedd36c3effc 100644 --- a/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHelpers.Windows.cs +++ b/src/libraries/System.Formats.Tar/src/System/Formats/Tar/TarHelpers.Windows.cs @@ -13,8 +13,10 @@ internal static partial class TarHelpers internal static SortedDictionary? CreatePendingModesDictionary() => null; +#pragma warning disable IDE0060 internal static void CreateDirectory(string fullPath, UnixFileMode? mode, SortedDictionary? pendingModes) => Directory.CreateDirectory(fullPath); +#pragma warning restore IDE0060 internal static void SetPendingModes(SortedDictionary? pendingModes) => Debug.Assert(pendingModes is null); diff --git a/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/FileSystemSecurity.cs b/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/FileSystemSecurity.cs index ecebf92fbb936..c438a4e9eb36f 100644 --- a/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/FileSystemSecurity.cs +++ b/src/libraries/System.IO.FileSystem.AccessControl/src/System/Security/AccessControl/FileSystemSecurity.cs @@ -130,7 +130,7 @@ internal void Persist(string fullPath) } } - internal void Persist(SafeFileHandle handle, string fullPath) + internal void Persist(SafeFileHandle handle, string _ /*fullPath*/) { WriteLock(); diff --git a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/Helper.Unix.cs b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/Helper.Unix.cs index 8001e9aa8933c..ade2f506751bd 100644 --- a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/Helper.Unix.cs +++ b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/Helper.Unix.cs @@ -5,7 +5,7 @@ namespace System.IO.IsolatedStorage { internal static partial class Helper { - internal static void CreateDirectory(string path, IsolatedStorageScope scope) + internal static void CreateDirectory(string path, IsolatedStorageScope _ /*scope*/) { Directory.CreateDirectory(path); } diff --git a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFileStream.cs b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFileStream.cs index 63da6562a5f6b..cd56b2031d0c4 100644 --- a/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFileStream.cs +++ b/src/libraries/System.IO.IsolatedStorage/src/System/IO/IsolatedStorage/IsolatedStorageFileStream.cs @@ -54,7 +54,7 @@ public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, } public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile? isf) - : this(path, mode, access, share, bufferSize, InitializeFileStream(path, mode, access, share, bufferSize, isf)) + : this(path, access, bufferSize, InitializeFileStream(path, mode, access, share, bufferSize, isf)) { } @@ -64,7 +64,7 @@ public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, // // We only expose our own nested FileStream so the base class having a handle doesn't matter. Passing a new SafeFileHandle // with ownsHandle: false avoids the parent class closing without our knowledge. - private IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, InitializationData initializationData) + private IsolatedStorageFileStream(string path, FileAccess access, int bufferSize, InitializationData initializationData) : base(new SafeFileHandle(initializationData.NestedStream.SafeFileHandle.DangerousGetHandle(), ownsHandle: false), access, bufferSize) { _isf = initializationData.StorageFile; diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Unix.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Unix.cs index b461f15f354b0..fd6f30551408d 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Unix.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Unix.cs @@ -122,6 +122,7 @@ private static SafeMemoryMappedFileHandle CreateOrOpenCore( return CreateCore(null, mapName, inheritability, access, options, capacity, -1); } +#pragma warning disable IDE0060 /// /// Used by the OpenExisting factory method group and by CreateOrOpen if access is write. /// We'll throw an ArgumentException if the file mapping object didn't exist and the @@ -143,6 +144,7 @@ private static SafeMemoryMappedFileHandle OpenCore( { throw CreateNamedMapsNotSupportedException(); } +#pragma warning restore IDE0060 /// Gets an exception indicating that named maps are not supported on this platform. private static Exception CreateNamedMapsNotSupportedException() diff --git a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.cs b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.cs index 84905632e61ab..7e15128a0d61e 100644 --- a/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.cs +++ b/src/libraries/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.cs @@ -43,17 +43,13 @@ public MemoryMappedFileAccess Access get { return _access; } } - private void Dispose(bool disposing) + public void Dispose() { if (!_viewHandle.IsClosed) { _viewHandle.Dispose(); } - } - public void Dispose() - { - Dispose(true); GC.SuppressFinalize(this); } diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackage.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackage.cs index c2cf548b6093c..edce0f121f90a 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackage.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackage.cs @@ -169,7 +169,7 @@ protected override PackagePart[] GetPartsCore() // part, it will be detected at this point because the part's Uri (which // is independent of interleaving) will already be in the dictionary. parts.Add(new ZipPackagePart(this, zipArchiveEntry.Archive, zipArchiveEntry, - _zipStreamManager, validatedPartUri, contentType.ToString(), GetCompressionOptionFromZipFileInfo(zipArchiveEntry))); + _zipStreamManager, validatedPartUri, contentType.ToString(), GetCompressionOptionFromZipFileInfo())); } } //If not valid part uri we can completely ignore this zip file item. Even if later someone adds @@ -452,7 +452,7 @@ private static bool IsZipItemValidOpcPartOrPiece(string zipItemName) } // convert from Zip CompressionMethodEnum and DeflateOptionEnum to XPS CompressionOption - private static CompressionOption GetCompressionOptionFromZipFileInfo(ZipArchiveEntry zipFileInfo) + private static CompressionOption GetCompressionOptionFromZipFileInfo() { // Note: we can't determine compression method / level from the ZipArchiveEntry. CompressionOption result = CompressionOption.Normal; @@ -653,7 +653,7 @@ internal void SaveToFile() _contentTypeZipArchiveEntry = thisArchive.CreateEntry(contentTypefullName); } - using (Stream s = _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite)) + using (Stream s = _zipStreamManager.Open(_contentTypeZipArchiveEntry, FileAccess.ReadWrite)) { // use UTF-8 encoding by default using (XmlWriter writer = XmlWriter.Create(s, new XmlWriterSettings { Encoding = System.Text.Encoding.UTF8 })) @@ -810,7 +810,7 @@ private void ParseContentTypesFile(System.Collections.ObjectModel.ReadOnlyCollec if (_contentTypeZipArchiveEntry != null) { _contentTypeStreamExists = true; - return _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite); + return _zipStreamManager.Open(_contentTypeZipArchiveEntry, FileAccess.ReadWrite); } // No content type stream was found. diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackagePart.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackagePart.cs index 17e99dc9320b1..441eb05a7197a 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackagePart.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipPackagePart.cs @@ -33,13 +33,13 @@ public sealed class ZipPackagePart : PackagePart // we'll want this call to SetLength. if (streamFileMode == FileMode.Create && _zipArchiveEntry.Archive.Mode != ZipArchiveMode.Create) { - using (var tempStream = _zipStreamManager.Open(_zipArchiveEntry, streamFileMode, streamFileAccess)) + using (var tempStream = _zipStreamManager.Open(_zipArchiveEntry, streamFileAccess)) { tempStream.SetLength(0); } } - var stream = _zipStreamManager.Open(_zipArchiveEntry, streamFileMode, streamFileAccess); + var stream = _zipStreamManager.Open(_zipArchiveEntry, streamFileAccess); return stream; } return null; diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipStreamManager.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipStreamManager.cs index 5ccb12d78aac1..b59dd034d23dc 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipStreamManager.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/ZipStreamManager.cs @@ -22,7 +22,7 @@ public ZipStreamManager(ZipArchive zipArchive, FileMode packageFileMode, FileAcc _packageFileAccess = packageFileAccess; } - public Stream Open(ZipArchiveEntry zipArchiveEntry, FileMode streamFileMode, FileAccess streamFileAccess) + public Stream Open(ZipArchiveEntry zipArchiveEntry, FileAccess streamFileAccess) { bool canRead = true; bool canWrite = true; diff --git a/src/libraries/System.IO.Pipes/src/Microsoft/Win32/SafeHandles/SafePipeHandle.Windows.cs b/src/libraries/System.IO.Pipes/src/Microsoft/Win32/SafeHandles/SafePipeHandle.Windows.cs index 5a1d27149f944..946f305c9c7f9 100644 --- a/src/libraries/System.IO.Pipes/src/Microsoft/Win32/SafeHandles/SafePipeHandle.Windows.cs +++ b/src/libraries/System.IO.Pipes/src/Microsoft/Win32/SafeHandles/SafePipeHandle.Windows.cs @@ -15,10 +15,5 @@ protected override bool ReleaseHandle() { return Interop.Kernel32.CloseHandle(handle); } - - internal void SetHandle(IntPtr descriptor, bool ownsHandle = true) - { - base.SetHandle(descriptor); - } } } diff --git a/src/libraries/System.IO.Pipes/src/Microsoft/Win32/SafeHandles/SafePipeHandle.cs b/src/libraries/System.IO.Pipes/src/Microsoft/Win32/SafeHandles/SafePipeHandle.cs index db58ee9a139c7..2836616123c6b 100644 --- a/src/libraries/System.IO.Pipes/src/Microsoft/Win32/SafeHandles/SafePipeHandle.cs +++ b/src/libraries/System.IO.Pipes/src/Microsoft/Win32/SafeHandles/SafePipeHandle.cs @@ -25,7 +25,7 @@ public SafePipeHandle() public SafePipeHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) { - SetHandle(preexistingHandle, ownsHandle); + SetHandle(preexistingHandle); } } } diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.Unix.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.Unix.cs index 3e07b15738cb6..cf86f49cf69e9 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.Unix.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.Unix.cs @@ -18,9 +18,9 @@ namespace System.IO.Pipes /// public sealed partial class NamedPipeClientStream : PipeStream { - private bool TryConnect(int timeout, CancellationToken cancellationToken) + private bool TryConnect(int _ /* timeout */) { - // timeout and cancellationToken aren't used as Connect will be very fast, + // timeout isn't used as Connect will be very fast, // either succeeding immediately if the server is listening or failing // immediately if it isn't. The only delay will be between the time the server // has called Bind and Listen, with the latter immediately following the former. diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.Windows.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.Windows.cs index 0cefc507a7b86..83d4f66d0cf47 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.Windows.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.Windows.cs @@ -20,7 +20,7 @@ public sealed partial class NamedPipeClientStream : PipeStream // on the server end, but WaitForConnection will not return until we have returned. Any data written to the // pipe by us after we have connected but before the server has called WaitForConnection will be available // to the server after it calls WaitForConnection. - private bool TryConnect(int timeout, CancellationToken cancellationToken) + private bool TryConnect(int timeout) { Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(_inheritability); diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs index 08d8029eca23d..063d8cc55cf13 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeClientStream.cs @@ -146,7 +146,7 @@ private void ConnectInternal(int timeout, CancellationToken cancellationToken, i } // Try to connect. - if (TryConnect(waitTime, cancellationToken)) + if (TryConnect(waitTime)) { return; } diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Windows.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Windows.cs index b486c44af4ac2..9c1e385a7c4f2 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Windows.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Windows.cs @@ -240,16 +240,14 @@ public void RunAsClient(PipeStreamImpersonationWorker impersonationWorker) { CheckWriteOperations(); ExecuteHelper execHelper = new ExecuteHelper(impersonationWorker, InternalHandle); - bool exceptionThrown = true; try { ImpersonateAndTryCode(execHelper); - exceptionThrown = false; } finally { - RevertImpersonationOnBackout(execHelper, exceptionThrown); + RevertImpersonationOnBackout(execHelper); } // now handle win32 impersonate/revert specific errors by throwing corresponding exceptions @@ -283,7 +281,7 @@ private static void ImpersonateAndTryCode(object? helper) } } - private static void RevertImpersonationOnBackout(object? helper, bool exceptionThrown) + private static void RevertImpersonationOnBackout(object? helper) { ExecuteHelper execHelper = (ExecuteHelper)helper!; diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs index 165c9787c6875..ce0607a69edb9 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs @@ -486,7 +486,7 @@ private int GetPipeBufferSize() } internal static void ConfigureSocket( - Socket s, SafePipeHandle pipeHandle, + Socket s, SafePipeHandle _, PipeDirection direction, int inBufferSize, int outBufferSize, HandleInheritability inheritability) { if (inBufferSize > 0) diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs index c820b81f1e3ae..a59bbe4e6b53b 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Unix.cs @@ -380,12 +380,14 @@ internal void DiscardOutBuffer() Interop.Termios.TermiosDiscard(_handle, Interop.Termios.Queue.SendQueue); } +#pragma warning disable IDE0060 internal void SetBufferSizes(int readBufferSize, int writeBufferSize) { if (_handle == null) InternalResources.FileNotOpen(); // Ignore for now. } +#pragma warning restore IDE0060 internal bool IsOpen => _handle != null; @@ -594,7 +596,7 @@ private static int EndReadWrite(IAsyncResult asyncResult) // this method is used by SerialPort upon SerialStream's creation internal SerialStream(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, int readTimeout, int writeTimeout, Handshake handshake, - bool dtrEnable, bool rtsEnable, bool discardNull, byte parityReplace) + bool dtrEnable, bool rtsEnable, bool _1 /*discardNull*/, byte _2 /*parityReplace*/) { ArgumentNullException.ThrowIfNull(portName); diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs index b6806569aeed5..2e63278a3b01b 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Windows.cs @@ -1031,7 +1031,7 @@ internal unsafe int Read(byte[] array, int offset, int count, int timeout) return numBytes; } - internal unsafe int ReadByte(int timeout) + internal unsafe int ReadByte(int _/*timeout*/) { if (_handle == null) InternalResources.FileNotOpen(); @@ -1101,12 +1101,7 @@ internal unsafe void Write(byte[] array, int offset, int count, int timeout) } // use default timeout as argument to WriteByte override with timeout arg - public override void WriteByte(byte value) - { - WriteByte(value, WriteTimeout); - } - - internal unsafe void WriteByte(byte value, int timeout) + public override unsafe void WriteByte(byte value) { if (_inBreak) throw new InvalidOperationException(SR.In_Break_State); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.cs index 42ecb44bb8489..951f44a6c50f5 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/CallInstruction.cs @@ -72,12 +72,9 @@ public static CallInstruction Create(MethodInfo info, ParameterInfo[] parameters // see if we've created one w/ a delegate CallInstruction? res; - if (ShouldCache(info)) + if (s_cache.TryGetValue(info, out res)) { - if (s_cache.TryGetValue(info, out res)) - { - return res; - } + return res; } // create it @@ -112,11 +109,8 @@ public static CallInstruction Create(MethodInfo info, ParameterInfo[] parameters res = new MethodInfoCallInstruction(info, argumentCount); } - // cache it for future users if it's a reasonable method to cache - if (ShouldCache(info)) - { - s_cache[info] = res; - } + // cache it for future users + s_cache[info] = res; return res; } @@ -171,11 +165,6 @@ public static void ArrayItemSetter3(Array array, int index0, int index1, int ind array.SetValue(value, index0, index1, index2); } - private static bool ShouldCache(MethodInfo info) - { - return true; - } - #if FEATURE_FAST_CREATE /// /// Gets the next type or null if no more types are available. diff --git a/src/libraries/System.Linq/src/System/Linq/Select.cs b/src/libraries/System.Linq/src/System/Linq/Select.cs index 9c0c576bbc1f3..791363496f68b 100644 --- a/src/libraries/System.Linq/src/System/Linq/Select.cs +++ b/src/libraries/System.Linq/src/System/Linq/Select.cs @@ -58,8 +58,10 @@ public static IEnumerable Select( return new SelectEnumerableIterator(source, selector); } +#pragma warning disable IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6177 static partial void CreateSelectIPartitionIterator( Func selector, IPartition partition, [NotNull] ref IEnumerable? result); +#pragma warning restore IDE0060 public static IEnumerable Select(this IEnumerable source, Func selector) { diff --git a/src/libraries/System.Management/src/System.Management.csproj b/src/libraries/System.Management/src/System.Management.csproj index 5b66be0b57356..0f4dbe30807ce 100644 --- a/src/libraries/System.Management/src/System.Management.csproj +++ b/src/libraries/System.Management/src/System.Management.csproj @@ -5,7 +5,7 @@ $(NoWarn);0618 - $(NoWarn);CA1845;IDE0059;CA1822 + $(NoWarn);CA1845;IDE0059;IDE0060;CA1822 annotations true true diff --git a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.netstandard.cs b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.netstandard.cs index 4198cc339ba84..e67e943b4dabd 100644 --- a/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.netstandard.cs +++ b/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json/HttpContentJsonExtensions.netstandard.cs @@ -12,6 +12,11 @@ public static partial class HttpContentJsonExtensions { private static Task ReadHttpContentStreamAsync(HttpContent content, CancellationToken cancellationToken) { + if (cancellationToken.IsCancellationRequested) + { + return Task.FromCanceled(cancellationToken); + } + // The ReadAsStreamAsync overload that takes a cancellationToken is not available in .NET Standard return content.ReadAsStreamAsync(); } diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/NoWriteNoSeekStreamContent.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/NoWriteNoSeekStreamContent.cs index eb11b2f14aa8b..047ef52edbb56 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/NoWriteNoSeekStreamContent.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/NoWriteNoSeekStreamContent.cs @@ -28,6 +28,7 @@ internal NoWriteNoSeekStreamContent(Stream content) protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) => SerializeToStreamAsync(stream, context, CancellationToken.None); +#pragma warning disable IDE0060 #if NETCOREAPP protected override #else @@ -59,6 +60,7 @@ Task SerializeToStreamAsync(Stream stream, TransportContext? context, Cancellati } return copyTask; } +#pragma warning restore IDE0060 protected override bool TryComputeLength(out long length) { diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs index 00cd0000f5bcb..653ec96c1bb3d 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs @@ -1260,7 +1260,7 @@ private void SetRequestHandleOptions(WinHttpRequestState state) SetRequestHandleRedirectionOptions(state.RequestHandle); SetRequestHandleCookieOptions(state.RequestHandle); SetRequestHandleTlsOptions(state.RequestHandle); - SetRequestHandleClientCertificateOptions(state.RequestHandle, state.RequestMessage.RequestUri, state.RequestMessage.Version); + SetRequestHandleClientCertificateOptions(state.RequestHandle, state.RequestMessage.RequestUri); SetRequestHandleCredentialsOptions(state); SetRequestHandleBufferingOptions(state.RequestHandle); SetRequestHandleHttp2Options(state.RequestHandle, state.RequestMessage.Version); @@ -1422,7 +1422,7 @@ private void SetRequestHandleTlsOptions(SafeWinHttpHandle requestHandle) } } - private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestHandle, Uri requestUri, Version requestVersion) + private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestHandle, Uri requestUri) { if (requestUri.Scheme != UriScheme.Https) { diff --git a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs index c8e2ca4090285..13c154516ce82 100644 --- a/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs +++ b/src/libraries/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs @@ -43,11 +43,10 @@ public static void WinHttpCallback( WinHttpRequestState? state = WinHttpRequestState.FromIntPtr(context); Debug.Assert(state != null, "WinHttpCallback must have a non-null state object"); - RequestCallback(handle, state, internetStatus, statusInformation, statusInformationLength); + RequestCallback(state, internetStatus, statusInformation, statusInformationLength); } private static void RequestCallback( - IntPtr handle, WinHttpRequestState state, uint internetStatus, IntPtr statusInformation, diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/HttpTelemetry.Browser.cs b/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/HttpTelemetry.Browser.cs index a5b2be615d821..34a6eda578b9e 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/HttpTelemetry.Browser.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/HttpTelemetry.Browser.cs @@ -7,7 +7,7 @@ namespace System.Net.Http { internal sealed partial class HttpTelemetry { -#pragma warning disable CA1822 +#pragma warning disable CA1822, IDE0060 public void Http11RequestLeftQueue(double timeOnQueueMilliseconds) { } @@ -15,7 +15,7 @@ public void Http11RequestLeftQueue(double timeOnQueueMilliseconds) public void Http20RequestLeftQueue(double timeOnQueueMilliseconds) { } -#pragma warning restore CA1822 +#pragma warning restore CA1822, IDE0060 protected override void OnEventCommand(EventCommandEventArgs command) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3Connection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3Connection.cs index 18169ea873315..688ba839abb45 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3Connection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http3Connection.cs @@ -648,7 +648,7 @@ private async Task ProcessServerControlStreamAsync(QuicStream stream, ArrayBuffe } return; default: - await SkipUnknownPayloadAsync(frameType.GetValueOrDefault(), payloadLength).ConfigureAwait(false); + await SkipUnknownPayloadAsync(payloadLength).ConfigureAwait(false); break; } } @@ -772,7 +772,7 @@ async ValueTask ProcessGoAwayFrameAsync(long goawayPayloadLength) OnServerGoAway(firstRejectedStreamId); } - async ValueTask SkipUnknownPayloadAsync(Http3FrameType frameType, long payloadLength) + async ValueTask SkipUnknownPayloadAsync(long payloadLength) { while (payloadLength != 0) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs index e4afdd294fca3..ba14928d05d24 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs @@ -775,7 +775,7 @@ private void CheckForHttp2ConnectionInjection() } } - private bool TryGetPooledHttp2Connection(HttpRequestMessage request, bool async, [NotNullWhen(true)] out Http2Connection? connection, out HttpConnectionWaiter? waiter) + private bool TryGetPooledHttp2Connection(HttpRequestMessage request, [NotNullWhen(true)] out Http2Connection? connection, out HttpConnectionWaiter? waiter) { Debug.Assert(_kind == HttpConnectionKind.Https || _kind == HttpConnectionKind.SslProxyTunnel || _kind == HttpConnectionKind.Http || _kind == HttpConnectionKind.SocksTunnel || _kind == HttpConnectionKind.SslSocksTunnel); @@ -1047,7 +1047,7 @@ public async ValueTask SendWithVersionDetectionAndRetryAsyn (request.Version.Major >= 2 || (request.VersionPolicy == HttpVersionPolicy.RequestVersionOrHigher && IsSecure)) && (request.VersionPolicy != HttpVersionPolicy.RequestVersionOrLower || IsSecure)) // prefer HTTP/1.1 if connection is not secured and downgrade is possible { - if (!TryGetPooledHttp2Connection(request, async, out Http2Connection? connection, out http2ConnectionWaiter) && + if (!TryGetPooledHttp2Connection(request, out Http2Connection? connection, out http2ConnectionWaiter) && http2ConnectionWaiter != null) { connection = await http2ConnectionWaiter.WaitForConnectionAsync(async, cancellationToken).ConfigureAwait(false); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionResponseContent.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionResponseContent.cs index 261ee3d17b4c1..3bc32fd2e19e3 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionResponseContent.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionResponseContent.cs @@ -51,9 +51,9 @@ protected sealed override Task SerializeToStreamAsync(Stream stream, TransportCo protected sealed override Task SerializeToStreamAsync(Stream stream, TransportContext? context, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(stream); - return Impl(stream, context, cancellationToken); + return Impl(stream, cancellationToken); - async Task Impl(Stream stream, TransportContext? context, CancellationToken cancellationToken) + async Task Impl(Stream stream, CancellationToken cancellationToken) { using (Stream contentStream = ConsumeStream()) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocksHelper.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocksHelper.cs index d6e73370b2804..25cee85afcd5a 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocksHelper.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocksHelper.cs @@ -39,15 +39,15 @@ public static async ValueTask EstablishSocksTunnelAsync(Stream stream, string ho if (string.Equals(proxyUri.Scheme, "socks5", StringComparison.OrdinalIgnoreCase)) { - await EstablishSocks5TunnelAsync(stream, host, port, proxyUri, credentials, async).ConfigureAwait(false); + await EstablishSocks5TunnelAsync(stream, host, port, credentials, async).ConfigureAwait(false); } else if (string.Equals(proxyUri.Scheme, "socks4a", StringComparison.OrdinalIgnoreCase)) { - await EstablishSocks4TunnelAsync(stream, isVersion4a: true, host, port, proxyUri, credentials, async, cancellationToken).ConfigureAwait(false); + await EstablishSocks4TunnelAsync(stream, isVersion4a: true, host, port, credentials, async, cancellationToken).ConfigureAwait(false); } else if (string.Equals(proxyUri.Scheme, "socks4", StringComparison.OrdinalIgnoreCase)) { - await EstablishSocks4TunnelAsync(stream, isVersion4a: false, host, port, proxyUri, credentials, async, cancellationToken).ConfigureAwait(false); + await EstablishSocks4TunnelAsync(stream, isVersion4a: false, host, port, credentials, async, cancellationToken).ConfigureAwait(false); } else { @@ -62,7 +62,7 @@ public static async ValueTask EstablishSocksTunnelAsync(Stream stream, string ho } } - private static async ValueTask EstablishSocks5TunnelAsync(Stream stream, string host, int port, Uri proxyUri, NetworkCredential? credentials, bool async) + private static async ValueTask EstablishSocks5TunnelAsync(Stream stream, string host, int port, NetworkCredential? credentials, bool async) { byte[] buffer = ArrayPool.Shared.Rent(BufferSize); try @@ -210,7 +210,7 @@ private static async ValueTask EstablishSocks5TunnelAsync(Stream stream, string } } - private static async ValueTask EstablishSocks4TunnelAsync(Stream stream, bool isVersion4a, string host, int port, Uri proxyUri, NetworkCredential? credentials, bool async, CancellationToken cancellationToken) + private static async ValueTask EstablishSocks4TunnelAsync(Stream stream, bool isVersion4a, string host, int port, NetworkCredential? credentials, bool async, CancellationToken cancellationToken) { byte[] buffer = ArrayPool.Shared.Rent(BufferSize); try diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs index 6fd15b4fbe36d..892d41c63c4a4 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs @@ -204,7 +204,7 @@ private ParsingResult ParseRawPath(Encoding encoding) else { // We found '%', but not followed by 'u', i.e. we have a percent encoded octed: %XX - if (!AddPercentEncodedOctetToRawOctetsList(encoding, _rawPath.Substring(index, 2))) + if (!AddPercentEncodedOctetToRawOctetsList(_rawPath.Substring(index, 2))) { return ParsingResult.InvalidString; } @@ -270,7 +270,7 @@ private bool AppendUnicodeCodePointValuePercentEncoded(string codePoint) return false; } - private bool AddPercentEncodedOctetToRawOctetsList(Encoding encoding, string escapedCharacter) + private bool AddPercentEncodedOctetToRawOctetsList(string escapedCharacter) { byte encodedValue; if (!byte.TryParse(escapedCharacter, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out encodedValue)) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs index 5cb7f73298a94..a6ab862a21ecc 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs @@ -210,19 +210,19 @@ public static void UnbindContext(HttpListenerContext context) } List? list = _unhandledPrefixes; - bestMatch = MatchFromList(host, path, list, out prefix); + bestMatch = MatchFromList(path, list, out prefix); if (path != pathSlash && bestMatch == null) - bestMatch = MatchFromList(host, pathSlash, list, out prefix); + bestMatch = MatchFromList(pathSlash, list, out prefix); if (bestMatch != null) return bestMatch; list = _allPrefixes; - bestMatch = MatchFromList(host, path, list, out prefix); + bestMatch = MatchFromList(path, list, out prefix); if (path != pathSlash && bestMatch == null) - bestMatch = MatchFromList(host, pathSlash, list, out prefix); + bestMatch = MatchFromList(pathSlash, list, out prefix); if (bestMatch != null) return bestMatch; @@ -230,7 +230,7 @@ public static void UnbindContext(HttpListenerContext context) return null; } - private static HttpListener? MatchFromList(string? host, string path, List? list, out ListenerPrefix? prefix) + private static HttpListener? MatchFromList(string path, List? list, out ListenerPrefix? prefix) { prefix = null; if (list == null) @@ -358,7 +358,7 @@ public void AddPrefix(ListenerPrefix prefix, HttpListener listener) } while (Interlocked.CompareExchange(ref _prefixes, p2, prefs) != prefs); } - public void RemovePrefix(ListenerPrefix prefix, HttpListener listener) + public void RemovePrefix(ListenerPrefix prefix) { List? current; List future; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointManager.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointManager.cs index 49b2b7318742a..4a4f64e2be5d5 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointManager.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointManager.cs @@ -210,7 +210,7 @@ private static void RemovePrefixInternal(string prefix, HttpListener listener) return; HttpEndPointListener epl = GetEPListener(lp.Host!, lp.Port, listener, lp.Secure); - epl.RemovePrefix(lp, listener); + epl.RemovePrefix(lp); } } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Certificates.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Certificates.cs index 60bfff006e2e4..4ecf9d836b532 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Certificates.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Certificates.cs @@ -16,10 +16,12 @@ internal static SslStream CreateSslStream(Stream innerStream, bool ownsStream, R return new SslStream(innerStream, ownsStream, callback); } +#pragma warning disable IDE0060 internal static X509Certificate? LoadCertificateAndKey(IPAddress addr, int port) { // TODO https://github.com/dotnet/runtime/issues/19752: Implement functionality to read SSL certificate. return null; } +#pragma warning restore IDE0060 } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs index 7a3670847451c..80686fc26a41b 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs @@ -95,7 +95,7 @@ public Task AcceptWebSocketAsync(string? subProtoc { WebSocketValidate.ValidateArraySegment(internalBuffer, nameof(internalBuffer)); HttpWebSocket.ValidateOptions(subProtocol, receiveBufferSize, HttpWebSocket.MinSendBufferSize, keepAliveInterval); - return HttpWebSocket.AcceptWebSocketAsyncCore(this, subProtocol, receiveBufferSize, keepAliveInterval, internalBuffer); + return HttpWebSocket.AcceptWebSocketAsyncCore(this, subProtocol, receiveBufferSize, keepAliveInterval); } } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerTimeoutManager.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerTimeoutManager.Managed.cs index 8289ed6200351..9711e36e20027 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerTimeoutManager.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerTimeoutManager.Managed.cs @@ -10,7 +10,7 @@ public class HttpListenerTimeoutManager private TimeSpan _drainEntityBody = TimeSpan.Zero; private TimeSpan _idleConnection = TimeSpan.Zero; - internal HttpListenerTimeoutManager(HttpListener listener) { } + internal HttpListenerTimeoutManager(HttpListener _) { } public TimeSpan DrainEntityBody { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/WebSockets/HttpWebSocket.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/WebSockets/HttpWebSocket.Managed.cs index e15457a40f902..b092a7893fafc 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/WebSockets/HttpWebSocket.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/WebSockets/HttpWebSocket.Managed.cs @@ -12,8 +12,7 @@ internal static partial class HttpWebSocket internal static async Task AcceptWebSocketAsyncCore(HttpListenerContext context, string? subProtocol, int receiveBufferSize, - TimeSpan keepAliveInterval, - ArraySegment? internalBuffer = null) + TimeSpan keepAliveInterval) { ValidateOptions(subProtocol, receiveBufferSize, MinSendBufferSize, keepAliveInterval); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs index 5a2b7c5d79367..8463d187a3b88 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs @@ -874,7 +874,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) else { binding = GetChannelBinding(session, connectionId, isSecureConnection, extendedProtectionPolicy); - ContextFlagsPal contextFlags = GetContextFlags(extendedProtectionPolicy, isSecureConnection); + ContextFlagsPal contextFlags = GetContextFlags(extendedProtectionPolicy); context = new NTAuthentication(true, package, CredentialCache.DefaultNetworkCredentials, null, contextFlags, binding); } @@ -1098,8 +1098,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) return null; } - challenges = BuildChallenge(authenticationScheme, connectionId, out newContext, - extendedProtectionPolicy, isSecureConnection); + challenges = BuildChallenge(authenticationScheme, out newContext); } } @@ -1242,12 +1241,10 @@ internal void SetAuthenticationHeaders(HttpListenerContext context) { Debug.Assert(context != null, "Null Context"); - HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; // We use the cached results from the delegates so that we don't have to call them again here. - ArrayList? challenges = BuildChallenge(context.AuthenticationSchemes, request._connectionId, - out _, context.ExtendedProtectionPolicy, request.IsSecureConnection); + ArrayList? challenges = BuildChallenge(context.AuthenticationSchemes, out _); // Setting 401 without setting WWW-Authenticate is a protocol violation // but throwing from HttpListener would be a breaking change. @@ -1421,7 +1418,7 @@ private static bool ScenarioChecksChannelBinding(bool isSecureConnection, Protec return (isSecureConnection && scenario == ProtectionScenario.TransportSelected); } - private static ContextFlagsPal GetContextFlags(ExtendedProtectionPolicy policy, bool isSecureConnection) + private static ContextFlagsPal GetContextFlags(ExtendedProtectionPolicy policy) { ContextFlagsPal result = ContextFlagsPal.Connection; if (policy.PolicyEnforcement != PolicyEnforcement.Never) @@ -1501,8 +1498,8 @@ private static void AddChallenge(ref ArrayList? challenges, string challenge) } } - private ArrayList? BuildChallenge(AuthenticationSchemes authenticationScheme, ulong connectionId, - out NTAuthentication? newContext, ExtendedProtectionPolicy policy, bool isSecureConnection) + private ArrayList? BuildChallenge(AuthenticationSchemes authenticationScheme, + out NTAuthentication? newContext) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "AuthenticationScheme:" + authenticationScheme.ToString()); ArrayList? challenges = null; @@ -1555,7 +1552,7 @@ private static void RegisterForDisconnectNotification(HttpListenerSession sessio if (statusCode == Interop.HttpApi.ERROR_SUCCESS && HttpListener.SkipIOCPCallbackOnSuccess) { // IO operation completed synchronously - callback won't be called to signal completion. - result.IOCompleted(statusCode, 0, result.NativeOverlapped); + result.IOCompleted(result.NativeOverlapped); } } catch (Win32Exception exception) @@ -1835,12 +1832,12 @@ internal void FinishOwningDisconnectHandling() } } - internal unsafe void IOCompleted(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) + internal unsafe void IOCompleted(NativeOverlapped* nativeOverlapped) { - IOCompleted(this, errorCode, numBytes, nativeOverlapped); + IOCompleted(this, nativeOverlapped); } - private static unsafe void IOCompleted(DisconnectAsyncResult asyncResult, uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) + private static unsafe void IOCompleted(DisconnectAsyncResult asyncResult, NativeOverlapped* nativeOverlapped) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, "_connectionId:" + asyncResult._connectionId); @@ -1856,7 +1853,7 @@ private static unsafe void WaitCallback(uint errorCode, uint numBytes, NativeOve if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"errorCode: {errorCode}, numBytes: {numBytes}, nativeOverlapped: {(IntPtr)nativeOverlapped:x}"); // take the DisconnectAsyncResult object from the state DisconnectAsyncResult asyncResult = (DisconnectAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; - IOCompleted(asyncResult, errorCode, numBytes, nativeOverlapped); + IOCompleted(asyncResult, nativeOverlapped); } private void HandleDisconnect() diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs index 7ea7b16d9d942..fbdeb8f50f4df 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs @@ -134,7 +134,7 @@ private void UpdateAfterRead(uint statusCode, uint dataRead) dataRead = Interop.HttpApi.GetChunks(_httpContext.Request.RequestBuffer, _httpContext.Request.OriginalBlobAddress, ref _dataChunkIndex, ref _dataChunkOffset, buffer, offset, size); if (_dataChunkIndex != -1 && dataRead == size) { - asyncResult = new HttpRequestStreamAsyncResult(_httpContext.RequestQueueBoundHandle, this, state, callback, buffer, offset, (uint)size, 0); + asyncResult = new HttpRequestStreamAsyncResult(_httpContext.RequestQueueBoundHandle, this, state, callback, buffer, offset, 0); asyncResult.InvokeCallback(dataRead); } } @@ -152,7 +152,7 @@ private void UpdateAfterRead(uint statusCode, uint dataRead) size = MaxReadSize; } - asyncResult = new HttpRequestStreamAsyncResult(_httpContext.RequestQueueBoundHandle, this, state, callback, buffer, offset, (uint)size, dataRead); + asyncResult = new HttpRequestStreamAsyncResult(_httpContext.RequestQueueBoundHandle, this, state, callback, buffer, offset, dataRead); uint bytesReturned; try @@ -288,7 +288,7 @@ internal HttpRequestStreamAsyncResult(object asyncObject, object? userState, Asy _dataAlreadyRead = dataAlreadyRead; } - internal HttpRequestStreamAsyncResult(ThreadPoolBoundHandle boundHandle, object asyncObject, object? userState, AsyncCallback? callback, byte[] buffer, int offset, uint size, uint dataAlreadyRead) : base(asyncObject, userState, callback) + internal HttpRequestStreamAsyncResult(ThreadPoolBoundHandle boundHandle, object asyncObject, object? userState, AsyncCallback? callback, byte[] buffer, int offset, uint dataAlreadyRead) : base(asyncObject, userState, callback) { _dataAlreadyRead = dataAlreadyRead; _boundHandle = boundHandle; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs index 438e36c85b503..555be7683fd91 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs @@ -1451,7 +1451,7 @@ protected virtual void ProcessAction_IndicateReceiveComplete( int count = 0; try { - ArraySegment payload = _webSocket._internalBuffer.ConvertNativeBuffer(action, dataBuffers[0], bufferType); + ArraySegment payload = _webSocket._internalBuffer.ConvertNativeBuffer(dataBuffers[0], bufferType); ReleaseLock(_webSocket.SessionHandle, ref sessionHandleLockTaken); HttpWebSocket.ThrowIfConnectionAborted(_webSocket._innerStream, true); @@ -1509,7 +1509,7 @@ protected virtual void ProcessAction_IndicateReceiveComplete( List> sendBuffers = new List>((int)dataBufferCount); int sendBufferSize = 0; - ArraySegment framingBuffer = _webSocket._internalBuffer.ConvertNativeBuffer(action, dataBuffers[0], bufferType); + ArraySegment framingBuffer = _webSocket._internalBuffer.ConvertNativeBuffer(dataBuffers[0], bufferType); sendBuffers.Add(framingBuffer); sendBufferSize += framingBuffer.Count; @@ -1530,7 +1530,7 @@ protected virtual void ProcessAction_IndicateReceiveComplete( } else { - payload = _webSocket._internalBuffer.ConvertNativeBuffer(action, dataBuffers[1], bufferType); + payload = _webSocket._internalBuffer.ConvertNativeBuffer(dataBuffers[1], bufferType); } sendBuffers.Add(payload); @@ -1716,14 +1716,14 @@ protected override void ProcessAction_IndicateReceiveComplete( if (bufferType == WebSocketProtocolComponent.BufferType.Close) { payload = ArraySegment.Empty; - _webSocket._internalBuffer.ConvertCloseBuffer(action, dataBuffers[0], out WebSocketCloseStatus closeStatus, out string? reason); + _webSocket._internalBuffer.ConvertCloseBuffer(dataBuffers[0], out WebSocketCloseStatus closeStatus, out string? reason); receiveResult = new WebSocketReceiveResult(bytesTransferred, messageType, true, closeStatus, reason); } else { - payload = _webSocket._internalBuffer.ConvertNativeBuffer(action, dataBuffers[0], bufferType); + payload = _webSocket._internalBuffer.ConvertNativeBuffer(dataBuffers[0], bufferType); bool endOfMessage = bufferType == WebSocketProtocolComponent.BufferType.BinaryMessage || diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs index 712b0d7f39d66..8a4998ce49da7 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs @@ -351,7 +351,7 @@ internal bool ReceiveFromBufferedPayload(ArraySegment buffer, out WebSocke return morePayloadBuffered; } - internal ArraySegment ConvertNativeBuffer(WebSocketProtocolComponent.Action action, + internal ArraySegment ConvertNativeBuffer( Interop.WebSocket.Buffer buffer, WebSocketProtocolComponent.BufferType bufferType) { @@ -380,7 +380,7 @@ internal ArraySegment ConvertNativeBuffer(WebSocketProtocolComponent.Actio throw new AccessViolationException(); } - internal void ConvertCloseBuffer(WebSocketProtocolComponent.Action action, + internal void ConvertCloseBuffer( Interop.WebSocket.Buffer buffer, out WebSocketCloseStatus closeStatus, out string? reason) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs index 406ecafc1eeeb..b1f4a764a3eb6 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs @@ -191,7 +191,7 @@ private async Task ReadAsyncCore(byte[] buffer, int offset, int count, Canc // true: async completion or error private unsafe bool ReadAsyncFast(HttpListenerAsyncEventArgs eventArgs) { - eventArgs.StartOperationCommon(this, _inputStream.InternalHttpContext.RequestQueueBoundHandle); + eventArgs.StartOperationCommon(_inputStream.InternalHttpContext.RequestQueueBoundHandle); eventArgs.StartOperationReceive(); bool completedAsynchronouslyOrWithError; @@ -440,7 +440,7 @@ private unsafe bool WriteAsyncFast(HttpListenerAsyncEventArgs eventArgs) { Interop.HttpApi.HTTP_FLAGS flags = Interop.HttpApi.HTTP_FLAGS.NONE; - eventArgs.StartOperationCommon(this, _outputStream.InternalHttpContext.RequestQueueBoundHandle); + eventArgs.StartOperationCommon(_outputStream.InternalHttpContext.RequestQueueBoundHandle); eventArgs.StartOperationSend(); uint statusCode; @@ -927,7 +927,7 @@ private unsafe void FreeOverlapped(bool checkForShutdown) // Method called to prepare for a native async http.sys call. // This method performs the tasks common to all http.sys operations. - internal void StartOperationCommon(WebSocketHttpListenerDuplexStream currentStream, ThreadPoolBoundHandle boundHandle) + internal void StartOperationCommon(ThreadPoolBoundHandle boundHandle) { // Change status to "in-use". if (Interlocked.CompareExchange(ref _operating, InProgress, Free) != Free) diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/Attachment.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/Attachment.cs index ab7c7098ef200..8c646058a8e38 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/Attachment.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/Attachment.cs @@ -133,10 +133,10 @@ internal void SetContentFromString(string content, Encoding? encoding, string? m int offset = 0; try { - string value = MailBnfHelper.ReadToken(mediaType, ref offset, null); + string value = MailBnfHelper.ReadToken(mediaType, ref offset); if (value.Length == 0 || offset >= mediaType.Length || mediaType[offset++] != '/') throw new ArgumentException(SR.MediaTypeInvalid, nameof(mediaType)); - value = MailBnfHelper.ReadToken(mediaType, ref offset, null); + value = MailBnfHelper.ReadToken(mediaType, ref offset); if (value.Length == 0 || offset < mediaType.Length) { throw new ArgumentException(SR.MediaTypeInvalid, nameof(mediaType)); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailBnfHelper.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailBnfHelper.cs index b932fa90f0667..be5ca6c69511d 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailBnfHelper.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailBnfHelper.cs @@ -243,15 +243,15 @@ internal static void ValidateHeaderName(string data) throw new FormatException(SR.MailHeaderFieldMalformedHeader); } - internal static string? ReadParameterAttribute(string data, ref int offset, StringBuilder? builder) + internal static string? ReadParameterAttribute(string data, ref int offset) { if (!SkipCFWS(data, ref offset)) return null; // - return ReadToken(data, ref offset, null); + return ReadToken(data, ref offset); } - internal static string ReadToken(string data, ref int offset, StringBuilder? builder) + internal static string ReadToken(string data, ref int offset) { int start = offset; for (; offset < data.Length; offset++) diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailMessage.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailMessage.cs index 9487709fd2344..c260999b2e15f 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailMessage.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailMessage.cs @@ -431,11 +431,11 @@ internal void Send(BaseWriter writer, bool sendEnvelope, bool allowUnicode) _message.Send(writer, sendEnvelope, allowUnicode); } - internal IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, bool allowUnicode, + internal IAsyncResult BeginSend(BaseWriter writer, bool allowUnicode, AsyncCallback? callback, object? state) { SetContent(allowUnicode); - return _message.BeginSend(writer, sendEnvelope, allowUnicode, callback, state); + return _message.BeginSend(writer, allowUnicode, callback, state); } internal void EndSend(IAsyncResult asyncResult) diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs index 81a7c54d873ed..db52511ec6ebb 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs @@ -273,10 +273,10 @@ internal EmptySendContext(BaseWriter writer, LazyAsyncResult result) internal BaseWriter _writer; } - internal IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, bool allowUnicode, + internal IAsyncResult BeginSend(BaseWriter writer, bool allowUnicode, AsyncCallback? callback, object? state) { - PrepareHeaders(sendEnvelope, allowUnicode); + PrepareHeaders(allowUnicode); writer.WriteHeaders(Headers, allowUnicode); if (Content != null) @@ -331,11 +331,11 @@ internal void Send(BaseWriter writer, bool sendEnvelope, bool allowUnicode) { if (sendEnvelope) { - PrepareEnvelopeHeaders(sendEnvelope, allowUnicode); + PrepareEnvelopeHeaders(allowUnicode); writer.WriteHeaders(EnvelopeHeaders, allowUnicode); } - PrepareHeaders(sendEnvelope, allowUnicode); + PrepareHeaders(allowUnicode); writer.WriteHeaders(Headers, allowUnicode); if (Content != null) @@ -348,7 +348,7 @@ internal void Send(BaseWriter writer, bool sendEnvelope, bool allowUnicode) } } - internal void PrepareEnvelopeHeaders(bool sendEnvelope, bool allowUnicode) + internal void PrepareEnvelopeHeaders(bool allowUnicode) { _headersEncoding ??= Encoding.GetEncoding(MimeBasePart.DefaultCharSet); @@ -379,7 +379,7 @@ internal void PrepareEnvelopeHeaders(bool sendEnvelope, bool allowUnicode) } } - internal void PrepareHeaders(bool sendEnvelope, bool allowUnicode) + internal void PrepareHeaders(bool allowUnicode) { _headersEncoding ??= Encoding.GetEncoding(MimeBasePart.DefaultCharSet); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs index 45c3664531ba5..d323c244dda87 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs @@ -938,7 +938,7 @@ private void SendMailCallback(IAsyncResult result) } else { - _message!.BeginSend(_writer, DeliveryMethod != SmtpDeliveryMethod.Network, + _message!.BeginSend(_writer, IsUnicodeSupported(), new AsyncCallback(SendMessageCallback), result.AsyncState!); } } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpException.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpException.cs index 4cbafad5d23ac..aa59188d74888 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpException.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpException.cs @@ -97,7 +97,7 @@ protected SmtpException(SerializationInfo serializationInfo, StreamingContext st _statusCode = (SmtpStatusCode)serializationInfo.GetInt32("Status"); } - internal SmtpException(SmtpStatusCode statusCode, string? serverMessage, bool serverResponse) : base(GetMessageForStatus(statusCode, serverMessage)) + internal SmtpException(SmtpStatusCode statusCode, string? serverMessage, bool _) : base(GetMessageForStatus(statusCode, serverMessage)) { _statusCode = statusCode; } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/ContentDisposition.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/ContentDisposition.cs index 5d72c47d81f12..8b60f28abce51 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/ContentDisposition.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/ContentDisposition.cs @@ -257,7 +257,7 @@ private void ParseValue() try { // the disposition MUST be the first parameter in the string - _dispositionType = MailBnfHelper.ReadToken(_disposition, ref offset, null); + _dispositionType = MailBnfHelper.ReadToken(_disposition, ref offset); // disposition MUST not be empty if (string.IsNullOrEmpty(_dispositionType)) @@ -290,7 +290,7 @@ private void ParseValue() break; } - string? paramAttribute = MailBnfHelper.ReadParameterAttribute(_disposition, ref offset, null); + string? paramAttribute = MailBnfHelper.ReadParameterAttribute(_disposition, ref offset); string? paramValue; // verify the next character after the parameter is correct @@ -308,7 +308,7 @@ private void ParseValue() paramValue = _disposition[offset] == '"' ? MailBnfHelper.ReadQuotedString(_disposition, ref offset, null) : - MailBnfHelper.ReadToken(_disposition, ref offset, null); + MailBnfHelper.ReadToken(_disposition, ref offset); // paramValue could potentially still be empty if it was a valid quoted string that // contained no inner value. this is invalid diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/ContentType.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/ContentType.cs index 08bcb5e7c6e72..9ca001fd00a2c 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/ContentType.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/ContentType.cs @@ -95,11 +95,11 @@ public string MediaType ArgumentException.ThrowIfNullOrEmpty(value); int offset = 0; - _mediaType = MailBnfHelper.ReadToken(value, ref offset, null); + _mediaType = MailBnfHelper.ReadToken(value, ref offset); if (_mediaType.Length == 0 || offset >= value.Length || value[offset++] != '/') throw new FormatException(SR.MediaTypeInvalid); - _subType = MailBnfHelper.ReadToken(value, ref offset, null); + _subType = MailBnfHelper.ReadToken(value, ref offset); if (_subType.Length == 0 || offset < value.Length) { throw new FormatException(SR.MediaTypeInvalid); @@ -223,13 +223,13 @@ private void ParseValue() { int offset = 0; - _mediaType = MailBnfHelper.ReadToken(_type, ref offset, null); + _mediaType = MailBnfHelper.ReadToken(_type, ref offset); if (_mediaType == null || _mediaType.Length == 0 || offset >= _type.Length || _type[offset++] != '/') { throw new FormatException(SR.ContentTypeInvalid); } - _subType = MailBnfHelper.ReadToken(_type, ref offset, null); + _subType = MailBnfHelper.ReadToken(_type, ref offset); if (_subType == null || _subType.Length == 0) { throw new FormatException(SR.ContentTypeInvalid); @@ -247,7 +247,7 @@ private void ParseValue() break; } - string? paramAttribute = MailBnfHelper.ReadParameterAttribute(_type, ref offset, null); + string? paramAttribute = MailBnfHelper.ReadParameterAttribute(_type, ref offset); if (paramAttribute == null || paramAttribute.Length == 0) { @@ -267,7 +267,7 @@ private void ParseValue() paramValue = _type[offset] == '"' ? MailBnfHelper.ReadQuotedString(_type, ref offset, null) : - MailBnfHelper.ReadToken(_type, ref offset, null); + MailBnfHelper.ReadToken(_type, ref offset); if (paramValue == null) { diff --git a/src/libraries/System.Net.Mail/tests/Unit/MessageTests/MessageHeaderBehaviorTest.cs b/src/libraries/System.Net.Mail/tests/Unit/MessageTests/MessageHeaderBehaviorTest.cs index f31df3d6f754f..43436e68d6cc3 100644 --- a/src/libraries/System.Net.Mail/tests/Unit/MessageTests/MessageHeaderBehaviorTest.cs +++ b/src/libraries/System.Net.Mail/tests/Unit/MessageTests/MessageHeaderBehaviorTest.cs @@ -17,7 +17,7 @@ public void Message_WithXSenderHeaderSet_ShouldNotOverwriteXSender() _message.From = new MailAddress("test@example.com"); _message.HeadersEncoding = Encoding.UTF8; - _message.PrepareEnvelopeHeaders(true, false); + _message.PrepareEnvelopeHeaders(false); _message.EncodeHeaders(_message.Headers, false); Assert.Equal("test@networking.com", _message.Headers["X-Sender"]); @@ -29,7 +29,7 @@ public void Message_WithNoXSender_ShouldSetXSenderToFromAddress() _message.From = new MailAddress("test@example.com"); _message.HeadersEncoding = Encoding.UTF8; - _message.PrepareEnvelopeHeaders(true, false); + _message.PrepareEnvelopeHeaders(false); _message.EncodeHeaders(_message.Headers, false); _message.EncodeHeaders(_message.EnvelopeHeaders, false); @@ -45,7 +45,7 @@ public void Message_WithXReceiverSetByUser_ShouldNotClearXReceiverHeader() _message.To.Add(new MailAddress("to@example.com")); _message.HeadersEncoding = Encoding.UTF8; - _message.PrepareEnvelopeHeaders(true, false); + _message.PrepareEnvelopeHeaders(false); Assert.NotNull(_message.EnvelopeHeaders.GetValues("X-Receiver")); _message.EncodeHeaders(_message.EnvelopeHeaders, false); _message.EncodeHeaders(_message.Headers, false); @@ -62,7 +62,7 @@ public void Message_WithBccAddresses_ShouldSetXReceiverHeaderForBccAddresses() _message.HeadersEncoding = Encoding.UTF8; _message.Bcc.Add("shouldbeset@example.com"); - _message.PrepareEnvelopeHeaders(true, false); + _message.PrepareEnvelopeHeaders(false); string[] xReceivers = _message.EnvelopeHeaders.GetValues("X-Receiver"); Assert.True(xReceivers.Length == 2); } @@ -99,7 +99,7 @@ public void Message_WithTo_WithCc_WithBcc_WithReplyToList_ShouldBeSingletons_Sho _message.Bcc.Add(new MailAddress(validBcc)); _message.ReplyToList.Add(new MailAddress(validReplyTo)); - _message.PrepareHeaders(true, false); + _message.PrepareHeaders(false); string[] fromHeaders = _message.Headers.GetValues("From"); string[] toHeaders = _message.Headers.GetValues("To"); @@ -131,7 +131,7 @@ public void MessagePriority_WithValueSetByHeader_AndImportanceNotSet_ShouldRespe _message.Headers.Add("Importance", "low"); _message.Headers.Add("X-Priority", "5"); - _message.PrepareHeaders(true, false); + _message.PrepareHeaders(false); Assert.Equal(MailPriority.Normal, _message.Priority); @@ -150,7 +150,7 @@ public void MessageSubject_WhenSetViaHeaders_AndSubjectPropertyIsSet_ShouldUsePr _message.From = new MailAddress("from@example.com"); _message.Headers.Add("Subject", "should be removed"); _message.Subject = "correct subject"; - _message.PrepareHeaders(true, false); + _message.PrepareHeaders(false); Assert.Equal("correct subject", _message.Subject); Assert.True(_message.Headers.GetValues("Subject").Length == 1); @@ -163,7 +163,7 @@ public void MessageSubject_WhenEmpty_WithHeaderSet_ShouldDiscardHeaderAndLeaveSu _message.From = new MailAddress("from@example.com"); _message.Headers.Add("Subject", "should be removed"); _message.Subject = string.Empty; - _message.PrepareHeaders(true, false); + _message.PrepareHeaders(false); Assert.Equal(string.Empty, _message.Subject); Assert.Null(_message.Headers["Subject"]); @@ -179,7 +179,7 @@ public void MessageSubject_Unicode_Accepted() Assert.Equal(Encoding.UTF8, _message.SubjectEncoding); - _message.PrepareHeaders(true, false); + _message.PrepareHeaders(false); Assert.Equal(input, _message.Subject); Assert.Equal("=?utf-8?B?SGkgw5wgQm9i?=", _message.Headers["Subject"]); @@ -195,7 +195,7 @@ public void MessageSubject_Utf8EncodedUnicode_Accepted() Assert.Equal(Encoding.UTF8, _message.SubjectEncoding); - _message.PrepareHeaders(true, false); + _message.PrepareHeaders(false); Assert.Equal("Hi \u00DC Bob", _message.Subject); Assert.Equal(input, _message.Headers["Subject"]); @@ -211,7 +211,7 @@ public void MessageSubject_UnknownEncodingEncodedUnicode_Accepted() Assert.Null(_message.SubjectEncoding); - _message.PrepareHeaders(true, false); + _message.PrepareHeaders(false); Assert.Equal(input, _message.Subject); Assert.Equal(input, _message.Headers["Subject"]); @@ -227,7 +227,7 @@ public void MessageSubject_BadBase64EncodedUnicode_Accepted() Assert.Null(_message.SubjectEncoding); - _message.PrepareHeaders(true, false); + _message.PrepareHeaders(false); Assert.Equal(input, _message.Subject); Assert.Equal(input, _message.Headers["Subject"]); @@ -243,7 +243,7 @@ public void MessageSubject_MultiLineEncodedUnicode_Accepted() Assert.Equal(Encoding.UTF8, _message.SubjectEncoding); - _message.PrepareHeaders(true, false); + _message.PrepareHeaders(false); Assert.Equal("Hi \u00DC Bob", _message.Subject); Assert.Equal("=?utf-8?B?SGkgw5wgQm9i?=", _message.Headers["Subject"]); @@ -254,7 +254,7 @@ public void MessageContentTypeHeader_WhenSetByUser_ShouldBeDiscarded() { _message.From = new MailAddress("from@example.com"); _message.Headers.Add("Content-Type", "should be removed"); - _message.PrepareHeaders(true, false); + _message.PrepareHeaders(false); // Content type header should be removed. Assert.Null(_message.Headers["Content-Type"]); diff --git a/src/libraries/System.Net.Mail/tests/Unit/MessageTests/ReplyToListTest.cs b/src/libraries/System.Net.Mail/tests/Unit/MessageTests/ReplyToListTest.cs index 71e303fc757e6..76c5e2c9c9981 100644 --- a/src/libraries/System.Net.Mail/tests/Unit/MessageTests/ReplyToListTest.cs +++ b/src/libraries/System.Net.Mail/tests/Unit/MessageTests/ReplyToListTest.cs @@ -35,7 +35,7 @@ public void PrepareHeaders_WithReplyToSet_ShouldIgnoreReplyToList() _message.From = new MailAddress("from@example.com"); - _message.PrepareHeaders(true, false); + _message.PrepareHeaders(false); Assert.Equal(2, _message.ReplyToList.Count); @@ -60,7 +60,7 @@ public void PrepareHeaders_WithReplyToNull_AndReplyToListSet_ShouldUseReplyToLis _message.From = new MailAddress("from@example.com"); - _message.PrepareHeaders(true, false); + _message.PrepareHeaders(false); Assert.Equal(3, _message.ReplyToList.Count); @@ -89,7 +89,7 @@ public void PrepareHeaders_WithReplyToListSet_AndReplyToHeaderSetManually_Should _message.From = new MailAddress("from@example.com"); - _message.PrepareHeaders(true, false); + _message.PrepareHeaders(false); Assert.True(_message.ReplyToList.Count == 3, "ReplyToList did not contain all email addresses"); diff --git a/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs b/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs index 8350340d7a2e5..e05861df757f4 100644 --- a/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs +++ b/src/libraries/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs @@ -16,8 +16,10 @@ internal static partial class NameResolutionPal { public const bool SupportsGetAddrInfoAsync = false; +#pragma warning disable IDE0060 internal static Task? GetAddrInfoAsync(string hostName, bool justAddresses, AddressFamily family, CancellationToken cancellationToken) => throw new NotSupportedException(); +#pragma warning restore IDE0060 private static SocketError GetSocketErrorForNativeError(int error) { diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs index c52263fcf6de8..75572bc56f871 100644 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs +++ b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.cs @@ -42,9 +42,9 @@ public Ping() } } - private void CheckArgs(int timeout, byte[] buffer, PingOptions? options) + private void CheckArgs(int timeout, byte[] buffer) { - CheckDisposed(); + ObjectDisposedException.ThrowIf(_disposeRequested, this); ArgumentNullException.ThrowIfNull(buffer); if (buffer.Length > MaxBufferSize) @@ -58,9 +58,9 @@ private void CheckArgs(int timeout, byte[] buffer, PingOptions? options) } } - private void CheckArgs(IPAddress address, int timeout, byte[] buffer, PingOptions? options) + private void CheckArgs(IPAddress address, int timeout, byte[] buffer) { - CheckArgs(timeout, buffer, options); + CheckArgs(timeout, buffer); ArgumentNullException.ThrowIfNull(address); @@ -363,7 +363,7 @@ public PingReply Send(string hostNameOrAddress, int timeout, byte[] buffer, Ping return Send(address, timeout, buffer, options); } - CheckArgs(timeout, buffer, options); + CheckArgs(timeout, buffer); return GetAddressAndSend(hostNameOrAddress, timeout, buffer, options); } @@ -398,7 +398,7 @@ public PingReply Send(string hostNameOrAddress, int timeout, byte[] buffer, Ping /// This object has been disposed. public PingReply Send(IPAddress address, int timeout, byte[] buffer, PingOptions? options) { - CheckArgs(address, timeout, buffer, options); + CheckArgs(address, timeout, buffer); // Need to snapshot the address here, so we're sure that it's not changed between now // and the operation, and to be sure that IPAddress.ToString() is called and not some override. @@ -590,7 +590,7 @@ public Task SendPingAsync(IPAddress address, TimeSpan timeout, byte[] private Task SendPingAsync(IPAddress address, int timeout, byte[] buffer, PingOptions? options, CancellationToken cancellationToken) { - CheckArgs(address, timeout, buffer, options); + CheckArgs(address, timeout, buffer); return SendPingAsyncInternal( // Need to snapshot the address here, so we're sure that it's not changed between now @@ -643,7 +643,7 @@ private Task SendPingAsync(string hostNameOrAddress, int timeout, byt return SendPingAsync(address, timeout, buffer, options, cancellationToken); } - CheckArgs(timeout, buffer, options); + CheckArgs(timeout, buffer); return SendPingAsyncInternal( hostNameOrAddress, diff --git a/src/libraries/System.Net.Primitives/src/System/Net/SocketException.Windows.cs b/src/libraries/System.Net.Primitives/src/System/Net/SocketException.Windows.cs index 8952b76109403..3950bb32fdbde 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/SocketException.Windows.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/SocketException.Windows.cs @@ -13,7 +13,7 @@ public SocketException() : this(Marshal.GetLastPInvokeError()) { } - internal SocketException(SocketError errorCode, uint platformError) + internal SocketException(SocketError errorCode, uint _ /*platformError*/) : this(errorCode) { // platformError is unused on Windows. It's the same value as errorCode. diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/QuicConnection.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/QuicConnection.cs index 94f0ad52c8a2d..d46ce9ecff409 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/QuicConnection.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/QuicConnection.cs @@ -482,7 +482,7 @@ private unsafe int HandleEventShutdownInitiatedByPeer(ref SHUTDOWN_INITIATED_BY_ _acceptQueue.Writer.TryComplete(ExceptionDispatchInfo.SetCurrentStackTrace(ThrowHelper.GetConnectionAbortedException((long)data.ErrorCode))); return QUIC_STATUS_SUCCESS; } - private unsafe int HandleEventShutdownComplete(ref SHUTDOWN_COMPLETE_DATA data) + private unsafe int HandleEventShutdownComplete() { if (NetEventSource.Log.IsEnabled()) { @@ -568,7 +568,7 @@ private unsafe int HandleConnectionEvent(ref QUIC_CONNECTION_EVENT connectionEve QUIC_CONNECTION_EVENT_TYPE.CONNECTED => HandleEventConnected(ref connectionEvent.CONNECTED), QUIC_CONNECTION_EVENT_TYPE.SHUTDOWN_INITIATED_BY_TRANSPORT => HandleEventShutdownInitiatedByTransport(ref connectionEvent.SHUTDOWN_INITIATED_BY_TRANSPORT), QUIC_CONNECTION_EVENT_TYPE.SHUTDOWN_INITIATED_BY_PEER => HandleEventShutdownInitiatedByPeer(ref connectionEvent.SHUTDOWN_INITIATED_BY_PEER), - QUIC_CONNECTION_EVENT_TYPE.SHUTDOWN_COMPLETE => HandleEventShutdownComplete(ref connectionEvent.SHUTDOWN_COMPLETE), + QUIC_CONNECTION_EVENT_TYPE.SHUTDOWN_COMPLETE => HandleEventShutdownComplete(), QUIC_CONNECTION_EVENT_TYPE.LOCAL_ADDRESS_CHANGED => HandleEventLocalAddressChanged(ref connectionEvent.LOCAL_ADDRESS_CHANGED), QUIC_CONNECTION_EVENT_TYPE.PEER_ADDRESS_CHANGED => HandleEventPeerAddressChanged(ref connectionEvent.PEER_ADDRESS_CHANGED), QUIC_CONNECTION_EVENT_TYPE.PEER_STREAM_STARTED => HandleEventPeerStreamStarted(ref connectionEvent.PEER_STREAM_STARTED), diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/QuicListener.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/QuicListener.cs index 4634d3e8e486e..de41265c05c96 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/QuicListener.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/QuicListener.cs @@ -201,7 +201,7 @@ private unsafe int HandleEventNewConnection(ref NEW_CONNECTION_DATA data) return QUIC_STATUS_SUCCESS; } - private unsafe int HandleEventStopComplete(ref STOP_COMPLETE_DATA data) + private unsafe int HandleEventStopComplete() { _shutdownTcs.TrySetResult(); return QUIC_STATUS_SUCCESS; @@ -211,7 +211,7 @@ private unsafe int HandleListenerEvent(ref QUIC_LISTENER_EVENT listenerEvent) => listenerEvent.Type switch { QUIC_LISTENER_EVENT_TYPE.NEW_CONNECTION => HandleEventNewConnection(ref listenerEvent.NEW_CONNECTION), - QUIC_LISTENER_EVENT_TYPE.STOP_COMPLETE => HandleEventStopComplete(ref listenerEvent.STOP_COMPLETE), + QUIC_LISTENER_EVENT_TYPE.STOP_COMPLETE => HandleEventStopComplete(), _ => QUIC_STATUS_SUCCESS }; diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs index 23940240517d6..383115cfd94fd 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs @@ -317,7 +317,7 @@ protected override PipelineInstruction PipelineCallback(PipelineEntry? entry, Re if (entry.HasFlag(PipelineEntryFlags.CreateDataConnection) && (response.PositiveCompletion || response.PositiveIntermediate)) { bool isSocketReady; - PipelineInstruction result = QueueOrCreateDataConection(entry, response, timeout, ref stream, out isSocketReady); + PipelineInstruction result = QueueOrCreateDataConection(entry, response, out isSocketReady); if (!isSocketReady) return result; // otherwise we have a stream to create @@ -573,8 +573,8 @@ protected override PipelineEntry[] BuildCommandsList(WebRequest req) else { string portCommand = (ServerAddress.AddressFamily == AddressFamily.InterNetwork || ServerAddress.IsIPv4MappedToIPv6) ? "PORT" : "EPRT"; - CreateFtpListenerSocket(request); - commandList.Add(new PipelineEntry(FormatFtpCommand(portCommand, GetPortCommandLine(request)))); + CreateFtpListenerSocket(); + commandList.Add(new PipelineEntry(FormatFtpCommand(portCommand, GetPortCommandLine()))); } if (request.ContentOffset > 0) @@ -627,7 +627,7 @@ protected override PipelineEntry[] BuildCommandsList(WebRequest req) return commandList.ToArray(); } - private PipelineInstruction QueueOrCreateDataConection(PipelineEntry entry, ResponseDescription response, bool timeout, ref Stream? stream, out bool isSocketReady) + private PipelineInstruction QueueOrCreateDataConection(PipelineEntry entry, ResponseDescription response, out bool isSocketReady) { isSocketReady = false; if (_dataHandshakeStarted) @@ -667,7 +667,7 @@ private PipelineInstruction QueueOrCreateDataConection(PipelineEntry entry, Resp try { - _dataSocket = CreateFtpDataSocket((FtpWebRequest)_request!, Socket); + _dataSocket = CreateFtpDataSocket(Socket); } catch (ObjectDisposedException) { @@ -1064,13 +1064,13 @@ private static int GetPortV6(string responseString) /// /// Creates the Listener socket /// - private void CreateFtpListenerSocket(FtpWebRequest request) + private void CreateFtpListenerSocket() { // Gets an IPEndPoint for the local host for the data socket to bind to. IPEndPoint epListener = new IPEndPoint(((IPEndPoint)Socket.LocalEndPoint!).Address, 0); try { - _dataSocket = CreateFtpDataSocket(request, Socket); + _dataSocket = CreateFtpDataSocket(Socket); } catch (ObjectDisposedException) { @@ -1085,7 +1085,7 @@ private void CreateFtpListenerSocket(FtpWebRequest request) /// /// Builds a command line to send to the server with proper port and IP address of client /// - private string GetPortCommandLine(FtpWebRequest request) + private string GetPortCommandLine() { try { @@ -1125,7 +1125,7 @@ private static string FormatFtpCommand(string command, string? parameter) /// This will handle either connecting to a port or listening for one /// /// - private static Socket CreateFtpDataSocket(FtpWebRequest request, Socket templateSocket) + private static Socket CreateFtpDataSocket(Socket templateSocket) { // Safe to be called under an Assert. Socket socket = new Socket(templateSocket.AddressFamily, templateSocket.SocketType, templateSocket.ProtocolType); diff --git a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs index 4dd5ff5ac2681..4973ce3940258 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs @@ -580,7 +580,7 @@ public override WebResponse GetResponse() FinishRequestStage(RequestStage.ReadReady); CheckError(); - EnsureFtpWebResponse(null); + EnsureFtpWebResponse(); } } catch (Exception exception) @@ -1105,7 +1105,7 @@ private void SetException(Exception exception) { if (exception is WebException) { - EnsureFtpWebResponse(exception); + EnsureFtpWebResponse(); _exception = new WebException(exception.Message, null, ((WebException)exception).Status, _ftpWebResponse); } else if (exception is AuthenticationException || exception is SecurityException) @@ -1114,7 +1114,7 @@ private void SetException(Exception exception) } else if (connection != null && connection.StatusCode != FtpStatusCode.Undefined) { - EnsureFtpWebResponse(exception); + EnsureFtpWebResponse(); _exception = new WebException(SR.Format(SR.net_ftp_servererror, connection.StatusLine), exception, WebExceptionStatus.ProtocolError, _ftpWebResponse); } else @@ -1174,7 +1174,7 @@ private void SyncRequestCallback(object? obj) if (connection != null) { - EnsureFtpWebResponse(null); + EnsureFtpWebResponse(); // This to update response status and exit message if any. // Note that status 221 "Service closing control connection" is always suppressed. @@ -1268,7 +1268,7 @@ private void AsyncRequestCallback(object? obj) } stream.SetSocketTimeoutOption(Timeout); - EnsureFtpWebResponse(null); + EnsureFtpWebResponse(); stageMode = stream.CanRead ? RequestStage.ReadReady : RequestStage.WriteReady; } @@ -1278,7 +1278,7 @@ private void AsyncRequestCallback(object? obj) if (connection != null) { - EnsureFtpWebResponse(null); + EnsureFtpWebResponse(); // This to update response status and exit message if any. // Note that the status 221 "Service closing control connection" is always suppressed. @@ -1626,7 +1626,7 @@ private bool InUse /// /// Creates an FTP WebResponse based off the responseStream and our active Connection /// - private void EnsureFtpWebResponse(Exception? exception) + private void EnsureFtpWebResponse() { if (_ftpWebResponse == null || (_ftpWebResponse.GetResponseStream() is FtpWebResponse.EmptyStream && _stream != null)) { diff --git a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Android.cs b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Android.cs index 43716cd04367b..3c288b1ecdda0 100644 --- a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Android.cs +++ b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Android.cs @@ -14,7 +14,7 @@ internal static SslPolicyErrors VerifyCertificateProperties( X509Chain chain, X509Certificate2? remoteCertificate, bool checkCertName, - bool isServer, + bool _ /*isServer*/, string? hostName) { if (remoteCertificate == null) diff --git a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs index 2e6bbfd5e85d0..9a3aa16ca8a80 100644 --- a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs +++ b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Unix.cs @@ -11,7 +11,7 @@ namespace System.Net internal static partial class CertificateValidationPal { internal static SslPolicyErrors VerifyCertificateProperties( - SafeDeleteContext? securityContext, + SafeDeleteContext? _ /*securityContext*/, X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, diff --git a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs index 1ead906ec3585..07db92b61f24f 100644 --- a/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs +++ b/src/libraries/System.Net.Security/src/System/Net/CertificateValidationPal.Windows.cs @@ -14,7 +14,7 @@ namespace System.Net internal static partial class CertificateValidationPal { internal static SslPolicyErrors VerifyCertificateProperties( - SafeDeleteContext? securityContext, + SafeDeleteContext? _ /*securityContext*/, X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Linux.cs b/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Linux.cs index cbc21b7109dae..e864e7400b696 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Linux.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Linux.cs @@ -98,7 +98,7 @@ internal static bool ShouldOptOutOfTls13(CipherSuitesPolicy? policy, EncryptionP return policy.Pal._tls13CipherSuites.Length == 1; } - internal static bool ShouldOptOutOfLowerThanTls13(CipherSuitesPolicy? policy, EncryptionPolicy encryptionPolicy) + internal static bool ShouldOptOutOfLowerThanTls13(CipherSuitesPolicy? policy) { if (policy == null) { diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Windows.cs index f809cec0c696d..998c5584c88b9 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Windows.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/CipherSuitesPolicyPal.Windows.cs @@ -7,7 +7,7 @@ namespace System.Net.Security { internal sealed class CipherSuitesPolicyPal { - internal CipherSuitesPolicyPal(IEnumerable allowedCipherSuites) + internal CipherSuitesPolicyPal(IEnumerable _ /*allowedCipherSuites*/) { throw new PlatformNotSupportedException(SR.net_ssl_ciphersuites_policy_not_supported); } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.PlatformNotSupported.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.PlatformNotSupported.cs index 841a3c59f25d9..4fde254e93833 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.PlatformNotSupported.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.PlatformNotSupported.cs @@ -15,6 +15,7 @@ namespace System.Net.Security [UnsupportedOSPlatform("tvos")] internal static partial class NegotiateStreamPal { +#pragma warning disable IDE0060 internal static IIdentity GetIdentity(NTAuthentication context) { throw new PlatformNotSupportedException(); @@ -29,5 +30,6 @@ internal static Win32Exception CreateExceptionFromError(SecurityStatusPal status { throw new PlatformNotSupportedException(); } +#pragma warning restore IDE0060 } } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/NetSecurityTelemetry.cs b/src/libraries/System.Net.Security/src/System/Net/Security/NetSecurityTelemetry.cs index 985662d9f2146..a6d89f11b8d21 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/NetSecurityTelemetry.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/NetSecurityTelemetry.cs @@ -164,6 +164,7 @@ public void HandshakeFailed(bool isServer, long startingTimestamp, string except HandshakeStop(SslProtocols.None); } +#pragma warning disable IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 [NonEvent] public void HandshakeCompleted(SslProtocols protocol, long startingTimestamp, bool connectionOpen) { @@ -212,6 +213,7 @@ public void HandshakeCompleted(SslProtocols protocol, long startingTimestamp, bo HandshakeStop(protocol); } +#pragma warning restore IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 [NonEvent] public void ConnectionClosed(SslProtocols protocol) diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Protocol.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Protocol.cs index ac8db67ba2775..18c5a7e824573 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Protocol.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.Protocol.cs @@ -1100,7 +1100,7 @@ internal bool VerifyRemoteCertificate(RemoteCertificateValidationCallback? remot NetEventSource.Info(this, $"alertMessage:{alertMessage}"); SecurityStatusPal status; - status = SslStreamPal.ApplyAlertToken(ref _credentialsHandle, _securityContext, TlsAlertType.Fatal, alertMessage); + status = SslStreamPal.ApplyAlertToken(_securityContext, TlsAlertType.Fatal, alertMessage); if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { @@ -1121,7 +1121,7 @@ internal bool VerifyRemoteCertificate(RemoteCertificateValidationCallback? remot private ProtocolToken? CreateShutdownToken() { SecurityStatusPal status; - status = SslStreamPal.ApplyShutdownToken(ref _credentialsHandle, _securityContext!); + status = SslStreamPal.ApplyShutdownToken(_securityContext!); if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Android.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Android.cs index f01dd68e294b2..32aaa30530cf8 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Android.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Android.cs @@ -8,6 +8,8 @@ using PAL_SSLStreamStatus = Interop.AndroidCrypto.PAL_SSLStreamStatus; +#pragma warning disable IDE0060 + namespace System.Net.Security { internal static class SslStreamPal @@ -210,7 +212,6 @@ private static SecurityStatusPal HandshakeInternal( } public static SecurityStatusPal ApplyAlertToken( - ref SafeFreeCredentials? credentialsHandle, SafeDeleteContext? securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage) @@ -221,7 +222,6 @@ public static SecurityStatusPal ApplyAlertToken( } public static SecurityStatusPal ApplyShutdownToken( - ref SafeFreeCredentials? credentialsHandle, SafeDeleteSslContext securityContext) { SafeSslHandle sslHandle = securityContext.SslContext; diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.OSX.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.OSX.cs index 255b30d7f2c2f..80d7590ea7d39 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.OSX.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.OSX.cs @@ -31,6 +31,7 @@ public static void VerifyPackageInfo() { } +#pragma warning disable IDE0060 public static SecurityStatusPal AcceptSecurityContext( ref SafeFreeCredentials credential, ref SafeDeleteSslContext? context, @@ -38,19 +39,19 @@ public static SecurityStatusPal AcceptSecurityContext( ref byte[]? outputBuffer, SslAuthenticationOptions sslAuthenticationOptions) { - return HandshakeInternal(credential, ref context, inputBuffer, ref outputBuffer, sslAuthenticationOptions, null); + return HandshakeInternal(ref context, inputBuffer, ref outputBuffer, sslAuthenticationOptions, null); } public static SecurityStatusPal InitializeSecurityContext( ref SafeFreeCredentials credential, ref SafeDeleteSslContext? context, - string? targetName, + string? _ /*targetName*/, ReadOnlySpan inputBuffer, ref byte[]? outputBuffer, SslAuthenticationOptions sslAuthenticationOptions, SelectClientCertificate clientCertificateSelectionCallback) { - return HandshakeInternal(credential, ref context, inputBuffer, ref outputBuffer, sslAuthenticationOptions, clientCertificateSelectionCallback); + return HandshakeInternal(ref context, inputBuffer, ref outputBuffer, sslAuthenticationOptions, clientCertificateSelectionCallback); } public static SecurityStatusPal Renegotiate( @@ -67,11 +68,13 @@ public static SecurityStatusPal Renegotiate( return null; } +#pragma warning restore IDE0060 + public static SecurityStatusPal EncryptMessage( SafeDeleteSslContext securityContext, ReadOnlyMemory input, - int headerSize, - int trailerSize, + int _ /*headerSize*/, + int _1 /*trailerSize*/, ref byte[] output, out int resultSize) { @@ -203,7 +206,7 @@ public static SecurityStatusPal DecryptMessage( } public static void QueryContextStreamSizes( - SafeDeleteContext? securityContext, + SafeDeleteContext? _ /*securityContext*/, out StreamSizes streamSizes) { streamSizes = StreamSizes.Default; @@ -217,7 +220,6 @@ public static void QueryContextConnectionInfo( } private static SecurityStatusPal HandshakeInternal( - SafeFreeCredentials credential, ref SafeDeleteSslContext? context, ReadOnlySpan inputBuffer, ref byte[]? outputBuffer, @@ -294,8 +296,8 @@ private static SecurityStatusPal PerformHandshake(SafeSslHandle sslHandle) } } +#pragma warning disable IDE0060 public static SecurityStatusPal ApplyAlertToken( - ref SafeFreeCredentials? credentialsHandle, SafeDeleteContext? securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage) @@ -305,9 +307,9 @@ public static SecurityStatusPal ApplyAlertToken( // SSLHandshake. return new SecurityStatusPal(SecurityStatusPalErrorCode.OK); } +#pragma warning restore IDE0060 public static SecurityStatusPal ApplyShutdownToken( - ref SafeFreeCredentials? credentialsHandle, SafeDeleteSslContext securityContext) { SafeSslHandle sslHandle = securityContext.SslContext; diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Unix.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Unix.cs index 1e1a0df55889e..35da4502293ae 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Unix.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Unix.cs @@ -24,6 +24,7 @@ public static void VerifyPackageInfo() { } +#pragma warning disable IDE0060 public static SecurityStatusPal AcceptSecurityContext( ref SafeFreeCredentials? credential, ref SafeDeleteSslContext? context, @@ -37,7 +38,7 @@ public static SecurityStatusPal AcceptSecurityContext( public static SecurityStatusPal InitializeSecurityContext( ref SafeFreeCredentials? credential, ref SafeDeleteSslContext? context, - string? targetName, + string? _ /*targetName*/, ReadOnlySpan inputBuffer, ref byte[]? outputBuffer, SslAuthenticationOptions sslAuthenticationOptions, @@ -51,7 +52,7 @@ public static SecurityStatusPal InitializeSecurityContext( return null; } - public static SecurityStatusPal EncryptMessage(SafeDeleteSslContext securityContext, ReadOnlyMemory input, int headerSize, int trailerSize, ref byte[] output, out int resultSize) + public static SecurityStatusPal EncryptMessage(SafeDeleteSslContext securityContext, ReadOnlyMemory input, int _ /*headerSize*/, int _1 /*trailerSize*/, ref byte[] output, out int resultSize) { try { @@ -141,7 +142,7 @@ public static SecurityStatusPal Renegotiate( return HandshakeInternal(ref context!, null, ref outputBuffer, sslAuthenticationOptions, null); } - public static void QueryContextStreamSizes(SafeDeleteContext? securityContext, out StreamSizes streamSizes) + public static void QueryContextStreamSizes(SafeDeleteContext? _ /*securityContext*/, out StreamSizes streamSizes) { streamSizes = StreamSizes.Default; } @@ -216,15 +217,16 @@ private static SecurityStatusPal HandshakeInternal(ref SafeDeleteSslContext? con } } - public static SecurityStatusPal ApplyAlertToken(ref SafeFreeCredentials? credentialsHandle, SafeDeleteContext? securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage) + public static SecurityStatusPal ApplyAlertToken(SafeDeleteContext? securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage) { // There doesn't seem to be an exposed API for writing an alert, // the API seems to assume that all alerts are generated internally by // SSLHandshake. return new SecurityStatusPal(SecurityStatusPalErrorCode.OK); } +#pragma warning restore IDE0060 - public static SecurityStatusPal ApplyShutdownToken(ref SafeFreeCredentials? credentialsHandle, SafeDeleteSslContext context) + public static SecurityStatusPal ApplyShutdownToken(SafeDeleteSslContext context) { // Unset the quiet shutdown option initially configured. Interop.Ssl.SslSetQuietShutdown((SafeSslHandle)context, 0); diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs index 1321cc0754ed0..aaf702411acab 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStreamPal.Windows.cs @@ -94,7 +94,7 @@ public static SecurityStatusPal InitializeSecurityContext( ReadOnlySpan inputBuffer, ref byte[]? outputBuffer, SslAuthenticationOptions sslAuthenticationOptions, - SelectClientCertificate? clientCertificateSelectionCallback) + SelectClientCertificate? _ /*clientCertificateSelectionCallback*/) { Interop.SspiCli.ContextFlags unusedAttributes = default; @@ -443,7 +443,7 @@ public static unsafe SecurityStatusPal DecryptMessage(SafeDeleteSslContext? secu } } - public static SecurityStatusPal ApplyAlertToken(ref SafeFreeCredentials? credentialsHandle, SafeDeleteContext? securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage) + public static SecurityStatusPal ApplyAlertToken(SafeDeleteContext? securityContext, TlsAlertType alertType, TlsAlertMessage alertMessage) { var alertToken = new Interop.SChannel.SCHANNEL_ALERT_TOKEN { @@ -464,7 +464,7 @@ public static SecurityStatusPal ApplyAlertToken(ref SafeFreeCredentials? credent private static readonly byte[] s_schannelShutdownBytes = BitConverter.GetBytes(Interop.SChannel.SCHANNEL_SHUTDOWN); - public static SecurityStatusPal ApplyShutdownToken(ref SafeFreeCredentials? credentialsHandle, SafeDeleteContext? securityContext) + public static SecurityStatusPal ApplyShutdownToken(SafeDeleteContext? securityContext) { var securityBuffer = new SecurityBuffer(s_schannelShutdownBytes, SecurityBufferType.SECBUFFER_TOKEN); diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SafeSocketHandle.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SafeSocketHandle.Windows.cs index 5b00069c25505..82b60b646a4a4 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SafeSocketHandle.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SafeSocketHandle.Windows.cs @@ -126,7 +126,7 @@ private unsafe bool OnHandleClose() } /// Returns whether operations were canceled. - private unsafe bool TryUnblockSocket(bool abortive) + private unsafe bool TryUnblockSocket(bool _ /*abortive*/) { // Try to cancel all pending IO. return Interop.Kernel32.CancelIoEx(handle, null); diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Unix.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Unix.cs index 2f93a77b4ecc0..8dba083e1c0ac 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Unix.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Unix.cs @@ -176,7 +176,7 @@ private static void ThrowMultiConnectNotSupported() throw new PlatformNotSupportedException(SR.net_sockets_connect_multiconnect_notsupported); } -#pragma warning disable CA1822 +#pragma warning disable IDE0060, CA1822 private Socket? GetOrCreateAcceptSocket(Socket? acceptSocket, bool checkDisconnected, string propertyName, out SafeSocketHandle? handle) { if (acceptSocket != null) @@ -195,7 +195,7 @@ private static void ThrowMultiConnectNotSupported() handle = null; return acceptSocket; } -#pragma warning restore CA1822 +#pragma warning restore IDE0060, CA1822 private static void CheckTransmitFileOptions(TransmitFileOptions flags) { diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs index 94d1cea46d1b0..ba3490b210512 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs @@ -169,7 +169,7 @@ private unsafe Socket(SafeSocketHandle handle, bool loadPropertiesFromHandle) break; case AddressFamily.Unix: - socketAddress = new Internals.SocketAddress(_addressFamily, buffer.Slice(0, bufferLength)); + socketAddress = new Internals.SocketAddress(AddressFamily.Unix, buffer.Slice(0, bufferLength)); _rightEndPoint = new UnixDomainSocketEndPoint(IPEndPointExtensions.GetNetSocketAddress(socketAddress)); break; } @@ -202,7 +202,7 @@ private unsafe Socket(SafeSocketHandle handle, bool loadPropertiesFromHandle) break; case AddressFamily.Unix: - socketAddress = new Internals.SocketAddress(_addressFamily, buffer.Slice(0, bufferLength)); + socketAddress = new Internals.SocketAddress(AddressFamily.Unix, buffer.Slice(0, bufferLength)); _remoteEndPoint = new UnixDomainSocketEndPoint(IPEndPointExtensions.GetNetSocketAddress(socketAddress)); break; } @@ -2739,7 +2739,7 @@ internal bool ConnectAsync(SocketAsyncEventArgs e, bool userSocket, bool saeaCan bool canUseConnectEx = _socketType == SocketType.Stream && endPointSnapshot.AddressFamily != AddressFamily.Unix; SocketError socketError = canUseConnectEx ? e.DoOperationConnectEx(this, _handle) : - e.DoOperationConnect(this, _handle); // For connectionless protocols, Connect is not an I/O call. + e.DoOperationConnect(_handle); // For connectionless protocols, Connect is not an I/O call. pending = socketError == SocketError.IOPending; } catch (Exception ex) diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncContext.Unix.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncContext.Unix.cs index 3a9066db918a0..1926097b8e45d 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncContext.Unix.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncContext.Unix.cs @@ -625,7 +625,7 @@ public ConnectOperation(SocketAsyncContext context) : base(context) { } protected override bool DoTryComplete(SocketAsyncContext context) { - bool result = SocketPal.TryCompleteConnect(context._socket, SocketAddressLen, out ErrorCode); + bool result = SocketPal.TryCompleteConnect(context._socket, out ErrorCode); context._socket.RegisterConnectResult(ErrorCode); return result; } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Unix.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Unix.cs index 79d8e77ec28d0..1a09d751708e6 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Unix.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Unix.cs @@ -25,19 +25,19 @@ public partial class SocketAsyncEventArgs : EventArgs, IDisposable private void AcceptCompletionCallback(IntPtr acceptedFileDescriptor, byte[] socketAddress, int socketAddressSize, SocketError socketError) { - CompleteAcceptOperation(acceptedFileDescriptor, socketAddress, socketAddressSize, socketError); + CompleteAcceptOperation(acceptedFileDescriptor, socketAddress, socketAddressSize); CompletionCallback(0, SocketFlags.None, socketError); } - private void CompleteAcceptOperation(IntPtr acceptedFileDescriptor, byte[] socketAddress, int socketAddressSize, SocketError socketError) + private void CompleteAcceptOperation(IntPtr acceptedFileDescriptor, byte[] socketAddress, int socketAddressSize) { _acceptedFileDescriptor = acceptedFileDescriptor; Debug.Assert(socketAddress == null || socketAddress == _acceptBuffer, $"Unexpected socketAddress: {socketAddress}"); _acceptAddressBufferCount = socketAddressSize; } - internal unsafe SocketError DoOperationAccept(Socket socket, SafeSocketHandle handle, SafeSocketHandle? acceptHandle, CancellationToken cancellationToken) + internal unsafe SocketError DoOperationAccept(Socket _ /*socket*/, SafeSocketHandle handle, SafeSocketHandle? acceptHandle, CancellationToken cancellationToken) { if (!_buffer.Equals(default)) { @@ -54,7 +54,7 @@ internal unsafe SocketError DoOperationAccept(Socket socket, SafeSocketHandle ha if (socketError != SocketError.IOPending) { - CompleteAcceptOperation(acceptedFd, _acceptBuffer!, socketAddressLen, socketError); + CompleteAcceptOperation(acceptedFd, _acceptBuffer!, socketAddressLen); FinishOperationSync(socketError, 0, SocketFlags.None); } @@ -66,10 +66,10 @@ private void ConnectCompletionCallback(SocketError socketError) CompletionCallback(0, SocketFlags.None, socketError); } - internal unsafe SocketError DoOperationConnectEx(Socket socket, SafeSocketHandle handle) - => DoOperationConnect(socket, handle); + internal unsafe SocketError DoOperationConnectEx(Socket _ /*socket*/, SafeSocketHandle handle) + => DoOperationConnect(handle); - internal unsafe SocketError DoOperationConnect(Socket socket, SafeSocketHandle handle) + internal unsafe SocketError DoOperationConnect(SafeSocketHandle handle) { SocketError socketError = handle.AsyncContext.ConnectAsync(_socketAddress!.Buffer, _socketAddress.Size, ConnectCompletionCallback); if (socketError != SocketError.IOPending) @@ -79,7 +79,7 @@ internal unsafe SocketError DoOperationConnect(Socket socket, SafeSocketHandle h return socketError; } - internal SocketError DoOperationDisconnect(Socket socket, SafeSocketHandle handle, CancellationToken cancellationToken) + internal SocketError DoOperationDisconnect(Socket socket, SafeSocketHandle handle, CancellationToken _ /*cancellationToken*/) { SocketError socketError = SocketPal.Disconnect(socket, handle, _disconnectReuseSocket); FinishOperationSync(socketError, 0, SocketFlags.None); @@ -91,12 +91,12 @@ internal SocketError DoOperationDisconnect(Socket socket, SafeSocketHandle handl private void TransferCompletionCallbackCore(int bytesTransferred, byte[]? socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError) { - CompleteTransferOperation(bytesTransferred, socketAddress, socketAddressSize, receivedFlags, socketError); + CompleteTransferOperation(socketAddress, socketAddressSize, receivedFlags); CompletionCallback(bytesTransferred, receivedFlags, socketError); } - private void CompleteTransferOperation(int bytesTransferred, byte[]? socketAddress, int socketAddressSize, SocketFlags receivedFlags, SocketError socketError) + private void CompleteTransferOperation(byte[]? socketAddress, int socketAddressSize, SocketFlags receivedFlags) { Debug.Assert(socketAddress == null || socketAddress == _socketAddress!.Buffer, $"Unexpected socketAddress: {socketAddress}"); _socketAddressSize = socketAddressSize; @@ -132,7 +132,7 @@ internal unsafe SocketError DoOperationReceive(SafeSocketHandle handle, Cancella if (errorCode != SocketError.IOPending) { - CompleteTransferOperation(bytesReceived, null, 0, flags, errorCode); + CompleteTransferOperation(null, 0, flags); FinishOperationSync(errorCode, bytesReceived, flags); } @@ -159,7 +159,7 @@ internal unsafe SocketError DoOperationReceiveFrom(SafeSocketHandle handle, Canc if (errorCode != SocketError.IOPending) { - CompleteTransferOperation(bytesReceived, _socketAddress.Buffer, socketAddressLen, flags, errorCode); + CompleteTransferOperation(_socketAddress.Buffer, socketAddressLen, flags); FinishOperationSync(errorCode, bytesReceived, flags); } @@ -168,12 +168,12 @@ internal unsafe SocketError DoOperationReceiveFrom(SafeSocketHandle handle, Canc private void ReceiveMessageFromCompletionCallback(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode) { - CompleteReceiveMessageFromOperation(bytesTransferred, socketAddress, socketAddressSize, receivedFlags, ipPacketInformation, errorCode); + CompleteReceiveMessageFromOperation(socketAddress, socketAddressSize, receivedFlags, ipPacketInformation); CompletionCallback(bytesTransferred, receivedFlags, errorCode); } - private void CompleteReceiveMessageFromOperation(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode) + private void CompleteReceiveMessageFromOperation(byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation) { Debug.Assert(_socketAddress != null, "Expected non-null _socketAddress"); Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress, $"Unexpected socketAddress: {socketAddress}"); @@ -199,7 +199,7 @@ internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeSoc SocketError socketError = handle.AsyncContext.ReceiveMessageFromAsync(_buffer.Slice(_offset, _count), _bufferListInternal, _socketFlags, _socketAddress.Buffer, ref socketAddressSize, isIPv4, isIPv6, out bytesReceived, out receivedFlags, out ipPacketInformation, ReceiveMessageFromCompletionCallback, cancellationToken); if (socketError != SocketError.IOPending) { - CompleteReceiveMessageFromOperation(bytesReceived, _socketAddress.Buffer, socketAddressSize, receivedFlags, ipPacketInformation, socketError); + CompleteReceiveMessageFromOperation(_socketAddress.Buffer, socketAddressSize, receivedFlags, ipPacketInformation); FinishOperationSync(socketError, bytesReceived, receivedFlags); } return socketError; @@ -223,14 +223,14 @@ internal unsafe SocketError DoOperationSend(SafeSocketHandle handle, Cancellatio if (errorCode != SocketError.IOPending) { - CompleteTransferOperation(bytesSent, null, 0, SocketFlags.None, errorCode); + CompleteTransferOperation(null, 0, SocketFlags.None); FinishOperationSync(errorCode, bytesSent, SocketFlags.None); } return errorCode; } - internal SocketError DoOperationSendPackets(Socket socket, SafeSocketHandle handle, CancellationToken cancellationToken) + internal SocketError DoOperationSendPackets(Socket socket, SafeSocketHandle _1 /*handle*/, CancellationToken cancellationToken) { Debug.Assert(_sendPacketsElements != null); SendPacketsElement[] elements = (SendPacketsElement[])_sendPacketsElements.Clone(); @@ -308,7 +308,7 @@ internal SocketError DoOperationSendTo(SafeSocketHandle handle, CancellationToke if (errorCode != SocketError.IOPending) { - CompleteTransferOperation(bytesSent, _socketAddress.Buffer, socketAddressLen, SocketFlags.None, errorCode); + CompleteTransferOperation(_socketAddress.Buffer, socketAddressLen, SocketFlags.None); FinishOperationSync(errorCode, bytesSent, SocketFlags.None); } diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs index e880f5516b735..51edda47b5023 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs @@ -281,7 +281,7 @@ internal unsafe SocketError DoOperationAccept(Socket socket, SafeSocketHandle ha } } - internal unsafe SocketError DoOperationConnect(Socket socket, SafeSocketHandle handle) + internal SocketError DoOperationConnect(SafeSocketHandle handle) { // Called for connectionless protocols. SocketError socketError = SocketPal.Connect(handle, _socketAddress!.Buffer, _socketAddress.Size); diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs index 35421e813cfaf..69681d43997c8 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs @@ -681,7 +681,7 @@ public static unsafe bool TryStartConnect(SafeSocketHandle socket, byte[] socket return false; } - public static unsafe bool TryCompleteConnect(SafeSocketHandle socket, int socketAddressLen, out SocketError errorCode) + public static unsafe bool TryCompleteConnect(SafeSocketHandle socket, out SocketError errorCode) { Interop.Error socketError = default; Interop.Error err; @@ -1343,7 +1343,7 @@ public static SocketError ReceiveFrom(SafeSocketHandle handle, Span buffer return completed ? errorCode : SocketError.WouldBlock; } - public static SocketError WindowsIoctl(SafeSocketHandle handle, int ioControlCode, byte[]? optionInValue, byte[]? optionOutValue, out int optionLength) + public static SocketError WindowsIoctl(SafeSocketHandle handle, int ioControlCode, byte[]? _ /*optionInValue*/, byte[]? optionOutValue, out int optionLength) { // Three codes are called out in the Winsock IOCTLs documentation as "The following Unix IOCTL codes (commands) are supported." They are // also the three codes available for use with ioctlsocket on Windows. Developers should be discouraged from using Socket.IOControl in @@ -1545,10 +1545,12 @@ public static void SetReceivingDualModeIPv4PacketInformation(Socket socket) } } +#pragma warning disable IDE0060 public static void SetIPProtectionLevel(Socket socket, SocketOptionLevel optionLevel, int protectionLevel) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_IPProtectionLevel); } +#pragma warning restore IDE0060 public static unsafe SocketError GetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, out int optionValue) { diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs index 1ed8cad04ab88..0d66ac80a3a61 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs @@ -164,7 +164,7 @@ public static unsafe SocketError GetPeerName(SafeSocketHandle handle, Span } } - public static SocketError Bind(SafeSocketHandle handle, ProtocolType socketProtocolType, byte[] buffer, int nameLen) + public static SocketError Bind(SafeSocketHandle handle, ProtocolType _ /*socketProtocolType*/, byte[] buffer, int nameLen) { SocketError errorCode = Interop.Winsock.bind(handle, buffer, nameLen); return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success; @@ -512,7 +512,7 @@ public static unsafe SocketError ReceiveMessageFrom(Socket socket, SafeSocketHan return SocketError.Success; } - public static unsafe SocketError ReceiveFrom(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, byte[] socketAddress, ref int addressLength, out int bytesTransferred) => + public static unsafe SocketError ReceiveFrom(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags _ /*socketFlags*/, byte[] socketAddress, ref int addressLength, out int bytesTransferred) => ReceiveFrom(handle, buffer.AsSpan(offset, size), SocketFlags.None, socketAddress, ref addressLength, out bytesTransferred); public static unsafe SocketError ReceiveFrom(SafeSocketHandle handle, Span buffer, SocketFlags socketFlags, byte[] socketAddress, ref int addressLength, out int bytesTransferred) @@ -1048,6 +1048,7 @@ private static unsafe bool TransmitFileHelper( } } + [Conditional("unnecessary")] public static void CheckDualModeReceiveSupport(Socket socket) { // Dual-mode sockets support received packet info on Windows. diff --git a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Browser.cs b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Browser.cs index f90eb22fa1e4f..25faba26157f3 100644 --- a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Browser.cs +++ b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Browser.cs @@ -34,7 +34,7 @@ public void Abort() WebSocket?.Abort(); } - public Task ConnectAsync(Uri uri, HttpMessageInvoker? invoker, CancellationToken cancellationToken, ClientWebSocketOptions options) + public Task ConnectAsync(Uri uri, HttpMessageInvoker? _ /*invoker*/, CancellationToken cancellationToken, ClientWebSocketOptions options) { cancellationToken.ThrowIfCancellationRequested(); diff --git a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs index 0ab159c1c42cb..962fe93322e0e 100644 --- a/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs +++ b/src/libraries/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs @@ -131,7 +131,7 @@ public async Task ConnectAsync(Uri uri, HttpMessageInvoker? invoker, Cancellatio externalAndAbortCancellation.Token.ThrowIfCancellationRequested(); // poll in case sends/receives in request/response didn't observe cancellation } - ValidateResponse(response, secValue, options); + ValidateResponse(response, secValue); break; } catch (HttpRequestException ex) when @@ -443,7 +443,7 @@ static string GetDeflateOptions(WebSocketDeflateOptions options) return secValue; } - private static void ValidateResponse(HttpResponseMessage response, string? secValue, ClientWebSocketOptions options) + private static void ValidateResponse(HttpResponseMessage response, string? secValue) { Debug.Assert(response.Version == HttpVersion.Version11 || response.Version == HttpVersion.Version20); diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.Android.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.Android.cs index 8b9b01276c313..b3bb0a25a1542 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.Android.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.Android.cs @@ -13,7 +13,7 @@ public static partial class Environment { private static Dictionary? s_specialFolders; - private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption option) + private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption _ /*option*/) { if (s_specialFolders == null) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Environment.iOS.cs b/src/libraries/System.Private.CoreLib/src/System/Environment.iOS.cs index 92af242c4df99..9f69fdea66588 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Environment.iOS.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Environment.iOS.cs @@ -18,7 +18,7 @@ public static partial class Environment private static Dictionary? s_specialFolders; - private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption option) + private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption _ /*option*/) { if (s_specialFolders == null) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Unix.cs index 140b6484e3041..ff4b34b2a35d2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Unix.cs @@ -13,7 +13,6 @@ private bool LoadCalendarDataFromSystemCore(string localeName, CalendarId calend #pragma warning disable IDE0060 internal static int GetCalendarsCore(string localeName, bool useUserOverride, CalendarId[] calendars) => IcuGetCalendars(localeName, calendars); -#pragma warning restore IDE0060 internal static int GetTwoDigitYearMax(CalendarId calendarId) { @@ -23,5 +22,6 @@ internal static int GetTwoDigitYearMax(CalendarId calendarId) // So just return -1 to use the hard-coded defaults. return GlobalizationMode.Invariant ? Invariant.iTwoDigitYearMax : -1; } +#pragma warning restore IDE0060 } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Windows.cs index 943d7dc829f71..b00eab023e93b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureData.Windows.cs @@ -229,16 +229,16 @@ internal static unsafe CultureData GetCurrentRegionData() new string[] { userOverride, icuFormatString } : new string[] { userOverride }; } - private int GetAnsiCodePage(string cultureName) => + private int GetAnsiCodePage(string _ /*cultureName*/) => NlsGetLocaleInfo(LocaleNumberData.AnsiCodePage); - private int GetOemCodePage(string cultureName) => + private int GetOemCodePage(string _ /*cultureName*/) => NlsGetLocaleInfo(LocaleNumberData.OemCodePage); - private int GetMacCodePage(string cultureName) => + private int GetMacCodePage(string _ /*cultureName*/) => NlsGetLocaleInfo(LocaleNumberData.MacCodePage); - private int GetEbcdicCodePage(string cultureName) => + private int GetEbcdicCodePage(string _ /*cultureName*/) => NlsGetLocaleInfo(LocaleNumberData.EbcdicCodePage); // If we are using ICU and loading the calendar data for the user's default diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Directory.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Directory.Windows.cs index f0fdfceeab195..3553186a6dd47 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Directory.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Directory.Windows.cs @@ -8,8 +8,10 @@ namespace System.IO { public static partial class Directory { +#pragma warning disable IDE0060 private static DirectoryInfo CreateDirectoryCore(string path, UnixFileMode unixCreateMode) => throw new PlatformNotSupportedException(SR.PlatformNotSupported_UnixFileMode); +#pragma warning restore IDE0060 private static unsafe string CreateTempSubdirectoryCore(string? prefix) { diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/File.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/IO/File.Windows.cs index 70ee2e2c142c5..cb846a5d7ba33 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/File.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/File.Windows.cs @@ -7,6 +7,7 @@ namespace System.IO { public static partial class File { +#pragma warning disable IDE0060 private static UnixFileMode GetUnixFileModeCore(string path) => throw new PlatformNotSupportedException(SR.PlatformNotSupported_UnixFileMode); @@ -18,5 +19,6 @@ private static void SetUnixFileModeCore(string path, UnixFileMode mode) private static void SetUnixFileModeCore(SafeFileHandle fileHandle, UnixFileMode mode) => throw new PlatformNotSupportedException(SR.PlatformNotSupported_UnixFileMode); +#pragma warning restore IDE0060 } } diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/FileStatus.SetTimes.OtherUnix.cs b/src/libraries/System.Private.CoreLib/src/System/IO/FileStatus.SetTimes.OtherUnix.cs index f30b3ead243f9..6446142db5621 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/FileStatus.SetTimes.OtherUnix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/FileStatus.SetTimes.OtherUnix.cs @@ -17,8 +17,10 @@ internal void SetCreationTime(SafeFileHandle handle, DateTimeOffset time, bool a private void SetAccessOrWriteTime(SafeFileHandle? handle, string? path, DateTimeOffset time, bool isAccessTime, bool asDirectory) => SetAccessOrWriteTimeCore(handle, path, time, isAccessTime, checkCreationTime: false, asDirectory); +#pragma warning disable IDE0060 // This is not used on these platforms, but is needed for source compat private static Interop.Error SetCreationTimeCore(SafeFileHandle? handle, string? path, long seconds, long nanoseconds) => throw new InvalidOperationException(); +#pragma warning restore IDE0060 } } diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Unix.cs index f538524471a91..f28cd70f08f83 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Unix.cs @@ -651,12 +651,12 @@ public static string[] GetLogicalDrives() #pragma warning disable IDE0060 internal static string? GetLinkTarget(ReadOnlySpan linkPath, bool isDirectory) => Interop.Sys.ReadLink(linkPath); -#pragma warning restore IDE0060 internal static void CreateSymbolicLink(string path, string pathToTarget, bool isDirectory) { Interop.CheckIo(Interop.Sys.SymLink(pathToTarget, path), path); } +#pragma warning restore IDE0060 internal static FileSystemInfo? ResolveLinkTarget(string linkPath, bool returnFinalTarget, bool isDirectory) { diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Windows.cs index a5fa7dea46c7f..19018c673f8cb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/FileSystem.Windows.cs @@ -180,7 +180,7 @@ private static void PopulateAttributeData(ref Interop.Kernel32.WIN32_FILE_ATTRIB data.nFileSizeLow = fileInformationData.nFileSizeLow; } - private static void MoveDirectory(string sourceFullPath, string destFullPath, bool isCaseSensitiveRename) + private static void MoveDirectory(string sourceFullPath, string destFullPath, bool _ /*isCaseSensitiveRename*/) { // Source and destination must have the same root. ReadOnlySpan sourceRoot = Path.GetPathRoot(sourceFullPath); diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Strategies/FileStreamHelpers.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Strategies/FileStreamHelpers.Windows.cs index 4cc2b56008c58..678f9c2fd74a4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Strategies/FileStreamHelpers.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Strategies/FileStreamHelpers.Windows.cs @@ -95,7 +95,7 @@ internal static int GetLastWin32ErrorAndDisposeHandleIfInvalid(SafeFileHandle ha return errorCode; } - internal static void Lock(SafeFileHandle handle, bool canWrite, long position, long length) + internal static void Lock(SafeFileHandle handle, bool _ /*canWrite*/, long position, long length) { int positionLow = unchecked((int)(position)); int positionHigh = unchecked((int)(position >> 32)); diff --git a/src/libraries/System.Private.CoreLib/src/System/IndexOfAnyAsciiSearcher.cs b/src/libraries/System.Private.CoreLib/src/System/IndexOfAnyAsciiSearcher.cs index 0f36b70738da3..d104cc839dec0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IndexOfAnyAsciiSearcher.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IndexOfAnyAsciiSearcher.cs @@ -273,6 +273,7 @@ private static int ComputeFirstIndex(ref short searchSpace, ref short return offsetInVector + (int)(Unsafe.ByteOffset(ref searchSpace, ref current) / sizeof(short)); } +#pragma warning disable IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int ComputeFirstIndexOverlapped(ref short searchSpace, ref short current0, ref short current1, Vector128 result) where TNegator : struct, INegator @@ -287,6 +288,7 @@ private static int ComputeFirstIndexOverlapped(ref short searchSpace, } return offsetInVector + (int)(Unsafe.ByteOffset(ref searchSpace, ref current0) / sizeof(short)); } +#pragma warning restore IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int ComputeLastIndex(ref short searchSpace, ref short current, Vector128 result) diff --git a/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector.cs b/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector.cs index 64a0ff3ebd4f4..1bc48cfe91b28 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Numerics/Vector.cs @@ -1073,6 +1073,7 @@ public static Vector LoadUnsafe(ref T source) return Unsafe.ReadUnaligned>(ref address); } +#pragma warning disable IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 /// Loads a vector from the given source and element offset. /// The type of the elements in the vector. /// The source to which will be added before loading the vector. @@ -1089,6 +1090,7 @@ public static Vector LoadUnsafe(ref T source, nuint elementOffset) source = ref Unsafe.Add(ref source, (nint)elementOffset); return Unsafe.ReadUnaligned>(ref Unsafe.As(ref source)); } +#pragma warning restore IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 /// Computes the maximum of two vectors on a per-element basis. /// The vector to compare with . @@ -1649,6 +1651,7 @@ public static void StoreUnsafe(this Vector source, ref T destination) Unsafe.WriteUnaligned(ref address, source); } +#pragma warning disable IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 /// Stores a vector at the given destination. /// The type of the elements in the vector. /// The vector that will be stored. @@ -1665,6 +1668,7 @@ public static void StoreUnsafe(this Vector source, ref T destination, nuin destination = ref Unsafe.Add(ref destination, (nint)elementOffset); Unsafe.WriteUnaligned(ref Unsafe.As(ref destination), source); } +#pragma warning restore IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 /// Subtracts two vectors to compute their difference. /// The vector from which will be subtracted. diff --git a/src/libraries/System.Private.CoreLib/src/System/ReadOnlySpan.cs b/src/libraries/System.Private.CoreLib/src/System/ReadOnlySpan.cs index ab1c7ce1ab8d6..b39ffa5c974e5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/ReadOnlySpan.cs +++ b/src/libraries/System.Private.CoreLib/src/System/ReadOnlySpan.cs @@ -119,6 +119,7 @@ public ReadOnlySpan(in T reference) _length = 1; } +#pragma warning disable IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 // Constructor for internal use only. It is not safe to expose publicly, and is instead exposed via the unsafe MemoryMarshal.CreateReadOnlySpan. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlySpan(ref T reference, int length) @@ -128,6 +129,7 @@ internal ReadOnlySpan(ref T reference, int length) _reference = ref reference; _length = length; } +#pragma warning restore IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 /// /// Returns the specified element of the read-only span. diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs index 2516a77f289ce..16ee1c358171c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/InvokeUtils.cs @@ -11,7 +11,7 @@ namespace System.Reflection internal static class InvokeUtils { // This method is similar to the NativeAot method ConvertOrWidenPrimitivesEnumsAndPointersIfPossible(). - public static object ConvertOrWiden(Type srcType, CorElementType srcElementType, object srcObject, Type dstType, CorElementType dstElementType) + public static object ConvertOrWiden(Type srcType, object srcObject, Type dstType, CorElementType dstElementType) { object dstObject; diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/MemoryMarshal.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/MemoryMarshal.cs index 5f93c5308f886..d1cdd3544ef58 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/MemoryMarshal.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/MemoryMarshal.cs @@ -85,6 +85,7 @@ public static Memory AsMemory(ReadOnlyMemory memory) => /// public static ref T GetReference(ReadOnlySpan span) => ref span._reference; +#pragma warning disable IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 /// /// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to fake non-null pointer. Such a reference can be used /// for pinning but must never be dereferenced. This is useful for interop with methods that do not accept null pointers for zero-sized buffers. @@ -98,6 +99,7 @@ public static Memory AsMemory(ReadOnlyMemory memory) => /// [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static unsafe ref T GetNonNullPinnableReference(ReadOnlySpan span) => ref (span.Length != 0) ? ref Unsafe.AsRef(in span._reference) : ref Unsafe.AsRef((void*)1); +#pragma warning restore IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 /// /// Casts a Span of one primitive type to another primitive type . diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/PosixSignalRegistration.PlatformNotSupported.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/PosixSignalRegistration.PlatformNotSupported.cs index 9db94c31ba242..ae6781b2b552e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/PosixSignalRegistration.PlatformNotSupported.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/PosixSignalRegistration.PlatformNotSupported.cs @@ -9,9 +9,11 @@ public sealed partial class PosixSignalRegistration { private PosixSignalRegistration() { } +#pragma warning disable IDE0060 [DynamicDependency("#ctor")] // Prevent the private ctor and the IDisposable implementation from getting linked away private static PosixSignalRegistration Register(PosixSignal signal, Action handler) => throw new PlatformNotSupportedException(); +#pragma warning restore IDE0060 partial void Unregister(); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Wasm/PackedSimd.PlatformNotSupported.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Wasm/PackedSimd.PlatformNotSupported.cs index fbc47a4330ac6..644956f2deb50 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Wasm/PackedSimd.PlatformNotSupported.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/Wasm/PackedSimd.PlatformNotSupported.cs @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; -using System.Runtime.Intrinsics; + +#pragma warning disable IDE0060 namespace System.Runtime.Intrinsics.Wasm { diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/X86/X86Base.PlatformNotSupported.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/X86/X86Base.PlatformNotSupported.cs index 9ca497a5b8990..ad93f26912ee1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/X86/X86Base.PlatformNotSupported.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/Intrinsics/X86/X86Base.PlatformNotSupported.cs @@ -15,6 +15,8 @@ internal X86Base() { } public static bool IsSupported { [Intrinsic] get => false; } +#pragma warning disable IDE0060 + public abstract class X64 { internal X64() { } @@ -77,5 +79,8 @@ internal X64() { } /// PAUSE /// public static void Pause() { throw new PlatformNotSupportedException(); } + +#pragma warning restore IDE0060 + } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Span.cs b/src/libraries/System.Private.CoreLib/src/System/Span.cs index 424ef84939dc5..5836ba4d5c8cb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Span.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Span.cs @@ -124,6 +124,7 @@ public Span(ref T reference) _length = 1; } +#pragma warning disable IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 // Constructor for internal use only. It is not safe to expose publicly, and is instead exposed via the unsafe MemoryMarshal.CreateSpan. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Span(ref T reference, int length) @@ -133,6 +134,7 @@ internal Span(ref T reference, int length) _reference = ref reference; _length = length; } +#pragma warning restore IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 /// /// Returns a reference to specified element of the Span. diff --git a/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.T.cs b/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.T.cs index be973f1f53be5..e3bef2bfe4702 100644 --- a/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.T.cs +++ b/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.T.cs @@ -7,6 +7,8 @@ using System.Runtime.CompilerServices; using System.Runtime.Intrinsics; +#pragma warning disable IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 + namespace System { internal static partial class SpanHelpers // .T diff --git a/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.cs b/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.cs index c46f5ec8ae425..fa40a769f92e3 100644 --- a/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.cs +++ b/src/libraries/System.Private.CoreLib/src/System/SpanHelpers.cs @@ -572,6 +572,7 @@ public static void Reverse(ref T elements, nuint length) ReverseInner(ref elements, length); } +#pragma warning disable IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void ReverseInner(ref T elements, nuint length) { @@ -588,5 +589,6 @@ private static void ReverseInner(ref T elements, nuint length) last = ref Unsafe.Subtract(ref last, 1); } while (Unsafe.IsAddressLessThan(ref first, ref last)); } +#pragma warning restore IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6228 } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/NativeRuntimeEventSource.PortableThreadPool.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/NativeRuntimeEventSource.PortableThreadPool.cs index 04e48db29d8a3..d1fcaf7adc6f1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/NativeRuntimeEventSource.PortableThreadPool.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/NativeRuntimeEventSource.PortableThreadPool.cs @@ -91,6 +91,7 @@ private unsafe void WriteThreadEvent(int eventId, uint numExistingThreads) WriteEventCore(eventId, 3, data); } +#pragma warning disable IDE0060 [Event(50, Level = EventLevel.Informational, Message = Messages.WorkerThread, Task = Tasks.ThreadPoolWorkerThread, Opcode = EventOpcode.Start, Version = 0, Keywords = Keywords.ThreadingKeyword)] public unsafe void ThreadPoolWorkerThreadStart( uint ActiveWorkerThreadCount, @@ -127,6 +128,7 @@ public void ThreadPoolWorkerThreadWait( WriteThreadEvent(57, ActiveWorkerThreadCount); } } +#pragma warning restore IDE0060 [System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = EventSourceSuppressMessage)] diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.GateThread.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.GateThread.cs index c2a8544479b64..5d1b79a3098e0 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.GateThread.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/PortableThreadPool.GateThread.cs @@ -218,7 +218,7 @@ internal static void EnsureRunningSlow(PortableThreadPool threadPoolInstance) } else if ((numRunsMask & GateThreadRunningMask) == 0) { - CreateGateThread(threadPoolInstance); + CreateGateThread(); } } @@ -229,7 +229,7 @@ private static int GetRunningStateForNumRuns(int numRuns) return GateThreadRunningMask | numRuns; } - private static void CreateGateThread(PortableThreadPool threadPoolInstance) + private static void CreateGateThread() { try { diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.MinimalGlobalizationData.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.MinimalGlobalizationData.cs index 5ef4d16edaa15..d04de84dcc8f8 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.MinimalGlobalizationData.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.MinimalGlobalizationData.cs @@ -5,10 +5,8 @@ namespace System { public sealed partial class TimeZoneInfo { - private static void TryPopulateTimeZoneDisplayNamesFromGlobalizationData(string timeZoneId, TimeSpan baseUtcOffset, ref string? standardDisplayName, ref string? daylightDisplayName, ref string? displayName) - { - // Do nothing. We'll use the fallback values already set. - } +#pragma warning disable IDE0060 + static partial void TryPopulateTimeZoneDisplayNamesFromGlobalizationData(string timeZoneId, TimeSpan baseUtcOffset, ref string? standardDisplayName, ref string? daylightDisplayName, ref string? displayName); private static string GetUtcStandardDisplayName() { @@ -40,5 +38,6 @@ private static unsafe bool TryConvertWindowsIdToIanaId(string windowsId, string? ianaId = null; return false; } +#pragma warning restore IDE0060 } } diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Win32.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Win32.cs index c0774303f3f91..6152acc0e8a52 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Win32.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Win32.cs @@ -1006,7 +1006,7 @@ private static string GetUtcStandardDisplayName() } // Helper function to get the full display name for the UTC static time zone instance - private static string GetUtcFullDisplayName(string timeZoneId, string standardDisplayName) + private static string GetUtcFullDisplayName(string _ /*timeZoneId*/, string standardDisplayName) { return $"(UTC) {standardDisplayName}"; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/BitFlagsGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/BitFlagsGenerator.cs index ca8c911f01296..5b1b4852f8877 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/BitFlagsGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/BitFlagsGenerator.cs @@ -14,7 +14,7 @@ internal sealed class BitFlagsGenerator private readonly CodeGenerator _ilg; private readonly LocalBuilder[] _locals; - public BitFlagsGenerator(int bitCount, CodeGenerator ilg, string localName) + public BitFlagsGenerator(int bitCount, CodeGenerator ilg) { _ilg = ilg; _bitCount = bitCount; @@ -22,7 +22,7 @@ public BitFlagsGenerator(int bitCount, CodeGenerator ilg, string localName) _locals = new LocalBuilder[localCount]; for (int i = 0; i < _locals.Length; i++) { - _locals[i] = ilg.DeclareLocal(typeof(byte), localName + i, (byte)0); + _locals[i] = ilg.DeclareLocal(typeof(byte), (byte)0); } } @@ -68,7 +68,7 @@ public void Load(int bitIndex) public void LoadArray() { - LocalBuilder localArray = _ilg.DeclareLocal(Globals.TypeOfByteArray, "localArray"); + LocalBuilder localArray = _ilg.DeclareLocal(Globals.TypeOfByteArray); _ilg.NewArray(typeof(byte), _locals.Length); _ilg.Store(localArray); for (int i = 0; i < _locals.Length; i++) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs index 953196aa81bdb..ba6d73260b369 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs @@ -108,13 +108,13 @@ internal static MethodInfo GetInvokeMethod(Type delegateType) internal CodeGenerator() { } - internal void BeginMethod(DynamicMethod dynamicMethod, Type delegateType, string methodName, Type[] argTypes, bool allowPrivateMemberAccess) + internal void BeginMethod(DynamicMethod dynamicMethod, Type delegateType, Type[] argTypes) { _dynamicMethod = dynamicMethod; _ilGen = _dynamicMethod.GetILGenerator(); _delegateType = delegateType; - InitILGeneration(methodName, argTypes); + InitILGeneration(argTypes); } [RequiresDynamicCode(DataContract.SerializerAOTWarning)] @@ -136,10 +136,10 @@ private void BeginMethod(Type returnType, string methodName, Type[] argTypes, bo _ilGen = _dynamicMethod.GetILGenerator(); - InitILGeneration(methodName, argTypes); + InitILGeneration(argTypes); } - private void InitILGeneration(string methodName, Type[] argTypes) + private void InitILGeneration(Type[] argTypes) { _methodEndLabel = _ilGen.DefineLabel(); _blockStack = new Stack(); @@ -187,15 +187,15 @@ internal static Type GetVariableType(object var) return var.GetType(); } - internal LocalBuilder DeclareLocal(Type type, string name, object initialValue) + internal LocalBuilder DeclareLocal(Type type, object initialValue) { - LocalBuilder local = DeclareLocal(type, name); + LocalBuilder local = DeclareLocal(type); Load(initialValue); Store(local); return local; } - internal LocalBuilder DeclareLocal(Type type, string name) + internal LocalBuilder DeclareLocal(Type type) { return DeclareLocal(type, false); } @@ -279,7 +279,7 @@ internal void InternalBreakFor(object userForState, OpCode branchInstruction) } } - internal void ForEach(LocalBuilder local, Type elementType, Type enumeratorType, + internal void ForEach(LocalBuilder local, Type elementType, LocalBuilder enumerator, MethodInfo getCurrentMethod) { ForState forState = new ForState(local, DefineLabel(), DefineLabel(), enumerator); @@ -659,7 +659,7 @@ internal void LoadDefaultValue(Type type) case TypeCode.Decimal: case TypeCode.DateTime: default: - LocalBuilder zero = DeclareLocal(type, "zero"); + LocalBuilder zero = DeclareLocal(type); LoadAddress(zero); InitObj(type); Load(zero); @@ -1028,7 +1028,6 @@ internal void Stelem(Type arrayElementType) OpCode opCode = GetStelemOpCode(Type.GetTypeCode(arrayElementType)); if (opCode.Equals(OpCodes.Nop)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayTypeIsNotSupported_GeneratingCode, DataContract.GetClrTypeFullName(arrayElementType)))); - _ilGen.Emit(opCode); } } @@ -1221,7 +1220,7 @@ internal Label[] Switch(int labelCount) _blockStack.Push(switchState); return caseLabels; } - internal void Case(Label caseLabel1, string caseLabelName) + internal void Case(Label caseLabel1) { MarkLabel(caseLabel1); } @@ -1293,7 +1292,7 @@ internal void EndWhile() internal void CallStringFormat(string msg, params object[] values) { NewArray(typeof(object), values.Length); - _stringFormatArray ??= DeclareLocal(typeof(object[]), "stringFormatArray"); + _stringFormatArray ??= DeclareLocal(typeof(object[])); Stloc(_stringFormatArray); for (int i = 0; i < values.Length; i++) StoreArrayElement(_stringFormatArray, i, values[i]); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs index f5776bef56be7..392157161feeb 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs @@ -53,12 +53,12 @@ internal DataContract(DataContractCriticalHelper helper) [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] internal static DataContract GetDataContract(Type type) { - return GetDataContract(type.TypeHandle, type); + return GetDataContract(type.TypeHandle); } [RequiresDynamicCode(DataContract.SerializerAOTWarning)] [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - internal static DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type? type) + internal static DataContract GetDataContract(RuntimeTypeHandle typeHandle) { int id = GetId(typeHandle); DataContract dataContract = GetDataContractSkipValidation(id, typeHandle, null); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs index 1b54f8255b049..b98bad5c8cd4c 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs @@ -79,11 +79,11 @@ public DataContractSerializer(Type type, string rootName, string rootNamespace) } public DataContractSerializer(Type type, string rootName, string rootNamespace, IEnumerable? knownTypes) - : this(type, rootName, rootNamespace, knownTypes, int.MaxValue, false, false) + : this(type, rootName, rootNamespace, knownTypes, false, false) { } - internal DataContractSerializer(Type type, string rootName, string rootNamespace, IEnumerable? knownTypes, int maxItemsInObjectGraph, + internal DataContractSerializer(Type type, string rootName, string rootNamespace, IEnumerable? knownTypes, bool ignoreExtensionDataObject, bool preserveObjectReferences) { XmlDictionary dictionary = new XmlDictionary(2); @@ -434,7 +434,7 @@ internal static DataContract GetDataContract(DataContract declaredTypeContract, } else { - return DataContract.GetDataContract(objectType.TypeHandle, objectType); + return DataContract.GetDataContract(objectType); } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DateTimeOffsetAdapter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DateTimeOffsetAdapter.cs index da469b0c337c6..b585a4f13f7c0 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DateTimeOffsetAdapter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DateTimeOffsetAdapter.cs @@ -64,9 +64,11 @@ public static DateTimeOffsetAdapter GetDateTimeOffsetAdapter(DateTimeOffset valu return new DateTimeOffsetAdapter(value.UtcDateTime, (short)value.Offset.TotalMinutes); } +#pragma warning disable IDE0060 // https://github.com/dotnet/runtime/issues/76012 public string ToString(IFormatProvider provider) { return "DateTime: " + UtcDateTime + ", Offset: " + OffsetMinutes; } +#pragma warning restore IDE0060 } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs index cbde92415a485..786363fadd01d 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs @@ -184,7 +184,7 @@ private static void BeginMethod(CodeGenerator ilg, string methodName, Type deleg paramTypes[i] = parameters[i].ParameterType; DynamicMethod dynamicMethod = new DynamicMethod(methodName, signature.ReturnType, paramTypes, typeof(JsonFormatReaderGenerator).Module, allowPrivateMemberAccess); - ilg.BeginMethod(dynamicMethod, delegateType, methodName, paramTypes, allowPrivateMemberAccess); + ilg.BeginMethod(dynamicMethod, delegateType, paramTypes); } private void InitArgs() @@ -201,7 +201,7 @@ private void CreateObject(ClassDataContract classContract) _objectType = classContract.UnderlyingType; Type type = classContract.ObjectType; - _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); + _objectLocal = _ilg.DeclareLocal(type); if (classContract.UnderlyingType == Globals.TypeOfDBNull) { @@ -284,7 +284,7 @@ private void ReadClass(ClassDataContract classContract) { if (classContract.HasExtensionData) { - LocalBuilder extensionDataLocal = _ilg.DeclareLocal(Globals.TypeOfExtensionDataObject, "extensionData"); + LocalBuilder extensionDataLocal = _ilg.DeclareLocal(Globals.TypeOfExtensionDataObject); _ilg.New(JsonFormatGeneratorStatics.ExtensionDataObjectCtor); _ilg.Store(extensionDataLocal); ReadMembers(classContract, extensionDataLocal); @@ -311,12 +311,12 @@ private void ReadMembers(ClassDataContract classContract, LocalBuilder? extensio int memberCount = classContract.MemberNames!.Length; _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, memberCount); - BitFlagsGenerator expectedElements = new BitFlagsGenerator(memberCount, _ilg, classContract.UnderlyingType.Name + "_ExpectedElements"); + BitFlagsGenerator expectedElements = new BitFlagsGenerator(memberCount, _ilg); byte[] requiredElements = new byte[expectedElements.GetLocalCount()]; SetRequiredElements(classContract, requiredElements); SetExpectedElements(expectedElements, 0 /*startIndex*/); - LocalBuilder memberIndexLocal = _ilg.DeclareLocal(Globals.TypeOfInt, "memberIndex", -1); + LocalBuilder memberIndexLocal = _ilg.DeclareLocal(Globals.TypeOfInt, -1); Label throwDuplicateMemberLabel = _ilg.DefineLabel(); Label throwMissingRequiredMembersLabel = _ilg.DefineLabel(); @@ -347,7 +347,7 @@ private void ReadMembers(ClassDataContract classContract, LocalBuilder? extensio _ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfObject); _ilg.Load(_memberNamesArg); expectedElements.LoadArray(); - LoadArray(requiredElements, "requiredElements"); + LoadArray(requiredElements); _ilg.Call(JsonFormatGeneratorStatics.ThrowMissingRequiredMembersMethod); _ilg.MarkLabel(endOfTypeLabel); @@ -365,7 +365,7 @@ private int ReadMembers(ClassDataContract classContract, BitFlagsGenerator expec { DataMember dataMember = classContract.Members[i]; Type memberType = dataMember.MemberType; - _ilg.Case(memberLabels[memberCount], dataMember.Name); + _ilg.Case(memberLabels[memberCount]); _ilg.Set(memberIndexLocal, memberCount); expectedElements.Load(memberCount); _ilg.Brfalse(throwDuplicateMemberLabel); @@ -374,7 +374,7 @@ private int ReadMembers(ClassDataContract classContract, BitFlagsGenerator expec { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(dataMember.MemberInfo); - value = _ilg.DeclareLocal(memberType, dataMember.Name + "Value"); + value = _ilg.DeclareLocal(memberType); _ilg.Stloc(value); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.StoreCollectionMemberInfoMethod, value); ReadValue(memberType, dataMember.Name); @@ -407,9 +407,9 @@ private void CheckRequiredElements(BitFlagsGenerator expectedElements, byte[] re } } - private void LoadArray(byte[] array, string name) + private void LoadArray(byte[] array) { - LocalBuilder localArray = _ilg.DeclareLocal(Globals.TypeOfByteArray, name); + LocalBuilder localArray = _ilg.DeclareLocal(Globals.TypeOfByteArray); _ilg.NewArray(typeof(byte), array.Length); _ilg.Store(localArray); for (int i = 0; i < array.Length; i++) @@ -466,7 +466,7 @@ private void ReadISerializable(ClassDataContract classContract) [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private LocalBuilder ReadValue(Type type, string name) { - LocalBuilder value = _ilg.DeclareLocal(type, "valueRead"); + LocalBuilder value = _ilg.DeclareLocal(type); LocalBuilder? nullableValue = null; int nullables = 0; while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) @@ -478,7 +478,7 @@ private LocalBuilder ReadValue(Type type, string name) PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) { - LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); + LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadAttributesMethod, _xmlReaderArg); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadIfNullOrRefMethod, _xmlReaderArg, type, DataContract.IsTypeSerializable(type)); _ilg.Stloc(objectId); @@ -512,7 +512,7 @@ private LocalBuilder ReadValue(Type type, string name) if (nullables != 0) { nullableValue = value; - value = _ilg.DeclareLocal(type, "innerValueRead"); + value = _ilg.DeclareLocal(type); } if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) @@ -626,7 +626,7 @@ private void ReadCollection(CollectionDataContract collectionContract) } } - _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); + _objectLocal = _ilg.DeclareLocal(type); if (!isArray) { if (type.IsValueType) @@ -655,7 +655,7 @@ private void ReadCollection(CollectionDataContract collectionContract) _ilg.Else(); } - LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); + LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod); _ilg.Stloc(objectId); @@ -669,11 +669,11 @@ private void ReadCollection(CollectionDataContract collectionContract) LocalBuilder? growingCollection = null; if (isArray) { - growingCollection = _ilg.DeclareLocal(type, "growingCollection"); + growingCollection = _ilg.DeclareLocal(type); _ilg.NewArray(itemType, 32); _ilg.Stloc(growingCollection); } - LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); + LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt); object forLoop = _ilg.For(i, 0, int.MaxValue); // Empty namespace IsStartElement(_memberNamesArg, _emptyDictionaryStringArg); @@ -765,7 +765,7 @@ private void ReadSimpleDictionary(CollectionDataContract collectionContract, Typ } else { - LocalBuilder nodeType = _ilg.DeclareLocal(typeof(XmlNodeType), "nodeType"); + LocalBuilder nodeType = _ilg.DeclareLocal(typeof(XmlNodeType)); _ilg.BeginWhileCondition(); _ilg.Call(_xmlReaderArg, JsonFormatGeneratorStatics.MoveToContentMethod); @@ -799,11 +799,11 @@ private void ReadSimpleDictionary(CollectionDataContract collectionContract, Typ { _ilg.Call(keyDataContract.ParseMethod!); } - LocalBuilder pairKey = _ilg.DeclareLocal(keyType, "key"); + LocalBuilder pairKey = _ilg.DeclareLocal(keyType); _ilg.Stloc(pairKey); if (keyTypeNullableDepth > 0) { - LocalBuilder pairKeyNullable = _ilg.DeclareLocal(keyTypeOriginal, "keyOriginal"); + LocalBuilder pairKeyNullable = _ilg.DeclareLocal(keyTypeOriginal); WrapNullableObject(pairKey, pairKeyNullable, keyTypeNullableDepth); pairKey = pairKeyNullable; } @@ -822,9 +822,9 @@ private void ReadGetOnlyCollection(CollectionDataContract collectionContract) Type type = collectionContract.UnderlyingType; Type itemType = collectionContract.ItemType; bool isArray = (collectionContract.Kind == CollectionKind.Array); - LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt, "arraySize"); + LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt); - _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); + _objectLocal = _ilg.DeclareLocal(type); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetCollectionMemberMethod); _ilg.ConvertValue(Globals.TypeOfObject, type); @@ -870,7 +870,7 @@ private void ReadGetOnlyCollection(CollectionDataContract collectionContract) _ilg.Stloc(size); } - LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); + LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt); object forLoop = _ilg.For(i, 0, int.MaxValue); IsStartElement(_memberNamesArg, _emptyDictionaryStringArg); _ilg.If(); @@ -964,7 +964,7 @@ private LocalBuilder ReadCollectionItem(CollectionDataContract collectionContrac if (collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary) { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ResetAttributesMethod); - LocalBuilder value = _ilg.DeclareLocal(itemType, "valueRead"); + LocalBuilder value = _ilg.DeclareLocal(itemType); _ilg.Load(_collectionContractArg); _ilg.Call(JsonFormatGeneratorStatics.GetItemContractMethod); _ilg.Call(JsonFormatGeneratorStatics.GetRevisedItemContractMethod); @@ -994,8 +994,8 @@ private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, C } DataMember keyMember = keyValuePairContract.Members![0]; DataMember valueMember = keyValuePairContract.Members[1]; - LocalBuilder pairKey = _ilg.DeclareLocal(keyMember.MemberType, keyMember.Name); - LocalBuilder pairValue = _ilg.DeclareLocal(valueMember.MemberType, valueMember.Name); + LocalBuilder pairKey = _ilg.DeclareLocal(keyMember.MemberType); + LocalBuilder pairValue = _ilg.DeclareLocal(valueMember.MemberType); _ilg.LoadAddress(value); _ilg.LoadMember(keyMember.MemberInfo); _ilg.Stloc(pairKey); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs index a3d4ea203812c..0ed588c941de6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs @@ -103,7 +103,7 @@ internal JsonFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionD InitArgs(collectionContract.UnderlyingType); if (collectionContract.IsReadOnlyContract) { - ThrowIfCannotSerializeReadOnlyTypes(collectionContract); + ThrowIfCannotSerializeReadOnlyTypes(); } WriteCollection(collectionContract); return (JsonFormatCollectionWriterDelegate)_ilg.EndMethod(); @@ -119,7 +119,7 @@ private static void BeginMethod(CodeGenerator ilg, string methodName, Type deleg paramTypes[i] = parameters[i].ParameterType; DynamicMethod dynamicMethod = new DynamicMethod(methodName, signature.ReturnType, paramTypes, typeof(JsonFormatWriterGenerator).Module, allowPrivateMemberAccess); - ilg.BeginMethod(dynamicMethod, delegateType, methodName, paramTypes, allowPrivateMemberAccess); + ilg.BeginMethod(dynamicMethod, delegateType, paramTypes); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] @@ -129,7 +129,7 @@ private void InitArgs(Type objType) _contextArg = _ilg.GetArg(2); _dataContractArg = _ilg.GetArg(3); - _objectLocal = _ilg.DeclareLocal(objType, "objSerialized"); + _objectLocal = _ilg.DeclareLocal(objType); ArgBuilder objectArg = _ilg.GetArg(1); _ilg.Load(objectArg); @@ -154,7 +154,7 @@ private void InitArgs(Type objType) _ilg.Stloc(_objectLocal); } - private void ThrowIfCannotSerializeReadOnlyTypes(CollectionDataContract classContract) + private void ThrowIfCannotSerializeReadOnlyTypes() { ThrowIfCannotSerializeReadOnlyTypes(XmlFormatGeneratorStatics.CollectionSerializationExceptionMessageProperty); } @@ -210,7 +210,7 @@ private void WriteClass(ClassDataContract classContract) { if (classContract.HasExtensionData) { - LocalBuilder extensionDataLocal = _ilg.DeclareLocal(Globals.TypeOfExtensionDataObject, "extensionData"); + LocalBuilder extensionDataLocal = _ilg.DeclareLocal(Globals.TypeOfExtensionDataObject); _ilg.Load(_objectLocal); _ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfIExtensibleDataObject); _ilg.LoadMember(JsonFormatGeneratorStatics.ExtensionDataProperty); @@ -298,7 +298,7 @@ private LocalBuilder LoadMemberValue(DataMember member) { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(member.MemberInfo); - LocalBuilder memberValue = _ilg.DeclareLocal(member.MemberType, member.Name + "Value"); + LocalBuilder memberValue = _ilg.DeclareLocal(member.MemberType); _ilg.Stloc(memberValue); return memberValue; } @@ -307,14 +307,14 @@ private LocalBuilder LoadMemberValue(DataMember member) [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private void WriteCollection(CollectionDataContract collectionContract) { - LocalBuilder itemName = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemName"); + LocalBuilder itemName = _ilg.DeclareLocal(typeof(XmlDictionaryString)); _ilg.LoadMember(JsonFormatGeneratorStatics.CollectionItemNameProperty); _ilg.Store(itemName); if (collectionContract.Kind == CollectionKind.Array) { Type itemType = collectionContract.ItemType; - LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); + LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementArrayCountMethod, _xmlWriterArg, _objectLocal); @@ -326,7 +326,7 @@ private void WriteCollection(CollectionDataContract collectionContract) { WriteStartElement(itemName, 0 /*nameIndex*/); _ilg.LoadArrayElement(_objectLocal, i); - LocalBuilder memberValue = _ilg.DeclareLocal(itemType, "memberValue"); + LocalBuilder memberValue = _ilg.DeclareLocal(itemType); _ilg.Stloc(memberValue); WriteValue(memberValue); WriteEndElement(); @@ -411,9 +411,9 @@ private void WriteCollection(CollectionDataContract collectionContract) } } Type elementType = getCurrentMethod.ReturnType; - LocalBuilder currentValue = _ilg.DeclareLocal(elementType, "currentValue"); + LocalBuilder currentValue = _ilg.DeclareLocal(elementType); - LocalBuilder enumerator = _ilg.DeclareLocal(enumeratorType, "enumerator"); + LocalBuilder enumerator = _ilg.DeclareLocal(enumeratorType); _ilg.Call(_objectLocal, collectionContract.GetEnumeratorMethod); if (isDictionary) { @@ -443,9 +443,9 @@ private void WriteCollection(CollectionDataContract collectionContract) _ilg.LoadMember(JsonFormatGeneratorStatics.UseSimpleDictionaryFormatWriteProperty); _ilg.If(); WriteObjectAttribute(); - LocalBuilder pairKey = _ilg.DeclareLocal(Globals.TypeOfString, "key"); - LocalBuilder pairValue = _ilg.DeclareLocal(keyValueTypes[1], "value"); - _ilg.ForEach(currentValue, elementType, enumeratorType, enumerator, getCurrentMethod); + LocalBuilder pairKey = _ilg.DeclareLocal(Globals.TypeOfString); + LocalBuilder pairValue = _ilg.DeclareLocal(keyValueTypes[1]); + _ilg.ForEach(currentValue, elementType, enumerator, getCurrentMethod); _ilg.LoadAddress(currentValue); _ilg.LoadMember(genericDictionaryKeyProperty); @@ -466,7 +466,7 @@ private void WriteCollection(CollectionDataContract collectionContract) WriteArrayAttribute(); - _ilg.ForEach(currentValue, elementType, enumeratorType, enumerator, getCurrentMethod); + _ilg.ForEach(currentValue, elementType, enumerator, getCurrentMethod); if (incrementCollectionCountMethod == null) { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); @@ -629,7 +629,7 @@ private void WriteValue(LocalBuilder memberValue) _ilg.Load(memberType); _ilg.Call(JsonFormatGeneratorStatics.BoxPointer); memberType = typeof(System.Reflection.Pointer); - memberValue = _ilg.DeclareLocal(memberType, "memberValueRefPointer"); + memberValue = _ilg.DeclareLocal(memberType); _ilg.Store(memberValue); } bool isNullableOfT = (memberType.IsGenericType && @@ -678,7 +678,7 @@ private void WriteValue(LocalBuilder memberValue) { _ilg.Load(memberValue); _ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject); - memberValue = _ilg.DeclareLocal(Globals.TypeOfObject, "unwrappedMemberValue"); + memberValue = _ilg.DeclareLocal(Globals.TypeOfObject); memberType = memberValue.LocalType; _ilg.Stloc(memberValue); _ilg.If(memberValue, Cmp.EqualTo, null); @@ -701,7 +701,7 @@ private void InternalSerialize(MethodInfo methodInfo, LocalBuilder memberValue, _ilg.Load(_xmlWriterArg); _ilg.Load(memberValue); _ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject); - LocalBuilder typeHandleValue = _ilg.DeclareLocal(typeof(RuntimeTypeHandle), "typeHandleValue"); + LocalBuilder typeHandleValue = _ilg.DeclareLocal(typeof(RuntimeTypeHandle)); _ilg.Call(memberValue, XmlFormatGeneratorStatics.GetTypeMethod); _ilg.Call(XmlFormatGeneratorStatics.GetTypeHandleMethod); _ilg.Stloc(typeHandleValue); @@ -731,7 +731,7 @@ private LocalBuilder UnwrapNullableObject(LocalBuilder memberValue)// Leaves !Ha _ilg.Call(typeof(Nullable<>).MakeGenericType(innerType).GetMethod("get_Value")!); memberType = innerType; } - memberValue = _ilg.DeclareLocal(memberType, "nullableUnwrappedMemberValue"); + memberValue = _ilg.DeclareLocal(memberType); _ilg.Stloc(memberValue); _ilg.Load(false); //isNull _ilg.Br(end); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatReader.cs index 342659448ca03..b1bb653913ec8 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatReader.cs @@ -29,7 +29,7 @@ public ReflectionJsonClassReader(ClassDataContract classDataContract) [RequiresDynamicCode(DataContract.SerializerAOTWarning)] [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson? context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[]? memberNames) + public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson? context, XmlDictionaryString _, XmlDictionaryString[]? memberNames) { Debug.Assert(_classContract != null); return _reflectionReader.ReflectionReadClass(xmlReader, context, memberNames, null /*memberNamespaces*/, _classContract); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs index 328fd1e3e23e2..5a8c71ff86807 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs @@ -41,7 +41,7 @@ public static void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, objec { context.IncrementArrayCount(jsonWriter, (Array)obj); Type itemType = collectionContract.ItemType; - if (!ReflectionTryWritePrimitiveArray(jsonWriter, obj, collectionContract.UnderlyingType, itemType, itemName)) + if (!ReflectionTryWritePrimitiveArray(jsonWriter, obj, itemType, itemName)) { ReflectionWriteArrayAttribute(jsonWriter); @@ -141,7 +141,7 @@ private static void ReflectionWriteObjectAttribute(XmlWriterDelegator xmlWriter) [RequiresDynamicCode(DataContract.SerializerAOTWarning)] [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private static bool ReflectionTryWritePrimitiveArray(JsonWriterDelegator jsonWriter, object obj, Type underlyingType, Type itemType, XmlDictionaryString collectionItemName) + private static bool ReflectionTryWritePrimitiveArray(JsonWriterDelegator jsonWriter, object obj, Type itemType, XmlDictionaryString collectionItemName) { PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) @@ -246,7 +246,7 @@ protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, obje memberValue ??= ReflectionGetMemberValue(obj, member); bool requiresNameAttribute = DataContractJsonSerializer.CheckIfXmlNameRequiresMapping(classContract.MemberNames![i]); PrimitiveDataContract? primitiveContract = member.MemberPrimitiveContract; - if (requiresNameAttribute || !ReflectionTryWritePrimitive(xmlWriter, context, memberType, memberValue, memberNames[i + childElementIndex] /*name*/, null/*ns*/, primitiveContract)) + if (requiresNameAttribute || !ReflectionTryWritePrimitive(xmlWriter, context, memberValue, memberNames[i + childElementIndex] /*name*/, null/*ns*/, primitiveContract)) { // Note: DataContractSerializer has member-conflict logic here to deal with the schema export // requirement that the same member can't be of two different types. diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionClassWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionClassWriter.cs index c8faaec179e22..b15050bbd7427 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionClassWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionClassWriter.cs @@ -23,7 +23,7 @@ internal abstract class ReflectionClassWriter public void ReflectionWriteClass(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, XmlDictionaryString[]? memberNames) { InvokeOnSerializing(obj, context, classContract); - obj = ResolveAdapterType(obj, classContract); + obj = ResolveAdapterType(obj); if (classContract.IsISerializable) { context.WriteISerializable(xmlWriter, (ISerializable)obj); @@ -117,7 +117,7 @@ public static void ReflectionWriteValue(XmlWriterDelegator xmlWriter, XmlObjectS [RequiresDynamicCode(DataContract.SerializerAOTWarning)] [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - protected static bool ReflectionTryWritePrimitive(XmlWriterDelegator xmlWriter, XmlObjectSerializerWriteContext context, Type type, object? value, XmlDictionaryString name, XmlDictionaryString? ns, PrimitiveDataContract? primitiveContract) + protected static bool ReflectionTryWritePrimitive(XmlWriterDelegator xmlWriter, XmlObjectSerializerWriteContext context, object? value, XmlDictionaryString name, XmlDictionaryString? ns, PrimitiveDataContract? primitiveContract) { if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject) return false; @@ -149,7 +149,7 @@ private void InvokeOnSerialized(object obj, XmlObjectSerializerWriteContext cont } } - private static object ResolveAdapterType(object obj, ClassDataContract classContract) + private static object ResolveAdapterType(object obj) { Type type = obj.GetType(); if (type == Globals.TypeOfDateTimeOffset) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs index a92d18f2fcf36..49e82ce4baf47 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs @@ -55,7 +55,7 @@ public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSeriali obj = context.GetRealObject(objectReference, context.GetObjectId()); } - obj = ResolveAdapterObject(obj, classContract); + obj = ResolveAdapterObject(obj); InvokeDeserializationCallback(obj); InvokeOnDeserialized(context, classContract, obj); @@ -100,7 +100,7 @@ private object ReflectionReadCollectionCore(XmlReaderDelegator xmlReader, XmlObj int arraySize = context.GetArraySize(); object? resultArray; - if (isArray && ReflectionTryReadPrimitiveArray(xmlReader, context, collectionItemName, collectionItemNamespace, collectionContract.UnderlyingType, collectionContract.ItemType, arraySize, out resultArray)) + if (isArray && ReflectionTryReadPrimitiveArray(xmlReader, context, collectionItemName, collectionItemNamespace, collectionContract.ItemType, arraySize, out resultArray)) { return resultArray; } @@ -434,7 +434,7 @@ private static object CreateObject(ClassDataContract classContract) return obj; } - private static object ResolveAdapterObject(object obj, ClassDataContract classContract) + private static object ResolveAdapterObject(object obj) { Type objType = obj.GetType(); if (objType == Globals.TypeOfDateTimeOffsetAdapter) @@ -621,7 +621,7 @@ private static CollectionSetItemDelegate GetCollectionSetItemDelegate(Collect [RequiresDynamicCode(DataContract.SerializerAOTWarning)] [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private static bool ReflectionTryReadPrimitiveArray(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString collectionItemName, XmlDictionaryString collectionItemNamespace, Type type, Type itemType, int arraySize, [NotNullWhen(true)] out object? resultArray) + private static bool ReflectionTryReadPrimitiveArray(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString collectionItemName, XmlDictionaryString collectionItemNamespace, Type itemType, int arraySize, [NotNullWhen(true)] out object? resultArray) { resultArray = null; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs index 27097b233dbc9..f822e5fbffaca 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs @@ -39,13 +39,13 @@ public static void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, objec { context.IncrementArrayCount(xmlWriter, (Array)obj); Type itemType = collectionDataContract.ItemType; - if (!ReflectionTryWritePrimitiveArray(xmlWriter, obj, collectionDataContract.UnderlyingType, itemType, itemName, ns)) + if (!ReflectionTryWritePrimitiveArray(xmlWriter, obj, itemType, itemName, ns)) { Array array = (Array)obj; PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); for (int i = 0; i < array.Length; ++i) { - ReflectionXmlClassWriter.ReflectionWriteStartElement(xmlWriter, itemType, ns, ns.Value, itemName.Value, 0); + ReflectionXmlClassWriter.ReflectionWriteStartElement(xmlWriter, itemType, ns, ns.Value, itemName.Value); ReflectionXmlClassWriter.ReflectionWriteValue(xmlWriter, context, itemType, array.GetValue(i), false, primitiveContract); ReflectionXmlClassWriter.ReflectionWriteEndElement(xmlWriter); } @@ -75,7 +75,7 @@ public static void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, objec { object current = enumerator.Current; context.IncrementItemCount(1); - ReflectionXmlClassWriter.ReflectionWriteStartElement(xmlWriter, elementType, ns, ns.Value, itemName.Value, 0); + ReflectionXmlClassWriter.ReflectionWriteStartElement(xmlWriter, elementType, ns, ns.Value, itemName.Value); if (isDictionary) { collectionDataContract.ItemContract.WriteXmlValue(xmlWriter, current, context); @@ -93,7 +93,7 @@ public static void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, objec [RequiresDynamicCode(DataContract.SerializerAOTWarning)] [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private static bool ReflectionTryWritePrimitiveArray(XmlWriterDelegator xmlWriter, object obj, Type type, Type itemType, XmlDictionaryString collectionItemName, XmlDictionaryString itemNamespace) + private static bool ReflectionTryWritePrimitiveArray(XmlWriterDelegator xmlWriter, object obj, Type itemType, XmlDictionaryString collectionItemName, XmlDictionaryString itemNamespace) { PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) @@ -181,9 +181,9 @@ protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, obje memberValue ??= ReflectionGetMemberValue(obj, member); PrimitiveDataContract? primitiveContract = member.MemberPrimitiveContract; - if (writeXsiType || !ReflectionTryWritePrimitive(xmlWriter, context, memberType, memberValue, memberNames[i + childElementIndex] /*name*/, ns, primitiveContract)) + if (writeXsiType || !ReflectionTryWritePrimitive(xmlWriter, context, memberValue, memberNames[i + childElementIndex] /*name*/, ns, primitiveContract)) { - ReflectionWriteStartElement(xmlWriter, memberType, ns, ns.Value, member.Name, 0); + ReflectionWriteStartElement(xmlWriter, memberType, ns, ns.Value, member.Name); if (classContract.ChildElementNamespaces![i + childElementIndex] != null) { var nsChildElement = classContract.ChildElementNamespaces[i + childElementIndex]!; @@ -203,7 +203,7 @@ protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, obje return memberCount; } - public static void ReflectionWriteStartElement(XmlWriterDelegator xmlWriter, Type type, XmlDictionaryString ns, string namespaceLocal, string nameLocal, int nameIndex) + public static void ReflectionWriteStartElement(XmlWriterDelegator xmlWriter, Type type, XmlDictionaryString ns, string namespaceLocal, string nameLocal) { bool needsPrefix = NeedsPrefix(type, ns); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs index 2f29ebad39b27..3a93e66279d26 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs @@ -348,7 +348,7 @@ private XmlElement ExportGenericInfo(Type clrType, string elementName, string el if (_dataContractSet.SerializationExtendedSurrogateProvider != null) DataContractSurrogateCaller.GetKnownCustomDataTypes(_dataContractSet.SerializationExtendedSurrogateProvider, knownTypes); DataContractSerializer serializer = new DataContractSerializer(Globals.TypeOfObject, - SurrogateDataAnnotationName.Name, SurrogateDataAnnotationName.Namespace, knownTypes, int.MaxValue, + SurrogateDataAnnotationName.Name, SurrogateDataAnnotationName.Namespace, knownTypes, ignoreExtensionDataObject: false, preserveObjectReferences: true); serializer.WriteObject(xmlWriter, surrogateData); xmlWriter.Flush(); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaImporter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaImporter.cs index 437a3d3990f1a..478a97592bf63 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaImporter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaImporter.cs @@ -639,7 +639,7 @@ private static void RemoveOptionalUnknownSerializationElements(XmlSchemaObjectCo ThrowTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.Format(SR.RootSequenceMaxOccursMustBe)); if (!isDerived && CheckIfCollection(rootSequence)) - dataContract = ImportCollection(typeName, rootSequence, attributes, annotation, isReference); + dataContract = ImportCollection(typeName, rootSequence, annotation, isReference); else if (CheckIfISerializable(rootSequence, attributes)) dataContract = ImportISerializable(typeName, rootSequence, baseTypeName, attributes, annotation); else @@ -666,7 +666,7 @@ private ClassDataContract ImportClass(XmlQualifiedName typeName, XmlSchemaSequen Debug.Assert(dataContract.BaseClassContract != null); // ImportBaseContract will always set this... or throw. if (dataContract.BaseClassContract.IsISerializable) { - if (IsISerializableDerived(typeName, rootSequence)) + if (IsISerializableDerived(rootSequence)) dataContract.IsISerializable = true; else ThrowTypeCannotBeImportedException(dataContract.XmlName.Name, dataContract.XmlName.Namespace, SR.Format(SR.DerivedTypeNotISerializable, baseTypeName.Name, baseTypeName.Namespace)); @@ -838,7 +838,7 @@ private ClassDataContract ImportISerializable(XmlQualifiedName typeName, XmlSche Debug.Assert(dataContract.BaseClassContract != null); // ImportBaseContract will always set this... or throw. if (!dataContract.BaseClassContract.IsISerializable) ThrowISerializableTypeCannotBeImportedException(dataContract.XmlName.Name, dataContract.XmlName.Namespace, SR.Format(SR.BaseTypeNotISerializable, baseTypeName.Name, baseTypeName.Namespace)); - if (!IsISerializableDerived(typeName, rootSequence)) + if (!IsISerializableDerived(rootSequence)) ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.Format(SR.ISerializableDerivedContainsOneOrMoreItems)); } @@ -891,7 +891,7 @@ private static void CheckISerializableBase(XmlQualifiedName typeName, XmlSchemaS ThrowISerializableTypeCannotBeImportedException(typeName.Name, typeName.Namespace, SR.Format(SR.ISerializableMustRefFactoryTypeAttribute, factoryTypeAttributeRefName.Name, factoryTypeAttributeRefName.Namespace)); } - private static bool IsISerializableDerived(XmlQualifiedName typeName, XmlSchemaSequence? rootSequence) + private static bool IsISerializableDerived(XmlSchemaSequence? rootSequence) { return (rootSequence == null || rootSequence.Items == null || rootSequence.Items.Count == 0); } @@ -1048,7 +1048,7 @@ internal static XmlQualifiedName ImportActualType(XmlSchemaAnnotation? annotatio [RequiresDynamicCode(DataContract.SerializerAOTWarning)] [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private CollectionDataContract ImportCollection(XmlQualifiedName typeName, XmlSchemaSequence rootSequence, XmlSchemaObjectCollection attributes, XmlSchemaAnnotation? annotation, bool isReference) + private CollectionDataContract ImportCollection(XmlQualifiedName typeName, XmlSchemaSequence rootSequence, XmlSchemaAnnotation? annotation, bool isReference) { CollectionDataContract dataContract = new CollectionDataContract(Globals.TypeOfSchemaDefinedType, CollectionKind.Array); dataContract.XmlName = typeName; @@ -1338,7 +1338,7 @@ private GenericInfo ImportGenericInfo(XmlElement typeElement, XmlSchemaType type Collection knownTypes = new Collection(); DataContractSurrogateCaller.GetKnownCustomDataTypes(_dataContractSet.SerializationExtendedSurrogateProvider, knownTypes); DataContractSerializer serializer = new DataContractSerializer(Globals.TypeOfObject, name, ns, knownTypes, - int.MaxValue, false /*ignoreExtensionDataObject*/, true /*preserveObjectReferences*/); + false /*ignoreExtensionDataObject*/, true /*preserveObjectReferences*/); return serializer.ReadObject(new XmlNodeReader(typeElement)); } return null; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlDataContract.cs index 918002ed84ed4..85b6df82804e7 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlDataContract.cs @@ -290,7 +290,7 @@ internal CreateXmlSerializableDelegate GenerateCreateXmlSerializableDelegate() } if (type.IsValueType) { - System.Reflection.Emit.LocalBuilder local = ilg.DeclareLocal(type, type.Name + "Value"); + System.Reflection.Emit.LocalBuilder local = ilg.DeclareLocal(type); ilg.Ldloca(local); ilg.InitObj(type); ilg.Ldloc(local); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs index 31b6b88fe23a2..028239874b8ff 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs @@ -110,7 +110,7 @@ public XmlFormatClassReaderDelegate GenerateClassReader(ClassDataContract classC LocalBuilder? objectId = null; if (HasFactoryMethod(classContract)) { - objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); + objectId = _ilg.DeclareLocal(Globals.TypeOfString); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod); _ilg.Stloc(objectId); } @@ -257,7 +257,7 @@ private void CreateObject(ClassDataContract classContract) if (type.IsValueType && !classContract.IsNonAttributedType) type = Globals.TypeOfValueType; - _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); + _objectLocal = _ilg.DeclareLocal(type); if (classContract.UnderlyingType == Globals.TypeOfDBNull) { @@ -350,7 +350,7 @@ private void ReadClass(ClassDataContract classContract) { if (classContract.HasExtensionData) { - LocalBuilder extensionDataLocal = _ilg.DeclareLocal(Globals.TypeOfExtensionDataObject, "extensionData"); + LocalBuilder extensionDataLocal = _ilg.DeclareLocal(Globals.TypeOfExtensionDataObject); _ilg.New(XmlFormatGeneratorStatics.ExtensionDataObjectCtor); _ilg.Store(extensionDataLocal); ReadMembers(classContract, extensionDataLocal); @@ -377,12 +377,12 @@ private void ReadMembers(ClassDataContract classContract, LocalBuilder? extensio int memberCount = classContract.MemberNames!.Length; _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, memberCount); - LocalBuilder memberIndexLocal = _ilg.DeclareLocal(Globals.TypeOfInt, "memberIndex", -1); + LocalBuilder memberIndexLocal = _ilg.DeclareLocal(Globals.TypeOfInt, -1); int firstRequiredMember; bool[] requiredMembers = GetRequiredMembers(classContract, out firstRequiredMember); bool hasRequiredMembers = (firstRequiredMember < memberCount); - LocalBuilder? requiredIndexLocal = hasRequiredMembers ? _ilg.DeclareLocal(Globals.TypeOfInt, "requiredIndex", firstRequiredMember) : null; + LocalBuilder? requiredIndexLocal = hasRequiredMembers ? _ilg.DeclareLocal(Globals.TypeOfInt, firstRequiredMember) : null; object forReadElements = _ilg.For(null, null, null); _ilg.Call(null, XmlFormatGeneratorStatics.MoveToNextElementMethod, _xmlReaderArg); @@ -424,7 +424,7 @@ private int ReadMembers(ClassDataContract classContract, bool[] requiredMembers, { DataMember dataMember = classContract.Members[i]; Type memberType = dataMember.MemberType; - _ilg.Case(memberLabels[memberCount], dataMember.Name); + _ilg.Case(memberLabels[memberCount]); if (dataMember.IsRequired) { int nextRequiredIndex = memberCount + 1; @@ -440,7 +440,7 @@ private int ReadMembers(ClassDataContract classContract, bool[] requiredMembers, { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(dataMember.MemberInfo); - value = _ilg.DeclareLocal(memberType, dataMember.Name + "Value"); + value = _ilg.DeclareLocal(memberType); _ilg.Stloc(value); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.StoreCollectionMemberInfoMethod, value); ReadValue(memberType, dataMember.Name, classContract.XmlName.Namespace); @@ -503,7 +503,7 @@ private void ReadISerializable(ClassDataContract classContract) [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private LocalBuilder ReadValue(Type type, string name, string ns) { - LocalBuilder value = _ilg.DeclareLocal(type, "valueRead"); + LocalBuilder value = _ilg.DeclareLocal(type); LocalBuilder? nullableValue = null; int nullables = 0; while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) @@ -515,7 +515,7 @@ private LocalBuilder ReadValue(Type type, string name, string ns) PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) { - LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); + LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadAttributesMethod, _xmlReaderArg); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadIfNullOrRefMethod, _xmlReaderArg, type, DataContract.IsTypeSerializable(type)); _ilg.Stloc(objectId); @@ -549,7 +549,7 @@ private LocalBuilder ReadValue(Type type, string name, string ns) if (nullables != 0) { nullableValue = value; - value = _ilg.DeclareLocal(type, "innerValueRead"); + value = _ilg.DeclareLocal(type); } if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) @@ -664,7 +664,7 @@ private void ReadCollection(CollectionDataContract collectionContract) string itemName = collectionContract.ItemName; string itemNs = collectionContract.XmlName.Namespace; - _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); + _objectLocal = _ilg.DeclareLocal(type); if (!isArray) { if (type.IsValueType) @@ -680,16 +680,16 @@ private void ReadCollection(CollectionDataContract collectionContract) } } - LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt, "arraySize"); + LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetArraySizeMethod); _ilg.Stloc(size); - LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); + LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.GetObjectIdMethod); _ilg.Stloc(objectId); bool canReadPrimitiveArray = false; - if (isArray && TryReadPrimitiveArray(type, itemType, size)) + if (isArray && TryReadPrimitiveArray(itemType, size)) { canReadPrimitiveArray = true; _ilg.IfNot(); @@ -700,11 +700,11 @@ private void ReadCollection(CollectionDataContract collectionContract) LocalBuilder? growingCollection = null; if (isArray) { - growingCollection = _ilg.DeclareLocal(type, "growingCollection"); + growingCollection = _ilg.DeclareLocal(type); _ilg.NewArray(itemType, 32); _ilg.Stloc(growingCollection); } - LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); + LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt); object forLoop = _ilg.For(i, 0, int.MaxValue); IsStartElement(_memberNamesArg, _memberNamespacesArg); _ilg.If(); @@ -746,7 +746,7 @@ private void ReadCollection(CollectionDataContract collectionContract) _ilg.Stloc(_objectLocal); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal); } - LocalBuilder j = _ilg.DeclareLocal(Globals.TypeOfInt, "j"); + LocalBuilder j = _ilg.DeclareLocal(Globals.TypeOfInt); _ilg.For(j, 0, size); IsStartElement(_memberNamesArg, _memberNamespacesArg); _ilg.If(); @@ -780,7 +780,7 @@ private void ReadGetOnlyCollection(CollectionDataContract collectionContract) string itemName = collectionContract.ItemName; string itemNs = collectionContract.XmlName.Namespace; - _objectLocal = _ilg.DeclareLocal(type, "objectDeserialized"); + _objectLocal = _ilg.DeclareLocal(type); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetCollectionMemberMethod); _ilg.ConvertValue(Globals.TypeOfObject, type); @@ -793,7 +793,7 @@ private void ReadGetOnlyCollection(CollectionDataContract collectionContract) _ilg.Call(null, XmlFormatGeneratorStatics.ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod, type); _ilg.Else(); - LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt, "arraySize"); + LocalBuilder size = _ilg.DeclareLocal(Globals.TypeOfInt); if (isArray) { _ilg.Load(_objectLocal); @@ -803,7 +803,7 @@ private void ReadGetOnlyCollection(CollectionDataContract collectionContract) _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal); - LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); + LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt); object forLoop = _ilg.For(i, 0, int.MaxValue); IsStartElement(_memberNamesArg, _memberNamespacesArg); _ilg.If(); @@ -836,7 +836,7 @@ private void ReadGetOnlyCollection(CollectionDataContract collectionContract) [RequiresDynamicCode(DataContract.SerializerAOTWarning)] [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private bool TryReadPrimitiveArray(Type type, Type itemType, LocalBuilder size) + private bool TryReadPrimitiveArray(Type itemType, LocalBuilder size) { Debug.Assert(_objectLocal != null); @@ -892,7 +892,7 @@ private LocalBuilder ReadCollectionItem(CollectionDataContract collectionContrac if (collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary) { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ResetAttributesMethod); - LocalBuilder value = _ilg.DeclareLocal(itemType, "valueRead"); + LocalBuilder value = _ilg.DeclareLocal(itemType); _ilg.Load(_collectionContractArg); _ilg.Call(XmlFormatGeneratorStatics.GetItemContractMethod); _ilg.Load(_xmlReaderArg); @@ -923,8 +923,8 @@ private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, C } DataMember keyMember = keyValuePairContract.Members![0]; DataMember valueMember = keyValuePairContract.Members[1]; - LocalBuilder pairKey = _ilg.DeclareLocal(keyMember.MemberType, keyMember.Name); - LocalBuilder pairValue = _ilg.DeclareLocal(valueMember.MemberType, valueMember.Name); + LocalBuilder pairKey = _ilg.DeclareLocal(keyMember.MemberType); + LocalBuilder pairValue = _ilg.DeclareLocal(valueMember.MemberType); _ilg.LoadAddress(value); _ilg.LoadMember(keyMember.MemberInfo); _ilg.Stloc(pairKey); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs index d6e595dce5846..fc2f0b7fe6852 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs @@ -99,7 +99,7 @@ internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract clas InitArgs(classContract.UnderlyingType); if (classContract.IsReadOnlyContract) { - ThrowIfCannotSerializeReadOnlyTypes(classContract); + ThrowIfCannotSerializeReadOnlyTypes(); } WriteClass(classContract); return (XmlFormatClassWriterDelegate)_ilg.EndMethod(); @@ -143,7 +143,7 @@ internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDa InitArgs(collectionContract.UnderlyingType); if (collectionContract.IsReadOnlyContract) { - ThrowIfCannotSerializeReadOnlyTypes(collectionContract); + ThrowIfCannotSerializeReadOnlyCollectionTypes(); } WriteCollection(collectionContract); return (XmlFormatCollectionWriterDelegate)_ilg.EndMethod(); @@ -157,7 +157,7 @@ private void InitArgs(Type objType) _contextArg = _ilg.GetArg(2); _dataContractArg = _ilg.GetArg(3); - _objectLocal = _ilg.DeclareLocal(objType, "objSerialized"); + _objectLocal = _ilg.DeclareLocal(objType); ArgBuilder objectArg = _ilg.GetArg(1); _ilg.Load(objectArg); @@ -182,12 +182,12 @@ private void InitArgs(Type objType) _ilg.Stloc(_objectLocal); } - private void ThrowIfCannotSerializeReadOnlyTypes(ClassDataContract classContract) + private void ThrowIfCannotSerializeReadOnlyTypes() { ThrowIfCannotSerializeReadOnlyTypes(XmlFormatGeneratorStatics.ClassSerializationExceptionMessageProperty); } - private void ThrowIfCannotSerializeReadOnlyTypes(CollectionDataContract classContract) + private void ThrowIfCannotSerializeReadOnlyCollectionTypes() { ThrowIfCannotSerializeReadOnlyTypes(XmlFormatGeneratorStatics.CollectionSerializationExceptionMessageProperty); } @@ -244,13 +244,13 @@ private void WriteClass(ClassDataContract classContract) { if (classContract.ContractNamespaces!.Length > 1) { - _contractNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "contractNamespaces"); + _contractNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[])); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.ContractNamespacesField); _ilg.Store(_contractNamespacesLocal); } - _memberNamesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "memberNames"); + _memberNamesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[])); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.MemberNamesField); _ilg.Store(_memberNamesLocal); @@ -259,7 +259,7 @@ private void WriteClass(ClassDataContract classContract) { if (classContract.ChildElementNamespaces[i] != null) { - _childElementNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "childElementNamespaces"); + _childElementNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[])); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.ChildElementNamespacesProperty); _ilg.Store(_childElementNamespacesLocal); @@ -268,7 +268,7 @@ private void WriteClass(ClassDataContract classContract) if (classContract.HasExtensionData) { - LocalBuilder extensionDataLocal = _ilg.DeclareLocal(Globals.TypeOfExtensionDataObject, "extensionData"); + LocalBuilder extensionDataLocal = _ilg.DeclareLocal(Globals.TypeOfExtensionDataObject); _ilg.Load(_objectLocal); _ilg.ConvertValue(_objectLocal.LocalType, Globals.TypeOfIExtensibleDataObject); _ilg.LoadMember(XmlFormatGeneratorStatics.ExtensionDataProperty); @@ -291,7 +291,7 @@ private int WriteMembers(ClassDataContract classContract, LocalBuilder? extensio int memberCount = (classContract.BaseClassContract == null) ? 0 : WriteMembers(classContract.BaseClassContract, extensionDataLocal, derivedMostClassContract); - LocalBuilder namespaceLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString), "ns"); + LocalBuilder namespaceLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString)); if (_contractNamespacesLocal == null) { _ilg.Load(_dataContractArg); @@ -364,7 +364,7 @@ private LocalBuilder LoadMemberValue(DataMember member) { _ilg.LoadAddress(_objectLocal); _ilg.LoadMember(member.MemberInfo); - LocalBuilder memberValue = _ilg.DeclareLocal(member.MemberType, member.Name + "Value"); + LocalBuilder memberValue = _ilg.DeclareLocal(member.MemberType); _ilg.Stloc(memberValue); return memberValue; } @@ -373,12 +373,12 @@ private LocalBuilder LoadMemberValue(DataMember member) [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] private void WriteCollection(CollectionDataContract collectionContract) { - LocalBuilder itemNamespace = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemNamespace"); + LocalBuilder itemNamespace = _ilg.DeclareLocal(typeof(XmlDictionaryString)); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.NamespaceProperty); _ilg.Store(itemNamespace); - LocalBuilder itemName = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemName"); + LocalBuilder itemName = _ilg.DeclareLocal(typeof(XmlDictionaryString)); _ilg.Load(_dataContractArg); _ilg.LoadMember(XmlFormatGeneratorStatics.CollectionItemNameProperty); _ilg.Store(itemName); @@ -394,7 +394,7 @@ private void WriteCollection(CollectionDataContract collectionContract) if (collectionContract.Kind == CollectionKind.Array) { Type itemType = collectionContract.ItemType; - LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i"); + LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementArrayCountMethod, _xmlWriterArg, _objectLocal); @@ -405,7 +405,7 @@ private void WriteCollection(CollectionDataContract collectionContract) { WriteStartElement(itemType, collectionContract.Namespace, itemNamespace, itemName, 0 /*nameIndex*/); _ilg.LoadArrayElement(_objectLocal, i); - LocalBuilder memberValue = _ilg.DeclareLocal(itemType, "memberValue"); + LocalBuilder memberValue = _ilg.DeclareLocal(itemType); _ilg.Stloc(memberValue); WriteValue(memberValue, false /*writeXsiType*/); WriteEndElement(); @@ -490,9 +490,9 @@ private void WriteCollection(CollectionDataContract collectionContract) } } Type elementType = getCurrentMethod.ReturnType; - LocalBuilder currentValue = _ilg.DeclareLocal(elementType, "currentValue"); + LocalBuilder currentValue = _ilg.DeclareLocal(elementType); - LocalBuilder enumerator = _ilg.DeclareLocal(enumeratorType, "enumerator"); + LocalBuilder enumerator = _ilg.DeclareLocal(enumeratorType); _ilg.Call(_objectLocal, collectionContract.GetEnumeratorMethod); if (isDictionary) { @@ -508,7 +508,7 @@ private void WriteCollection(CollectionDataContract collectionContract) } _ilg.Stloc(enumerator); - _ilg.ForEach(currentValue, elementType, enumeratorType, enumerator, getCurrentMethod); + _ilg.ForEach(currentValue, elementType, enumerator, getCurrentMethod); if (incrementCollectionCountMethod == null) { _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1); @@ -642,7 +642,7 @@ private void WriteValue(LocalBuilder memberValue, bool writeXsiType) _ilg.Load(memberType); _ilg.Call(XmlFormatGeneratorStatics.BoxPointer); memberType = Globals.TypeOfReflectionPointer; - memberValue = _ilg.DeclareLocal(memberType, "memberValueRefPointer"); + memberValue = _ilg.DeclareLocal(memberType); _ilg.Store(memberValue); } bool isNullableOfT = (memberType.IsGenericType && @@ -691,7 +691,7 @@ private void WriteValue(LocalBuilder memberValue, bool writeXsiType) { _ilg.Load(memberValue); _ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject); - memberValue = _ilg.DeclareLocal(Globals.TypeOfObject, "unwrappedMemberValue"); + memberValue = _ilg.DeclareLocal(Globals.TypeOfObject); memberType = memberValue.LocalType; _ilg.Stloc(memberValue); _ilg.If(memberValue, Cmp.EqualTo, null); @@ -714,7 +714,7 @@ private void InternalSerialize(MethodInfo methodInfo, LocalBuilder memberValue, _ilg.Load(_xmlWriterArg); _ilg.Load(memberValue); _ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject); - LocalBuilder typeHandleValue = _ilg.DeclareLocal(typeof(RuntimeTypeHandle), "typeHandleValue"); + LocalBuilder typeHandleValue = _ilg.DeclareLocal(typeof(RuntimeTypeHandle)); _ilg.Call(null, typeof(Type).GetMethod("GetTypeHandle")!, memberValue); _ilg.Stloc(typeHandleValue); _ilg.LoadAddress(typeHandleValue); @@ -744,7 +744,7 @@ private LocalBuilder UnwrapNullableObject(LocalBuilder memberValue)// Leaves !Ha _ilg.Call(XmlFormatGeneratorStatics.GetNullableValueMethod.MakeGenericMethod(innerType)); memberType = innerType; } - memberValue = _ilg.DeclareLocal(memberType, "nullableUnwrappedMemberValue"); + memberValue = _ilg.DeclareLocal(memberType); _ilg.Stloc(memberValue); _ilg.Load(false); //isNull _ilg.Br(end); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs index 5c0407c8399ea..61a3c5f53847a 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs @@ -110,7 +110,7 @@ internal virtual DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type } else { - return DataContract.GetDataContract(typeHandle, type); + return DataContract.GetDataContract(typeHandle); } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs index 24d1a94287e2e..385307dc237cd 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs @@ -110,7 +110,7 @@ internal XmlObjectSerializerReadContext(DataContractSerializer serializer, DataC [RequiresDynamicCode(DataContract.SerializerAOTWarning)] [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - protected bool TryHandleNullOrRef(XmlReaderDelegator reader, Type declaredType, string? name, string? ns, ref object? retObj) + protected bool TryHandleNullOrRef(XmlReaderDelegator reader, string? name, string? ns, Type declaredType, ref object? retObj) { ReadAttributes(reader); @@ -140,7 +140,7 @@ protected bool TryHandleNullOrRef(XmlReaderDelegator reader, Type declaredType, protected object? InternalDeserialize(XmlReaderDelegator reader, string? name, string? ns, Type declaredType, ref DataContract dataContract) { object? retObj = null; - if (TryHandleNullOrRef(reader, dataContract.UnderlyingType, name, ns, ref retObj)) + if (TryHandleNullOrRef(reader, name, ns, dataContract.UnderlyingType, ref retObj)) return retObj; bool knownTypesAddedInCurrentScope = false; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContextComplex.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContextComplex.cs index 000639ef07fae..1f3bbe4f0e45c 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContextComplex.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContextComplex.cs @@ -146,7 +146,7 @@ internal override void InternalSerialize(XmlWriterDelegator xmlWriter, object ob } else { - InternalSerializeWithSurrogate(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeID, declaredTypeHandle); + InternalSerializeWithSurrogate(xmlWriter, obj, isDeclaredType, writeXsiType, declaredTypeHandle); } } @@ -218,7 +218,7 @@ internal override Type GetSurrogatedType(Type type) [RequiresDynamicCode(DataContract.SerializerAOTWarning)] [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private void InternalSerializeWithSurrogate(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle) + private void InternalSerializeWithSurrogate(XmlWriterDelegator xmlWriter, object obj, bool isDeclaredType, bool writeXsiType, RuntimeTypeHandle declaredTypeHandle) { RuntimeTypeHandle objTypeHandle = isDeclaredType ? declaredTypeHandle : obj.GetType().TypeHandle; object oldObj = obj; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs index e0be3dee36dfe..784033b7a8b91 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs @@ -530,7 +530,7 @@ private void StartElement(ref string? prefix, string localName, string? ns, XmlD element.LocalName = localName; } - private void PreStartElementAsyncCheck(string? prefix, string localName, string? ns, XmlDictionaryString? xNs) + private void PreStartElementAsyncCheck(string localName) { if (IsClosed) ThrowClosed(); @@ -590,7 +590,7 @@ public override void WriteStartElement(string? prefix, string localName, string? public override Task WriteStartElementAsync(string? prefix, string localName, string? namespaceUri) { - PreStartElementAsyncCheck(prefix, localName, namespaceUri, null); + PreStartElementAsyncCheck(localName); return StartElementAndWriteStartElementAsync(prefix, localName, namespaceUri); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs index 4594d534ffe93..e6602e6b69e63 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs @@ -52,7 +52,7 @@ public void SetInput(byte[] buffer, int offset, int count, throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative)); if (count > buffer.Length - offset) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset))); - MoveToInitial(quotas, session, onClose); + MoveToInitial(quotas, onClose); BufferReader.SetBuffer(buffer, offset, count, dictionary, session); _buffered = true; } @@ -65,12 +65,12 @@ public void SetInput(Stream stream, { ArgumentNullException.ThrowIfNull(stream); - MoveToInitial(quotas, session, onClose); + MoveToInitial(quotas, onClose); BufferReader.SetBuffer(stream, dictionary, session); _buffered = false; } - private void MoveToInitial(XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession? session, OnXmlDictionaryReaderClose? onClose) + private void MoveToInitial(XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { MoveToInitial(quotas); _maxBytesPerRead = quotas.MaxBytesPerRead; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs index 65b0d12bae450..cd2975c3f2c9a 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs @@ -184,7 +184,7 @@ public override void WriteStartElement(string? prefix, XmlDictionaryString local if (string.IsNullOrEmpty(prefix)) { WriteNode(XmlBinaryNodeType.ShortDictionaryElement); - WriteDictionaryString(localName, key); + WriteDictionaryString(key); } else { @@ -193,13 +193,13 @@ public override void WriteStartElement(string? prefix, XmlDictionaryString local if (prefix.Length == 1 && char.IsAsciiLetterLower(ch)) { WritePrefixNode(XmlBinaryNodeType.PrefixDictionaryElementA, ch - 'a'); - WriteDictionaryString(localName, key); + WriteDictionaryString(key); } else { WriteNode(XmlBinaryNodeType.DictionaryElement); WriteName(prefix); - WriteDictionaryString(localName, key); + WriteDictionaryString(key); } } } @@ -272,7 +272,7 @@ public override void WriteStartAttribute(string prefix, XmlDictionaryString loca if (prefix.Length == 0) { WriteNode(XmlBinaryNodeType.ShortDictionaryAttribute); - WriteDictionaryString(localName, key); + WriteDictionaryString(key); } else { @@ -280,13 +280,13 @@ public override void WriteStartAttribute(string prefix, XmlDictionaryString loca if (prefix.Length == 1 && char.IsAsciiLetterLower(ch)) { WritePrefixNode(XmlBinaryNodeType.PrefixDictionaryAttributeA, ch - 'a'); - WriteDictionaryString(localName, key); + WriteDictionaryString(key); } else { WriteNode(XmlBinaryNodeType.DictionaryAttribute); WriteName(prefix); - WriteDictionaryString(localName, key); + WriteDictionaryString(key); } } _inAttribute = true; @@ -331,13 +331,13 @@ public override void WriteXmlnsAttribute(string? prefix, XmlDictionaryString ns) if (string.IsNullOrEmpty(prefix)) { WriteNode(XmlBinaryNodeType.ShortDictionaryXmlnsAttribute); - WriteDictionaryString(ns, key); + WriteDictionaryString(key); } else { WriteNode(XmlBinaryNodeType.DictionaryXmlnsAttribute); WriteName(prefix); - WriteDictionaryString(ns, key); + WriteDictionaryString(key); } } } @@ -370,7 +370,7 @@ private bool TryGetKey(XmlDictionaryString s, out int key) return true; } - private void WriteDictionaryString(XmlDictionaryString s, int key) + private void WriteDictionaryString(int key) { WriteMultiByteInt32(key); } @@ -598,7 +598,7 @@ public override void WriteText(XmlDictionaryString value) else { WriteTextNode(XmlBinaryNodeType.DictionaryText); - WriteDictionaryString(value, key); + WriteDictionaryString(key); } } } @@ -1059,7 +1059,7 @@ public override void WriteQualifiedName(string prefix, XmlDictionaryString local { WriteTextNode(XmlBinaryNodeType.QNameDictionaryText); WriteByte((byte)(ch - 'a')); - WriteDictionaryString(localName, key); + WriteDictionaryString(key); } else { diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs index 113f346fb80be..69bca92f5e904 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs @@ -847,7 +847,7 @@ internal void ReadContentFrom(XmlReader r, LoadOptions o) if (r.ReadState != ReadState.Interactive) throw new InvalidOperationException(SR.InvalidOperation_ExpectedInteractive); ContentReader cr = new ContentReader(this, r, o); - while (cr.ReadContentFrom(this, r, o) && r.Read()) ; + while (cr.ReadContentFromContainer(this, r) && r.Read()) ; } internal async Task ReadContentFromAsync(XmlReader r, CancellationToken cancellationToken) @@ -876,7 +876,7 @@ internal async Task ReadContentFromAsync(XmlReader r, LoadOptions o, Cancellatio { cancellationToken.ThrowIfCancellationRequested(); } - while (await cr.ReadContentFromAsync(this, r, o).ConfigureAwait(false) && await r.ReadAsync().ConfigureAwait(false)); + while (await cr.ReadContentFromContainerAsync(this, r).ConfigureAwait(false) && await r.ReadAsync().ConfigureAwait(false)); } private sealed class ContentReader @@ -1009,7 +1009,7 @@ public async ValueTask ReadContentFromAsync(XContainer rootContainer, XmlR return true; } - public bool ReadContentFrom(XContainer rootContainer, XmlReader r, LoadOptions o) + public bool ReadContentFromContainer(XContainer rootContainer, XmlReader r) { XNode? newNode = null; string baseUri = r.BaseURI; @@ -1123,7 +1123,7 @@ public bool ReadContentFrom(XContainer rootContainer, XmlReader r, LoadOptions o return true; } - public async ValueTask ReadContentFromAsync(XContainer rootContainer, XmlReader r, LoadOptions o) + public async ValueTask ReadContentFromContainerAsync(XContainer rootContainer, XmlReader r) { XNode? newNode = null; string baseUri = r.BaseURI!; diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XElement.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XElement.cs index a97dfcc51277a..77a11dfd63d52 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XElement.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XElement.cs @@ -144,7 +144,7 @@ internal XElement(XmlReader r) { } - private XElement(AsyncConstructionSentry s) + private XElement(AsyncConstructionSentry _) { // Dummy ctor used to avoid public default ctor. This is used // by async methods meant to perform the same operations as diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XLinq.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XLinq.cs index 84f4af1d57b76..a5b7cc8c41612 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XLinq.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XLinq.cs @@ -400,6 +400,7 @@ private async Task WriteStartElementAsync(XElement e, CancellationToken cancella ns = a.Name.Namespace; string localName = a.Name.LocalName; string namespaceName = ns.NamespaceName; + cancellationToken.ThrowIfCancellationRequested(); await _writer.WriteAttributeStringAsync(GetPrefixOfNamespace(ns, false), localName, namespaceName.Length == 0 && localName == "xmlns" ? XNamespace.xmlnsPrefixNamespace : namespaceName, a.Value).ConfigureAwait(false); } while (a != e.lastAttr); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs index 54ab4cd1a31a8..c1707fd21a36c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs @@ -4557,7 +4557,7 @@ private void AddDefaultAttributesAndNormalize() foreach (IDtdDefaultAttributeInfo defaultAttributeInfo in defaultAttributes) { - if (AddDefaultAttributeDtd(defaultAttributeInfo, true, nameSortedAttributes)) + if (AddDefaultAttributeDtd(defaultAttributeInfo, nameSortedAttributes)) { if (DtdValidation && _standalone && defaultAttributeInfo.IsDeclaredInExternal) { @@ -9239,7 +9239,7 @@ internal ConformanceLevel V1ComformanceLevel } } - private bool AddDefaultAttributeDtd(IDtdDefaultAttributeInfo defAttrInfo, bool definedInDtd, NodeData[]? nameSortedNodeData) + private bool AddDefaultAttributeDtd(IDtdDefaultAttributeInfo defAttrInfo, NodeData[]? nameSortedNodeData) { if (defAttrInfo.Prefix.Length > 0) { @@ -9786,6 +9786,8 @@ internal static void BlockCopy(byte[] src, int srcOffset, byte[] dst, int dstOff Buffer.BlockCopy(src, srcOffset, dst, dstOffset, count); } +#pragma warning disable IDE0060 // https://github.com/dotnet/roslyn-analyzers/issues/6177 static partial void ConvertAbsoluteUnixPathToAbsoluteUri([NotNullIfNotNull(nameof(url))] ref string? url, XmlResolver? resolver); +#pragma warning restore IDE0060 } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs index 21307b0cad714..ca72311182e94 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs @@ -3211,7 +3211,7 @@ private enum ParseTextFunction //To avoid stackoverflow like ParseText->ParseEntity->ParText->..., use a loop and parsing function to implement such call. private ValueTask<(int, int, int, bool)> ParseTextAsync(int outOrChars) { - Task<(int, int, int, bool)> task = ParseTextAsync(outOrChars, _ps.chars, _ps.charPos, 0, -1, outOrChars, (char)0); + Task<(int, int, int, bool)> task = ParseTextAsync(outOrChars, _ps.chars, _ps.charPos, 0, -1, outOrChars); while (true) { if (!task.IsSuccess()) @@ -3230,7 +3230,7 @@ private enum ParseTextFunction switch (_parseText_NextFunction) { case ParseTextFunction.ParseText: - task = ParseTextAsync(outOrChars, chars, pos, rcount, rpos, orChars, c); + task = ParseTextAsync(outOrChars, chars, pos, rcount, rpos, orChars); break; case ParseTextFunction.Entity: task = ParseTextAsync_ParseEntity(outOrChars, chars, pos, rcount, rpos, orChars, c); @@ -3266,7 +3266,7 @@ private enum ParseTextFunction switch (_parseText_NextFunction) { case ParseTextFunction.ParseText: - task = ParseTextAsync(outOrChars, chars, pos, rcount, rpos, orChars, c); + task = ParseTextAsync(outOrChars, chars, pos, rcount, rpos, orChars); break; case ParseTextFunction.Entity: task = ParseTextAsync_ParseEntity(outOrChars, chars, pos, rcount, rpos, orChars, c); @@ -3285,10 +3285,11 @@ private enum ParseTextFunction } } - private Task<(int, int, int, bool)> ParseTextAsync(int outOrChars, char[] chars, int pos, int rcount, int rpos, int orChars, char c) + private Task<(int, int, int, bool)> ParseTextAsync(int outOrChars, char[] chars, int pos, int rcount, int rpos, int orChars) { while (true) { + char c; // parse text content while (XmlCharType.IsTextChar(c = chars[pos])) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs index c251362175799..7893e4a88056d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs @@ -42,7 +42,7 @@ private XmlElementList(XmlNode parent) ~XmlElementList() { - Dispose(false); + Dispose(); } internal void ConcurrencyCheck(XmlNodeChangedEventArgs args) @@ -272,7 +272,7 @@ public override int Count public override IEnumerator GetEnumerator() { if (_empty) - return new XmlEmptyElementListEnumerator(this); + return new XmlEmptyElementListEnumerator(); return new XmlElementListEnumerator(this); } @@ -280,10 +280,10 @@ public override IEnumerator GetEnumerator() protected override void PrivateDisposeNodeList() { GC.SuppressFinalize(this); - Dispose(true); + Dispose(); } - private void Dispose(bool disposing) + private void Dispose() { if (_listener != null) { @@ -339,7 +339,7 @@ public object? Current internal sealed class XmlEmptyElementListEnumerator : IEnumerator { - public XmlEmptyElementListEnumerator(XmlElementList list) + public XmlEmptyElementListEnumerator() { } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntity.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntity.cs index 88a405193b022..a32299be61c55 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntity.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntity.cs @@ -14,7 +14,7 @@ public class XmlEntity : XmlNode private XmlLinkedNode? _lastChild; private bool _childrenFoliating; - internal XmlEntity(string name, string? strdata, string? publicId, string? systemId, string? notationName, XmlDocument doc) : base(doc) + internal XmlEntity(string name, string? publicId, string? systemId, string? notationName, XmlDocument doc) : base(doc) { _name = doc.NameTable.Add(name); _publicId = publicId; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs index 3b96851ef6b88..f139daac0eca9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs @@ -636,7 +636,7 @@ private void LoadDocumentType(IDtdInfo dtdInfo, XmlDocumentType dtNode) { foreach (SchemaEntity scEnt in schInfo.GeneralEntities.Values) { - XmlEntity ent = new XmlEntity(scEnt.Name.Name, scEnt.Text, scEnt.Pubid, scEnt.Url, scEnt.NData.IsEmpty ? null : scEnt.NData.Name, _doc); + XmlEntity ent = new XmlEntity(scEnt.Name.Name, scEnt.Pubid, scEnt.Url, scEnt.NData.IsEmpty ? null : scEnt.NData.Name, _doc); ent.SetBaseURI(scEnt.DeclaredURI); dtNode.Entities.SetNamedItem(ent); } @@ -646,7 +646,7 @@ private void LoadDocumentType(IDtdInfo dtdInfo, XmlDocumentType dtNode) { foreach (SchemaEntity scEnt in schInfo.ParameterEntities.Values) { - XmlEntity ent = new XmlEntity(scEnt.Name.Name, scEnt.Text, scEnt.Pubid, scEnt.Url, scEnt.NData.IsEmpty ? null : scEnt.NData.Name, _doc); + XmlEntity ent = new XmlEntity(scEnt.Name.Name, scEnt.Pubid, scEnt.Url, scEnt.NData.IsEmpty ? null : scEnt.NData.Name, _doc); ent.SetBaseURI(scEnt.DeclaredURI); dtNode.Entities.SetNamedItem(ent); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Ref.cs b/src/libraries/System.Private.Xml/src/System/Xml/Ref.cs index d5064eaab20be..95d470a61b6b0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Ref.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Ref.cs @@ -18,11 +18,5 @@ public static bool Equal(string? strA, string? strB) #endif return (object?)strA == (object?)strB; } - - // Prevent typos. If someone uses Ref.Equals instead of Ref.Equal, - // the program would not compile. - public static new void Equals(object objA, object objB) - { - } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs index 60dc7a394078b..00e56f9e32464 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs @@ -434,7 +434,7 @@ public SyntaxTreeNode? RightChild } //no recursive version of expand tree for Sequence and Choice node - protected void ExpandTreeNoRecursive(InteriorNode parent, SymbolsDictionary symbols, Positions positions) + protected void ExpandTreeNoRecursive(SymbolsDictionary symbols, Positions positions) { Stack nodeStack = new Stack(); InteriorNode this_ = this; @@ -560,7 +560,7 @@ public override bool IsNullable public override void ExpandTree(InteriorNode parent, SymbolsDictionary symbols, Positions positions) { - ExpandTreeNoRecursive(parent, symbols, positions); + ExpandTreeNoRecursive(symbols, positions); } #if DEBUG @@ -643,7 +643,7 @@ public override bool IsNullable public override void ExpandTree(InteriorNode parent, SymbolsDictionary symbols, Positions positions) { - ExpandTreeNoRecursive(parent, symbols, positions); + ExpandTreeNoRecursive(symbols, positions); } #if DEBUG @@ -1268,7 +1268,7 @@ public ContentValidator Finish(bool useDFA) if (_minMaxNodesCount > 0) { //If the tree has any terminal range nodes BitSet positionsWithRangeTerminals; - BitSet[] minMaxFollowPos = CalculateTotalFollowposForRangeNodes(firstpos, followpos, out positionsWithRangeTerminals); + BitSet[] minMaxFollowPos = CalculateTotalFollowposForRangeNodes(followpos, out positionsWithRangeTerminals); if (_enableUpaCheck) { @@ -1309,7 +1309,7 @@ public ContentValidator Finish(bool useDFA) } } - private BitSet[] CalculateTotalFollowposForRangeNodes(BitSet firstpos, BitSet[] followpos, out BitSet posWithRangeTerminals) + private BitSet[] CalculateTotalFollowposForRangeNodes(BitSet[] followpos, out BitSet posWithRangeTerminals) { int positionsCount = _positions!.Count; //terminals posWithRangeTerminals = new BitSet(positionsCount); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs index 8c691948625cb..9e9260d94a13f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs @@ -938,8 +938,7 @@ internal void InferElement(XmlSchemaElement xse, bool bCreatingNewType, XmlSchem } else { - bool bParticleChanged = false; - FindMatchingElement(bCreatingNewType || bCreatingNewSequence, _xtr, ct, ref lastUsedSeqItem, ref bParticleChanged, parentSchema, Maxoccursflag); + FindMatchingElement(bCreatingNewType || bCreatingNewSequence, _xtr, ct, ref lastUsedSeqItem, parentSchema, Maxoccursflag); } } else if (_xtr.NodeType == XmlNodeType.Text) @@ -1025,10 +1024,9 @@ private static XmlSchemaSimpleContentExtension CheckSimpleContentExtension(XmlSc /// text reader positioned to the current element /// complex type with Sequence or Choice Particle /// ordinal number in the sequence to indicate current sequence position - /// This indicates to the caller if Sequence was changed to Choice /// The parent schema. /// Whether set max occurs. - internal XmlSchemaElement FindMatchingElement(bool bCreatingNewType, XmlReader xtr, XmlSchemaComplexType ct, ref int lastUsedSeqItem, ref bool bParticleChanged, XmlSchema? parentSchema, bool setMaxoccurs) + internal XmlSchemaElement FindMatchingElement(bool bCreatingNewType, XmlReader xtr, XmlSchemaComplexType ct, ref int lastUsedSeqItem, XmlSchema? parentSchema, bool setMaxoccurs) { if (xtr.NamespaceURI == XmlSchema.Namespace) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs index a1f642b93d04f..71af70d587a6b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs @@ -869,7 +869,7 @@ private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, X else { CompileSimpleType(simpleRestriction.BaseType); - if (!XmlSchemaType.IsDerivedFromDatatype(simpleRestriction.BaseType.Datatype!, baseType.Datatype!, XmlSchemaDerivationMethod.None)) + if (!XmlSchemaType.IsDerivedFromDatatype(simpleRestriction.BaseType.Datatype!, baseType.Datatype!)) { SendValidationEvent(SR.Sch_DerivedNotFromBase, simpleRestriction); } @@ -1080,7 +1080,7 @@ private XmlSchemaParticle CanonicalizeParticle(XmlSchemaParticle? particle, bool } else if (particle is XmlSchemaGroupRef) { - return CanonicalizeGroupRef((XmlSchemaGroupRef)particle, root, substitution); + return CanonicalizeGroupRef((XmlSchemaGroupRef)particle, root); } else if (particle is XmlSchemaAll) { @@ -1123,7 +1123,7 @@ private XmlSchemaParticle CanonicalizeElement(XmlSchemaElement element, bool sub } } - private XmlSchemaParticle CanonicalizeGroupRef(XmlSchemaGroupRef groupRef, bool root, bool substitution) + private XmlSchemaParticle CanonicalizeGroupRef(XmlSchemaGroupRef groupRef, bool root) { XmlSchemaGroup? group; if (groupRef.Redefined != null) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs index f909fc346f1b8..02049223d0156 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs @@ -949,7 +949,7 @@ private void CompileSimpleContentRestriction(XmlSchemaComplexType complexType, X else { CompileSimpleType(simpleRestriction.BaseType); - if (!XmlSchemaType.IsDerivedFromDatatype(simpleRestriction.BaseType.Datatype!, baseType.Datatype!, XmlSchemaDerivationMethod.None)) + if (!XmlSchemaType.IsDerivedFromDatatype(simpleRestriction.BaseType.Datatype!, baseType.Datatype!)) { SendValidationEvent(SR.Sch_DerivedNotFromBase, simpleRestriction); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaType.cs index dca6879ac9157..e9cd767f2c43d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaType.cs @@ -327,7 +327,7 @@ public static bool IsDerivedFrom([NotNullWhen(true)] XmlSchemaType? derivedType, } - internal static bool IsDerivedFromDatatype(XmlSchemaDatatype derivedDataType, XmlSchemaDatatype baseDataType, XmlSchemaDerivationMethod except) + internal static bool IsDerivedFromDatatype(XmlSchemaDatatype derivedDataType, XmlSchemaDatatype baseDataType) { if (DatatypeImplementation.AnySimpleType.Datatype == baseDataType) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs index a9023e8b1097d..0ee0a68a5f249 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs @@ -66,7 +66,7 @@ internal TempAssembly(XmlMapping[] xmlMappings, Type?[] types, string? defaultNa { try { - _assembly = GenerateRefEmitAssembly(xmlMappings, types, defaultNamespace); + _assembly = GenerateRefEmitAssembly(xmlMappings, types); } // Only catch and handle known failures with RefEmit catch (CodeGeneratorConversionException) @@ -413,7 +413,7 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type?[ readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i])!; } - readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types); + readerCodeGen.GenerateEnd(); string baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes); var serializers = new Hashtable(); @@ -425,7 +425,7 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type?[ } } - readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types!, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); + readerCodeGen.GenerateSerializerContract(xmlMappings, types!, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); writer.Indent--; writer.WriteLine("}"); @@ -437,7 +437,7 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type?[ } [RequiresUnreferencedCode("calls GenerateElement")] - internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type?[] types, string? defaultNamespace) + internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type?[] types) { var mainType = (types.Length > 0) ? types[0] : null; Assembly? mainAssembly = mainType?.Assembly; @@ -509,7 +509,7 @@ internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type? { readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i])!; } - readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types!); + readerCodeGen.GenerateEnd(); string baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes); var serializers = new Dictionary(); @@ -520,7 +520,7 @@ internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type? serializers[xmlMappings[i].Key!] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); } } - readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types!, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); + readerCodeGen.GenerateSerializerContract(xmlMappings, types!, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); return writerType.Assembly; } @@ -613,7 +613,7 @@ internal static void VerifyLoadContext(Type? t, Assembly? assembly) { encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key!); reader = Contract.Reader; - reader.Init(xmlReader, events, encodingStyle, this); + reader.Init(xmlReader, events, encodingStyle); if (_methods![mapping.Key!].readMethod == null) { _readerMethods ??= Contract.ReadMethods; @@ -640,7 +640,7 @@ internal void InvokeWriter(XmlMapping mapping, XmlWriter xmlWriter, object? o, X { encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key!); writer = Contract.Writer; - writer.Init(xmlWriter, namespaces, encodingStyle, id, this); + writer.Init(xmlWriter, namespaces, encodingStyle, id); if (_methods![mapping.Key!].writeMethod == null) { _writerMethods ??= Contract.WriteMethods; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs index 1a09c21caf772..d6d93c540041d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs @@ -64,7 +64,7 @@ internal sealed class SchemaObjectCache internal StringCollection Warnings => _warnings ??= new StringCollection(); - internal XmlSchemaObject? AddItem(XmlSchemaObject? item, XmlQualifiedName? qname, XmlSchemas schemas) + internal XmlSchemaObject? AddItem(XmlSchemaObject? item, XmlQualifiedName? qname) { if (item == null) return null; @@ -114,7 +114,7 @@ internal bool Match(XmlSchemaObject o1, XmlSchemaObject o2, bool shareTypes) return false; if (shareTypes) - return CompositeHash(o1, hash1) == CompositeHash(o2, hash2); + return CompositeHash(o1) == CompositeHash(o2); return true; } @@ -136,7 +136,7 @@ private ArrayList GetDependencies(XmlSchemaObject o, ArrayList deps, Hashtable r return deps; } - private int CompositeHash(XmlSchemaObject o, int hash) + private int CompositeHash(XmlSchemaObject o) { ArrayList list = GetDependencies(o, new ArrayList(), new Hashtable()); double tmp = 0; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs index e3a3075f97ea0..a08aa058ec0e5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs @@ -37,7 +37,7 @@ internal sealed class ReflectionXmlSerializationReader : XmlSerializationReader public ReflectionXmlSerializationReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, string? encodingStyle) { - Init(xmlReader, events, encodingStyle, tempAssembly: null); + Init(xmlReader, events, encodingStyle); _mapping = mapping; } @@ -549,7 +549,7 @@ private static void ProcessUnknownNode(UnknownNodeAction action) } [RequiresUnreferencedCode(XmlSerializer.TrimSerializationWarning)] - private void WriteMembers(ref object? o, Member[] members, UnknownNodeAction elementElseAction, UnknownNodeAction elseAction, Member? anyElement, Member? anyText) + private void WriteMembers(Member[] members, UnknownNodeAction elementElseAction, UnknownNodeAction elseAction, Member? anyElement, Member? anyText) { Reader.MoveToContent(); @@ -731,7 +731,7 @@ private bool WriteMemberText(Member anyText) return false; } - private static bool IsSequence(Member[] members) + private static bool IsSequence() { // https://github.com/dotnet/runtime/issues/1402: // Currently the reflection based method treat this kind of type as normal types. @@ -743,7 +743,7 @@ private static bool IsSequence(Member[] members) private void WriteMemberElementsIf(Member[] expectedMembers, Member? anyElementMember, UnknownNodeAction elementElseAction, Fixup? fixup = null, CheckTypeSource? checkTypeSource = null) { bool checkType = checkTypeSource != null; - bool isSequence = IsSequence(expectedMembers); + bool isSequence = IsSequence(); if (isSequence) { // https://github.com/dotnet/runtime/issues/1402: @@ -819,7 +819,7 @@ private void WriteMemberElementsIf(Member[] expectedMembers, Member? anyElementM { string? ns = e!.Form == XmlSchemaForm.Qualified ? e.Namespace : string.Empty; bool isList = member!.Mapping.TypeDesc!.IsArrayLike && !member.Mapping.TypeDesc.IsArray; - WriteElement(e, member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite, isList && member.Mapping.TypeDesc.IsNullable, member.Mapping.ReadOnly, ns, member.FixupIndex, elementIndex, fixup, member); + WriteElement(e, isList && member.Mapping.TypeDesc.IsNullable, member.Mapping.ReadOnly, ns, member.FixupIndex, fixup, member); } } else @@ -835,7 +835,7 @@ private void WriteMemberElementsIf(Member[] expectedMembers, Member? anyElementM if (element.Any && element.Name.Length == 0) { string? ns = element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty; - WriteElement(element, anyElement.CheckSpecified == SpecifiedAccessor.ReadWrite, false, false, ns, fixup: fixup, member: member); + WriteElement(element, false, false, ns, fixup: fixup, member: member); break; } } @@ -849,16 +849,16 @@ private void WriteMemberElementsIf(Member[] expectedMembers, Member? anyElementM } [RequiresUnreferencedCode(XmlSerializer.TrimSerializationWarning)] - private object? WriteElement(ElementAccessor element, bool checkSpecified, bool checkForNull, bool readOnly, string? defaultNamespace, int fixupIndex = -1, int elementIndex = -1, Fixup? fixup = null, Member? member = null) + private object? WriteElement(ElementAccessor element, bool checkForNull, bool readOnly, string? defaultNamespace, int fixupIndex = -1, Fixup? fixup = null, Member? member = null) { object? value = null; if (element.Mapping is ArrayMapping arrayMapping) { - value = WriteArray(arrayMapping, readOnly, element.IsNullable, defaultNamespace, fixupIndex, fixup, member); + value = WriteArray(arrayMapping, readOnly, fixupIndex, fixup, member); } else if (element.Mapping is NullableMapping nullableMapping) { - value = WriteNullableMethod(nullableMapping, true, defaultNamespace); + value = WriteNullableMethod(nullableMapping, defaultNamespace); } else if (!element.Mapping!.IsSoap && (element.Mapping is PrimitiveMapping)) { @@ -978,7 +978,7 @@ private void WriteMemberElementsIf(Member[] expectedMembers, Member? anyElementM if (sm.DerivedMappings != null) { XmlQualifiedName? tser = GetXsiType(); - if (tser == null || QNameEqual(tser, sm.XsiType!.Name, sm.XsiType.Namespace, defaultNamespace)) + if (tser == null || QNameEqual(tser, sm.XsiType!.Name, defaultNamespace)) { } else @@ -1042,7 +1042,7 @@ private XmlSerializationReadCallback CreateXmlSerializationReadCallback(TypeMapp else if (mapping is NullableMapping nullableMapping) { [RequiresUnreferencedCode("calls WriteNullableMethod")] - object? Wrapper() => WriteNullableMethod(nullableMapping, false, null); + object? Wrapper() => WriteNullableMethod(nullableMapping, null); return Wrapper; } @@ -1088,7 +1088,7 @@ private static bool IsWildcard(SpecialMapping mapping) } [RequiresUnreferencedCode(XmlSerializer.TrimSerializationWarning)] - private object? WriteArray(ArrayMapping arrayMapping, bool readOnly, bool isNullable, string? defaultNamespace, int fixupIndex = -1, Fixup? fixup = null, Member? member = null) + private object? WriteArray(ArrayMapping arrayMapping, bool readOnly, int fixupIndex = -1, Fixup? fixup = null, Member? member = null) { object? o = null; if (arrayMapping.IsSoap) @@ -1249,7 +1249,7 @@ private object WritePrimitive(TypeMapping mapping, Func readFunc } [RequiresUnreferencedCode(XmlSerializer.TrimSerializationWarning)] - private object? WriteNullableMethod(NullableMapping nullableMapping, bool checkType, string? defaultNamespace) + private object? WriteNullableMethod(NullableMapping nullableMapping, string? defaultNamespace) { object? o = Activator.CreateInstance(nullableMapping.TypeDesc!.Type!); if (!ReadNull()) @@ -1259,7 +1259,7 @@ private object WritePrimitive(TypeMapping mapping, Func readFunc element.Any = false; element.IsNullable = nullableMapping.BaseMapping!.TypeDesc!.IsNullable; - o = WriteElement(element, false, false, false, defaultNamespace); + o = WriteElement(element, false, false, defaultNamespace); } return o; @@ -1282,8 +1282,8 @@ private object WriteEnumMethod(EnumMapping mapping, string source) { if (mapping.IsFlags) { - Hashtable table = WriteHashtable(mapping, mapping.TypeDesc!.Name); - return Enum.ToObject(mapping.TypeDesc.Type!, ToEnum(source, table, mapping.TypeDesc.Name)); + Hashtable table = WriteHashtable(mapping); + return Enum.ToObject(mapping.TypeDesc!.Type!, ToEnum(source, table, mapping.TypeDesc.Name)); } else { @@ -1299,7 +1299,7 @@ private object WriteEnumMethod(EnumMapping mapping, string source) } } - private static Hashtable WriteHashtable(EnumMapping mapping, string name) + private static Hashtable WriteHashtable(EnumMapping mapping) { var h = new Hashtable(); ConstantMapping[] constants = mapping.Constants!; @@ -1558,7 +1558,7 @@ void Wrapper(object? collection, object? collectionItems) } object? o = null; - if (xsiType == null || (!structMapping.TypeDesc.IsRoot && QNameEqual(xsiType, structMapping.TypeName, structMapping.Namespace, defaultNamespace))) + if (xsiType == null || (!structMapping.TypeDesc.IsRoot && QNameEqual(xsiType, structMapping.TypeName, defaultNamespace))) { if (structMapping.TypeDesc.IsRoot) { @@ -1569,7 +1569,7 @@ void Wrapper(object? collection, object? collectionItems) { return o; } - else if (structMapping.TypeDesc.IsRoot && WriteEnumAndArrayTypes(out o, structMapping, xsiType, defaultNamespace)) + else if (structMapping.TypeDesc.IsRoot && WriteEnumAndArrayTypes(out o, xsiType, defaultNamespace)) { return o; } @@ -1770,7 +1770,7 @@ void Wrapper(object elementNameObject) } Reader.ReadStartElement(); - bool IsSequenceAllMembers = IsSequence(allMembers); + bool IsSequenceAllMembers = IsSequence(); if (IsSequenceAllMembers) { // https://github.com/dotnet/runtime/issues/1402: @@ -1778,7 +1778,7 @@ void Wrapper(object elementNameObject) // But potentially we can do some optimization for types that have ordered properties. } - WriteMembers(ref o, allMembers, unknownNodeAction, unknownNodeAction, anyElementMember, anyTextMember); + WriteMembers(allMembers, unknownNodeAction, unknownNodeAction, anyElementMember, anyTextMember); foreach (Member member in allMembers) { @@ -1799,13 +1799,13 @@ void Wrapper(object elementNameObject) } [RequiresUnreferencedCode(XmlSerializer.TrimSerializationWarning)] - private bool WriteEnumAndArrayTypes(out object? o, StructMapping mapping, XmlQualifiedName xsiType, string? defaultNamespace) + private bool WriteEnumAndArrayTypes(out object? o, XmlQualifiedName xsiType, string? defaultNamespace) { foreach (var m in _mapping.Scope!.TypeMappings) { if (m is EnumMapping enumMapping) { - if (QNameEqual(xsiType, enumMapping.TypeName, enumMapping.Namespace, defaultNamespace)) + if (QNameEqual(xsiType, enumMapping.TypeName, defaultNamespace)) { Reader.ReadStartElement(); Func functor = (state) => @@ -1823,9 +1823,9 @@ private bool WriteEnumAndArrayTypes(out object? o, StructMapping mapping, XmlQua if (m is ArrayMapping arrayMapping) { - if (QNameEqual(xsiType, arrayMapping.TypeName, arrayMapping.Namespace, defaultNamespace)) + if (QNameEqual(xsiType, arrayMapping.TypeName, defaultNamespace)) { - o = WriteArray(arrayMapping, false, false, defaultNamespace); + o = WriteArray(arrayMapping, false); return true; } @@ -1842,7 +1842,7 @@ private bool WriteDerivedTypes(out object? o, StructMapping mapping, XmlQualifie { for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { - if (QNameEqual(xsiType, derived.TypeName, derived.Namespace, defaultNamespace)) + if (QNameEqual(xsiType, derived.TypeName, defaultNamespace)) { o = WriteStructMethod(derived, isNullable, checkType, defaultNamespace); return true; @@ -2045,7 +2045,7 @@ private static bool XmlNodeEqual(XmlReader source, string name, string? ns) return source.LocalName == name && string.Equals(source.NamespaceURI, ns); } - private static bool QNameEqual(XmlQualifiedName xsiType, string? name, string? ns, string? defaultNamespace) + private static bool QNameEqual(XmlQualifiedName xsiType, string? name, string? defaultNamespace) { return xsiType.Name == name && string.Equals(xsiType.Namespace, defaultNamespace); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs index 3fbfc2650b199..49ce530633c3e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs @@ -17,7 +17,7 @@ internal sealed class ReflectionXmlSerializationWriter : XmlSerializationWriter public ReflectionXmlSerializationWriter(XmlMapping xmlMapping, XmlWriter xmlWriter, XmlSerializerNamespaces namespaces, string? encodingStyle, string? id) { - Init(xmlWriter, namespaces, encodingStyle, id, null); + Init(xmlWriter, namespaces, encodingStyle, id); if (!xmlMapping.IsWriteable || !xmlMapping.GenerateSerializer) { @@ -125,7 +125,7 @@ private void WriteMember(object? o, object? choiceSource, ElementAccessor[] elem } else { - WriteElements(o, choiceSource, elements, text, choice, writeAccessors, memberTypeDesc.IsNullable); + WriteElements(o, elements, text, choice, writeAccessors, memberTypeDesc.IsNullable); } } @@ -150,11 +150,11 @@ private void WriteArray(object o, object? choiceSource, ElementAccessor[] elemen } } - WriteArrayItems(elements, text, choice, arrayTypeDesc, o); + WriteArrayItems(elements, text, choice, o); } [RequiresUnreferencedCode("calls WriteElements")] - private void WriteArrayItems(ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc? arrayTypeDesc, object o) + private void WriteArrayItems(ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, object o) { var arr = o as IList; @@ -163,7 +163,7 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor? text, Cho for (int i = 0; i < arr.Count; i++) { object? ai = arr[i]; - WriteElements(ai, null/*choiceName + "i"*/, elements, text, choice, true, true); + WriteElements(ai, elements, text, choice, true, true); } } else @@ -177,14 +177,14 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor? text, Cho while (e.MoveNext()) { object ai = e.Current; - WriteElements(ai, null/*choiceName + "i"*/, elements, text, choice, true, true); + WriteElements(ai, elements, text, choice, true, true); } } } } [RequiresUnreferencedCode("calls CreateUnknownTypeException")] - private void WriteElements(object? o, object? enumSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, bool writeAccessors, bool isNullable) + private void WriteElements(object? o, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, bool writeAccessors, bool isNullable) { if (elements.Length == 0 && text == null) return; @@ -291,7 +291,7 @@ private void WriteText(object o, TextAccessor text) } else { - if (!WritePrimitiveValue(primitiveMapping.TypeDesc!, o, false, out stringValue)) + if (!WritePrimitiveValue(primitiveMapping.TypeDesc!, o, out stringValue)) { Debug.Assert(o is byte[]); } @@ -376,7 +376,7 @@ private void WriteElement(object? o, ElementAccessor element, bool writeAccessor if (o != null) { WriteStartElement(name, ns, false); - WriteArrayItems(mapping.ElementsSortedByDerivation!, null, null, mapping.TypeDesc, o); + WriteArrayItems(mapping.ElementsSortedByDerivation!, null, null, o); WriteEndElement(); } } @@ -391,7 +391,7 @@ private void WriteElement(object? o, ElementAccessor element, bool writeAccessor } else { - WritePrimitive(WritePrimitiveMethodRequirement.WriteElementString, name, ns!, element.Default, o!, element.Mapping, false, true, element.IsNullable); + WritePrimitive(WritePrimitiveMethodRequirement.WriteElementString, name, ns!, element.Default, o!, element.Mapping, false); } } else if (element.Mapping is PrimitiveMapping) @@ -419,7 +419,7 @@ private void WriteElement(object? o, ElementAccessor element, bool writeAccessor WritePrimitive(element.IsNullable ? WritePrimitiveMethodRequirement.WriteNullableStringLiteral | suffixNullable | suffixRaw : WritePrimitiveMethodRequirement.WriteElementString | suffixRaw, - name, ns!, element.Default, o!, mapping, mapping.IsSoap, true, element.IsNullable); + name, ns!, element.Default, o!, mapping, mapping.IsSoap); } } else if (element.Mapping is StructMapping) @@ -487,7 +487,7 @@ void Wrapper(object o) private void WriteQualifiedNameElement(string name, string ns, object? defaultValue, XmlQualifiedName o, bool nullable, bool isSoap, PrimitiveMapping mapping) { bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc!.HasDefaultSupport; - if (hasDefault && IsDefaultValue(mapping, o, defaultValue!, nullable)) + if (hasDefault && IsDefaultValue(o, defaultValue!)) return; if (isSoap) @@ -537,7 +537,7 @@ private void WriteStructMethod(StructMapping mapping, string n, string? ns, obje if (mapping.TypeDesc.IsRoot) { - if (WriteEnumAndArrayTypes(mapping, o, n!, ns)) + if (WriteEnumAndArrayTypes(o, n!, ns)) { return; } @@ -670,7 +670,7 @@ private void WriteStructMethod(StructMapping mapping, string n, string? ns, obje } [RequiresUnreferencedCode("calls WriteMember")] - private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, string n, string? ns) + private bool WriteEnumAndArrayTypes(object o, string n, string? ns) { Type objType = o.GetType(); @@ -808,7 +808,7 @@ private void WriteMember(object? memberValue, AttributeAccessor attribute, TypeD } else { - if (!WritePrimitiveValue(arrayElementTypeDesc!, ai, true, out stringValue)) + if (!WritePrimitiveValue(arrayElementTypeDesc!, ai, out stringValue)) { Debug.Assert(ai is byte[]); } @@ -899,7 +899,7 @@ private void WriteAttribute(object memberValue, AttributeAccessor attribute, obj else { string? ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; - WritePrimitive(WritePrimitiveMethodRequirement.WriteAttribute, attribute.Name, ns, attribute.Default, memberValue, attribute.Mapping!, false, false, false); + WritePrimitive(WritePrimitiveMethodRequirement.WriteAttribute, attribute.Name, ns, attribute.Default, memberValue, attribute.Mapping!, false); } } @@ -937,7 +937,7 @@ private bool WriteDerivedTypes(StructMapping mapping, string n, string? ns, obje return false; } - private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, string? ns, object? defaultValue, object o, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable) + private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, string? ns, object? defaultValue, object o, TypeMapping mapping, bool writeXsiType) { TypeDesc typeDesc = mapping.TypeDesc!; bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc!.HasDefaultSupport; @@ -961,7 +961,7 @@ private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, } else { - if (IsDefaultValue(mapping, o, defaultValue!, isNullable)) + if (IsDefaultValue(o, defaultValue!)) { return; } @@ -983,7 +983,7 @@ private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, } else { - hasValidStringValue = WritePrimitiveValue(typeDesc, o, isElement, out stringValue); + hasValidStringValue = WritePrimitiveValue(typeDesc, o, out stringValue); } if (hasValidStringValue) @@ -1064,7 +1064,7 @@ private static bool hasRequirement(WritePrimitiveMethodRequirement value, WriteP return (value & requirement) == requirement; } - private static bool IsDefaultValue(TypeMapping mapping, object o, object value, bool isNullable) + private static bool IsDefaultValue(object o, object value) { if (value is string && ((string)value).Length == 0) { @@ -1077,7 +1077,7 @@ private static bool IsDefaultValue(TypeMapping mapping, object o, object value, } } - private bool WritePrimitiveValue(TypeDesc typeDesc, object? o, bool isElement, out string? stringValue) + private bool WritePrimitiveValue(TypeDesc typeDesc, object? o, out string? stringValue) { if (typeDesc == ReflectionXmlSerializationReader.StringTypeDesc || typeDesc.FormatterName == "String") { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs index a2c17817064e4..9bedc6dc0ce20 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs @@ -208,7 +208,7 @@ private void WriteAttribute(XmlAttribute a) } } - private void WriteAttributes(XmlAttribute[]? a, XmlSchemaObject o) + private void WriteAttributes(XmlAttribute[]? a) { if (a == null) return; ArrayList attrs = new ArrayList(); @@ -299,7 +299,7 @@ private void Write1_XmlSchemaAttribute(XmlSchemaAttribute? o) if (o is null) return; WriteStartElement("attribute"); WriteAttribute(@"id", @"", ((string?)o.@Id)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); WriteAttribute(@"default", @"", ((string?)o.@DefaultValue)); WriteAttribute(@"fixed", @"", ((string?)o.@FixedValue)); if (o.Parent != null && !(o.Parent is XmlSchema)) @@ -372,7 +372,7 @@ private void Write3_XmlSchemaObject(XmlSchemaObject? o) } else if (t == typeof(XmlSchemaXPath)) { - Write49_XmlSchemaXPath("xpath", "", (XmlSchemaXPath)o); + Write49_XmlSchemaXPath("xpath", (XmlSchemaXPath)o); return; } else if (t == typeof(XmlSchemaIdentityConstraint)) @@ -493,7 +493,7 @@ private void Write5_XmlSchemaAnnotation(XmlSchemaAnnotation? o) WriteStartElement("annotation"); WriteAttribute(@"id", @"", ((string?)o.@Id)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); System.Xml.Schema.XmlSchemaObjectCollection a = (System.Xml.Schema.XmlSchemaObjectCollection)o.@Items; if (a != null) { @@ -558,7 +558,7 @@ private void Write9_XmlSchemaSimpleType(XmlSchemaSimpleType? o) WriteStartElement("simpleType"); WriteAttribute(@"id", @"", ((string?)o.@Id)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); WriteAttribute(@"name", @"", ((string?)o.@Name)); WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved)); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); @@ -588,7 +588,7 @@ private void Write12_XmlSchemaSimpleTypeUnion(XmlSchemaSimpleTypeUnion? o) WriteStartElement("union"); WriteAttribute(@"id", @"", ((string?)o.@Id)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); if (o.MemberTypes != null) { @@ -620,7 +620,7 @@ private void Write14_XmlSchemaSimpleTypeList(XmlSchemaSimpleTypeList o) WriteStartElement("list"); WriteAttribute(@"id", @"", ((string?)o.@Id)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); if (!o.@ItemTypeName.IsEmpty) { WriteAttribute(@"itemType", @"", o.@ItemTypeName); @@ -635,7 +635,7 @@ private void Write15_XmlSchemaSimpleTypeRestriction(XmlSchemaSimpleTypeRestricti if (o is null) return; WriteStartElement("restriction"); WriteAttribute(@"id", @"", ((string?)o.@Id)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); @@ -721,7 +721,7 @@ private void Write_XmlSchemaFacet(string name, XmlSchemaFacet? o) { WriteAttribute(@"fixed", @"", XmlConvert.ToString(o.IsFixed)); } - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } @@ -746,7 +746,7 @@ private void Write31_XmlSchemaAttributeGroup(XmlSchemaAttributeGroup? o) WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute(@"name", @"", ((string?)o.@Name)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); @@ -764,7 +764,7 @@ private void Write32_XmlSchemaAttributeGroupRef(XmlSchemaAttributeGroupRef? o) { WriteAttribute("ref", "", o.RefName); } - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } @@ -778,7 +778,7 @@ private void Write33_XmlSchemaAnyAttribute(XmlSchemaAnyAttribute? o) WriteAttribute("namespace", "", ToString(o.NamespaceList)); XmlSchemaContentProcessing process = o.@ProcessContents == XmlSchemaContentProcessing.@None ? XmlSchemaContentProcessing.Strict : o.@ProcessContents; WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } @@ -813,7 +813,7 @@ private void Write35_XmlSchemaComplexType(XmlSchemaComplexType o) { WriteAttribute(@"mixed", @"", XmlConvert.ToString((bool)(bool)o.@IsMixed)); } - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@ContentModel is XmlSchemaComplexContent) { @@ -850,7 +850,7 @@ private void Write36_XmlSchemaSimpleContent(XmlSchemaSimpleContent? o) WriteStartElement("simpleContent"); WriteAttribute(@"id", @"", ((string?)o.@Id)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Content is XmlSchemaSimpleContentRestriction) { @@ -869,7 +869,7 @@ private void Write38_XmlSchemaSimpleContentExtension(XmlSchemaSimpleContentExten WriteStartElement("extension"); WriteAttribute(@"id", @"", ((string?)o.@Id)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); @@ -885,7 +885,7 @@ private void Write40_XmlSchemaSimpleContentRestriction(XmlSchemaSimpleContentRes if (o is null) return; WriteStartElement("restriction"); WriteAttribute(@"id", @"", ((string?)o.@Id)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); @@ -905,7 +905,7 @@ private void Write41_XmlSchemaComplexContent(XmlSchemaComplexContent? o) WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute(@"mixed", @"", XmlConvert.ToString((bool)((bool)o.@IsMixed))); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Content is XmlSchemaComplexContentRestriction) { @@ -924,7 +924,7 @@ private void Write42_XmlSchemaComplexContentExtension(XmlSchemaComplexContentExt WriteStartElement("extension"); WriteAttribute(@"id", @"", ((string?)o.@Id)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); @@ -959,7 +959,7 @@ private void Write43_XmlSchemaAll(XmlSchemaAll o) WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.@Items); WriteEndElement(); @@ -1012,7 +1012,7 @@ private void Write46_XmlSchemaElement(XmlSchemaElement? o) WriteAttribute("type", "", o.SchemaTypeName); } - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation(o.Annotation); if (o.SchemaType is XmlSchemaComplexType) { @@ -1032,16 +1032,16 @@ private void Write47_XmlSchemaKey(XmlSchemaKey? o) WriteStartElement("key"); WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute(@"name", @"", ((string?)o.@Name)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); - Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath?)o.@Selector); + Write49_XmlSchemaXPath(@"selector", (XmlSchemaXPath?)o.@Selector); { XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { - Write49_XmlSchemaXPath(@"field", @"", (XmlSchemaXPath)a[ia]); + Write49_XmlSchemaXPath(@"field", (XmlSchemaXPath)a[ia]); } } } @@ -1069,13 +1069,13 @@ private void Write48_XmlSchemaIdentityConstraint(XmlSchemaIdentityConstraint? o) } } - private void Write49_XmlSchemaXPath(string name, string ns, XmlSchemaXPath? o) + private void Write49_XmlSchemaXPath(string name, XmlSchemaXPath? o) { if (o is null) return; WriteStartElement(name); WriteAttribute(@"id", @"", o.@Id); WriteAttribute(@"xpath", @"", o.@XPath); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } @@ -1087,18 +1087,18 @@ private void Write50_XmlSchemaKeyref(XmlSchemaKeyref? o) WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute(@"name", @"", ((string?)o.@Name)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); // UNDONE compare reference here WriteAttribute(@"refer", @"", o.@Refer); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); - Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath?)o.@Selector); + Write49_XmlSchemaXPath(@"selector", (XmlSchemaXPath?)o.@Selector); { XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { - Write49_XmlSchemaXPath(@"field", @"", (XmlSchemaXPath)a[ia]); + Write49_XmlSchemaXPath(@"field", (XmlSchemaXPath)a[ia]); } } } @@ -1112,15 +1112,15 @@ private void Write51_XmlSchemaUnique(XmlSchemaUnique? o) WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute(@"name", @"", ((string?)o.@Name)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); - Write49_XmlSchemaXPath("selector", "", (XmlSchemaXPath?)o.@Selector); + Write49_XmlSchemaXPath("selector", (XmlSchemaXPath?)o.@Selector); XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { - Write49_XmlSchemaXPath("field", "", (XmlSchemaXPath)a[ia]); + Write49_XmlSchemaXPath("field", (XmlSchemaXPath)a[ia]); } } WriteEndElement(); @@ -1134,7 +1134,7 @@ private void Write52_XmlSchemaChoice(XmlSchemaChoice? o) WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.@Items); WriteEndElement(); @@ -1151,7 +1151,7 @@ private void Write53_XmlSchemaAny(XmlSchemaAny? o) WriteAttribute(@"namespace", @"", ToString(o.NamespaceList)); XmlSchemaContentProcessing process = o.@ProcessContents == XmlSchemaContentProcessing.@None ? XmlSchemaContentProcessing.Strict : o.@ProcessContents; WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } @@ -1164,7 +1164,7 @@ private void Write54_XmlSchemaSequence(XmlSchemaSequence? o) WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Items; if (a != null) @@ -1210,7 +1210,7 @@ private void Write55_XmlSchemaGroupRef(XmlSchemaGroupRef? o) { WriteAttribute("ref", "", o.RefName); } - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } @@ -1221,7 +1221,7 @@ private void Write56_XmlSchemaComplexContentRestriction(XmlSchemaComplexContentR WriteStartElement("restriction"); WriteAttribute(@"id", @"", ((string?)o.@Id)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); if (!o.@BaseTypeName.IsEmpty) { @@ -1257,7 +1257,7 @@ private void Write57_XmlSchemaGroup(XmlSchemaGroup? o) WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute(@"name", @"", ((string?)o.@Name)); - WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Particle is XmlSchemaSequence) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs index 6aa7d5a51ed10..61fbe309c6230 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs @@ -806,7 +806,7 @@ private TypeDesc ImportTypeDesc(Type type, MemberInfo? memberInfo, bool directRe { kind = TypeKind.Serializable; flags |= TypeFlags.Special | TypeFlags.CanBeElementValue; - flags |= GetConstructorFlags(type, ref exception); + flags |= GetConstructorFlags(type); } else if (type.IsArray) { @@ -823,7 +823,7 @@ private TypeDesc ImportTypeDesc(Type type, MemberInfo? memberInfo, bool directRe { kind = TypeKind.Collection; arrayElementType = GetCollectionElementType(type, memberInfo == null ? null : $"{memberInfo.DeclaringType!.FullName}.{memberInfo.Name}"); - flags |= GetConstructorFlags(type, ref exception); + flags |= GetConstructorFlags(type); } else if (type == typeof(XmlQualifiedName)) { @@ -906,7 +906,7 @@ private TypeDesc ImportTypeDesc(Type type, MemberInfo? memberInfo, bool directRe // check to see if the type has public default constructor for classes if (kind == TypeKind.Class && !type.IsAbstract) { - flags |= GetConstructorFlags(type, ref exception); + flags |= GetConstructorFlags(type); } // check if a struct-like type is enumerable if (kind == TypeKind.Struct || kind == TypeKind.Class) @@ -918,7 +918,7 @@ private TypeDesc ImportTypeDesc(Type type, MemberInfo? memberInfo, bool directRe // GetEnumeratorElementType checks for the security attributes on the GetEnumerator(), Add() methods and Current property, // we need to check the MoveNext() and ctor methods for the security attribues - flags |= GetConstructorFlags(type, ref exception); + flags |= GetConstructorFlags(type); } } typeDesc = new TypeDesc(type, CodeIdentifier.MakeValid(TypeName(type)), type.ToString(), kind, null, flags, null); @@ -1226,8 +1226,7 @@ private static bool ShouldBeReplaced( private static TypeFlags GetConstructorFlags( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors - | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type type, - ref Exception? exception) + | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type type) { ConstructorInfo? ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, Type.EmptyTypes); if (ctor != null) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs index a062a33142ba4..c65a4db922b5a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs @@ -454,7 +454,7 @@ private TypeMapping ImportTypeMapping(TypeModel model, string? ns, ImportContext if (a.XmlFlags != 0) throw InvalidAttributeUseException(model.Type); } if (model.TypeDesc.IsSpecial) - return ImportSpecialMapping(model.Type, model.TypeDesc, ns, context, limiter); + return ImportSpecialMapping(model.Type, model.TypeDesc, ns, context); throw UnsupportedException(model.TypeDesc, context); } } @@ -491,7 +491,7 @@ private TypeMapping ImportTypeMapping(TypeModel model, string? ns, ImportContext } [RequiresUnreferencedCode("calls IncludeTypes")] - private SpecialMapping ImportSpecialMapping(Type type, TypeDesc typeDesc, string? ns, ImportContext context, RecursionLimiter limiter) + private SpecialMapping ImportSpecialMapping(Type type, TypeDesc typeDesc, string? ns, ImportContext context) { _specials ??= new Hashtable(); SpecialMapping? mapping = (SpecialMapping?)_specials[type]; @@ -1078,7 +1078,7 @@ private ArrayMapping ImportArrayLikeMapping(ArrayModel model, string? ns, Recurs _savedArrayItemAttributes ??= new XmlArrayItemAttributes(); if (CountAtLevel(_savedArrayItemAttributes, _arrayNestingLevel) == 0) - _savedArrayItemAttributes.Add(CreateArrayItemAttribute(_typeScope.GetTypeDesc(model.Element.Type), _arrayNestingLevel)); + _savedArrayItemAttributes.Add(CreateArrayItemAttribute(_arrayNestingLevel)); CreateArrayElementsFromAttributes(mapping, _savedArrayItemAttributes, model.Element.Type, _savedArrayNamespace ?? ns, limiter); SetArrayMappingType(mapping, ns, model.Type); @@ -1312,7 +1312,7 @@ private MemberMapping ImportMemberMapping(XmlReflectionMember xmlReflectionMembe { if (typeDesc.IsArrayLike) { - XmlArrayAttribute xmlArray = CreateArrayAttribute(typeDesc); + XmlArrayAttribute xmlArray = CreateArrayAttribute(); xmlArray.ElementName = xmlReflectionMember.MemberName; xmlArray.Namespace = rpc ? null : ns; xmlArray.Form = form; @@ -1520,7 +1520,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml XmlAttributeFlags flags = a.XmlFlags; accessor.Ignore = a.XmlIgnore; if (rpc) - CheckTopLevelAttributes(a, accessorName); + CheckTopLevelAttributes(a); else CheckAmbiguousChoice(a, accessorType, accessorName); @@ -1711,9 +1711,9 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml } TypeDesc arrayElementTypeDesc = _typeScope.GetTypeDesc(arrayElementType); - a.XmlArray ??= CreateArrayAttribute(accessor.TypeDesc); + a.XmlArray ??= CreateArrayAttribute(); if (CountAtLevel(a.XmlArrayItems, _arrayNestingLevel) == 0) - a.XmlArrayItems.Add(CreateArrayItemAttribute(arrayElementTypeDesc, _arrayNestingLevel)); + a.XmlArrayItems.Add(CreateArrayItemAttribute(_arrayNestingLevel)); ElementAccessor arrayElement = new ElementAccessor(); arrayElement.Name = XmlConvert.EncodeLocalName(a.XmlArray.ElementName.Length == 0 ? accessorName : a.XmlArray.ElementName); arrayElement.Namespace = rpc ? null : a.XmlArray.Namespace ?? ns; @@ -2017,7 +2017,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml } - private static void CheckTopLevelAttributes(XmlAttributes a, string accessorName) + private static void CheckTopLevelAttributes(XmlAttributes a) { XmlAttributeFlags flags = a.XmlFlags; @@ -2138,14 +2138,14 @@ private static void CheckChoiceIdentifierMapping(EnumMapping choiceMapping) return a.XmlDefaultValue; } - private static XmlArrayItemAttribute CreateArrayItemAttribute(TypeDesc typeDesc, int nestingLevel) + private static XmlArrayItemAttribute CreateArrayItemAttribute(int nestingLevel) { XmlArrayItemAttribute xmlArrayItem = new XmlArrayItemAttribute(); xmlArrayItem.NestingLevel = nestingLevel; return xmlArrayItem; } - private static XmlArrayAttribute CreateArrayAttribute(TypeDesc typeDesc) + private static XmlArrayAttribute CreateArrayAttribute() { XmlArrayAttribute xmlArrayItem = new XmlArrayAttribute(); return xmlArrayItem; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs index 0e18a2484a6e9..c6efc6548ea51 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs @@ -327,7 +327,7 @@ private TypeMapping ImportElementType(XmlSchemaElement element, string identifie else if (element.SchemaType != null) { if (element.SchemaType is XmlSchemaComplexType) - mapping = ImportType((XmlSchemaComplexType)element.SchemaType, ns, identifier, desiredMappingType, baseType, TypeFlags.CanBeElementValue); + mapping = ImportType((XmlSchemaComplexType)element.SchemaType, ns, identifier, desiredMappingType, baseType); else mapping = ImportDataType((XmlSchemaSimpleType)element.SchemaType, ns, identifier, baseType, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeTextValue, false)!; mapping!.ReferencedByElement = true; @@ -408,7 +408,7 @@ internal override void ImportDerivedTypes(XmlQualifiedName baseName) AddReference(name, TypesInUse, SR.XmlCircularTypeReference); if (type is XmlSchemaComplexType) { - mapping = ImportType((XmlSchemaComplexType)type, name.Namespace, name.Name, desiredMappingType, baseType, flags); + mapping = ImportType((XmlSchemaComplexType)type, name.Namespace, name.Name, desiredMappingType, baseType); } else if (type is XmlSchemaSimpleType) mapping = ImportDataType((XmlSchemaSimpleType)type, name.Namespace, name.Name, baseType, flags, false); @@ -422,7 +422,7 @@ internal override void ImportDerivedTypes(XmlQualifiedName baseName) } [RequiresUnreferencedCode("calls ImportMembersType")] - private TypeMapping? ImportType(XmlSchemaComplexType type, string? typeNs, string identifier, Type desiredMappingType, Type? baseType, TypeFlags flags) + private TypeMapping? ImportType(XmlSchemaComplexType type, string? typeNs, string identifier, Type desiredMappingType, Type? baseType) { if (type.Redefined != null) { @@ -435,9 +435,9 @@ internal override void ImportDerivedTypes(XmlQualifiedName baseName) if (baseType == null) { - if ((mapping = ImportArrayMapping(type, identifier, typeNs, false)) == null) + if ((mapping = ImportArrayMapping(type, identifier, typeNs)) == null) { - mapping = ImportAnyMapping(type, identifier, typeNs, false); + mapping = ImportAnyMapping(type, false); } } if (mapping == null) @@ -652,7 +652,7 @@ private MemberMapping[] ImportTypeMembers(XmlSchemaType type, string? typeNs, st } if (items.AnyAttribute != null) { - ImportAnyAttributeMember(items.AnyAttribute, members, membersScope); + ImportAnyAttributeMember(members, membersScope); } if (items.baseSimpleType != null || (items.Particle == null && mixed)) @@ -1017,7 +1017,7 @@ private void ImportGroupMembers(XmlSchemaParticle? particle, string identifier, ImportElementMember((XmlSchemaElement)item, identifier, members, membersScope, elementsScope, ns, groupRepeats, ref needExplicitOrder, allowDuplicates, allowUnboundedElements); else if (item is XmlSchemaAny) { - ImportAnyMember((XmlSchemaAny)item, identifier, members, membersScope, elementsScope, ns, ref mixed, ref needExplicitOrder, allowDuplicates); + ImportAnyMember((XmlSchemaAny)item, members, membersScope, elementsScope, ns, ref mixed, ref needExplicitOrder, allowDuplicates); } else if (item is XmlSchemaParticle) { @@ -1133,7 +1133,7 @@ private void ImportTextMember(CodeIdentifiers members, CodeIdentifiers membersSc } [RequiresUnreferencedCode("calls GetTypeDesc")] - private MemberMapping ImportAnyMember(XmlSchemaAny any, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string? ns, ref bool mixed, ref bool needExplicitOrder, bool allowDuplicates) + private MemberMapping ImportAnyMember(XmlSchemaAny any, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string? ns, ref bool mixed, ref bool needExplicitOrder, bool allowDuplicates) { ElementAccessor[] accessors = ImportAny(any, !mixed, ns); AddScopeElements(elementsScope, accessors, ref needExplicitOrder, allowDuplicates); @@ -1211,7 +1211,7 @@ private ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string? if (element.SchemaType == null) return null; if (element.IsMultipleOccurrence) return null; XmlSchemaType type = element.SchemaType; - ArrayMapping? arrayMapping = ImportArrayMapping(type, identifier, ns, repeats); + ArrayMapping? arrayMapping = ImportArrayMapping(type, identifier, ns); if (arrayMapping == null) return null; ElementAccessor arrayAccessor = new ElementAccessor(); arrayAccessor.Name = element.Name; @@ -1224,7 +1224,7 @@ private ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string? } [RequiresUnreferencedCode("calls ImportChoiceGroup")] - private ArrayMapping? ImportArrayMapping(XmlSchemaType type, string identifier, string? ns, bool repeats) + private ArrayMapping? ImportArrayMapping(XmlSchemaType type, string identifier, string? ns) { if (!(type is XmlSchemaComplexType)) return null; if (!type.DerivedFrom.IsEmpty) return null; @@ -1328,7 +1328,7 @@ private bool IsCyclicReferencedType(XmlSchemaElement element, List ident } [RequiresUnreferencedCode("calls GetTypeDesc")] - private SpecialMapping? ImportAnyMapping(XmlSchemaType? type, string identifier, string? ns, bool repeats) + private SpecialMapping? ImportAnyMapping(XmlSchemaType? type, bool repeats) { if (type == null) return null; if (!type.DerivedFrom.IsEmpty) return null; @@ -1450,7 +1450,7 @@ private void ImportAttributeMember(XmlSchemaAttribute attribute, string identifi } [RequiresUnreferencedCode("calls GetTypeDesc")] - private void ImportAnyAttributeMember(XmlSchemaAnyAttribute any, CodeIdentifiers members, CodeIdentifiers membersScope) + private void ImportAnyAttributeMember(CodeIdentifiers members, CodeIdentifiers membersScope) { SpecialMapping mapping = new SpecialMapping(); mapping.TypeDesc = Scope.GetTypeDesc(typeof(XmlAttribute)); @@ -1545,11 +1545,11 @@ private void ImportAttributeGroupMembers(XmlSchemaAttributeGroup group, string i ImportAttributeMember((XmlSchemaAttribute)item, identifier, members, membersScope, ns); } if (group.AnyAttribute != null) - ImportAnyAttributeMember(group.AnyAttribute, members, membersScope); + ImportAnyAttributeMember(members, membersScope); } [RequiresUnreferencedCode("calls GetTypeDesc")] - private AttributeAccessor ImportSpecialAttribute(XmlQualifiedName name, string identifier) + private AttributeAccessor ImportSpecialAttribute(XmlQualifiedName name) { PrimitiveMapping mapping = new PrimitiveMapping(); mapping.TypeDesc = Scope.GetTypeDesc(typeof(string)); @@ -1569,7 +1569,7 @@ private AttributeAccessor ImportSpecialAttribute(XmlQualifiedName name, string i if (!attribute.RefName.IsEmpty) { if (attribute.RefName.Namespace == XmlReservedNs.NsXml) - return ImportSpecialAttribute(attribute.RefName, identifier); + return ImportSpecialAttribute(attribute.RefName); else return ImportAttribute(FindAttribute(attribute.RefName), identifier, attribute.RefName.Namespace, defaultValueProvider); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs index 1dd3f6570a5dd..c8ff8e95cdd2a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs @@ -264,7 +264,7 @@ private void RemoveName(XmlSchema schema) #endif if (ret != null && _shareTypes && checkCache && !IsReference(ret)) - ret = Cache.AddItem(ret, name, this); + ret = Cache.AddItem(ret, name); if (ret != null) { return ret; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs index 8ff09f27cd9ca..94c7afa80f00e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs @@ -364,7 +364,7 @@ private void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappin _writer.WriteLine("}"); } - internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type?[] types, string readerType, string?[] readMethods, string writerType, string?[] writerMethods, Hashtable serializers) + internal void GenerateSerializerContract(XmlMapping[] xmlMappings, Type?[] types, string readerType, string?[] readMethods, string writerType, string?[] writerMethods, Hashtable serializers) { _writer.WriteLine(); _writer.Write("public class XmlSerializerContract : global::"); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs index b57ac4bd7d2aa..e35719e7c0073 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs @@ -476,7 +476,7 @@ private void GenerateGetSerializer(Dictionary serializers, XmlMa } [RequiresUnreferencedCode("calls GenerateTypedSerializers")] - internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type[] types, string readerType, string[] readMethods, string writerType, string[] writerMethods, Dictionary serializers) + internal void GenerateSerializerContract(XmlMapping[] xmlMappings, Type[] types, string readerType, string[] readMethods, string writerType, string[] writerMethods, Dictionary serializers) { TypeBuilder serializerContractTypeBuilder = CodeGenerator.CreateTypeBuilder( _moduleBuilder!, diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs index 05a40de3b2828..6623d11ebd62a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs @@ -111,7 +111,7 @@ public abstract class XmlSerializationReader : XmlSerializationGeneratedCode protected abstract void InitIDs(); // this method must be called before any generated deserialization methods are called - internal void Init(XmlReader r, XmlDeserializationEvents events, string? encodingStyle, TempAssembly? tempAssembly) + internal void Init(XmlReader r, XmlDeserializationEvents events, string? encodingStyle) { _events = events; _r = r; @@ -2276,7 +2276,7 @@ internal override void GenerateMethod(TypeMapping mapping) } [RequiresUnreferencedCode("calls GenerateReferencedMethods")] - internal void GenerateEnd(string?[] methods, XmlMapping[] xmlMappings, Type?[]? types) + internal void GenerateEnd() { GenerateReferencedMethods(); GenerateInitCallbacksMethod(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs index f7d8514e55a2c..50a2c73c72c41 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs @@ -42,27 +42,27 @@ private sealed class Member private string? _paramsReadSource; private string? _checkSpecifiedSource; - internal Member(XmlSerializationReaderILGen outerClass, string source, string? arrayName, int i, MemberMapping mapping) - : this(outerClass, source, null, arrayName, i, mapping, false, null) + internal Member(string source, string? arrayName, int i, MemberMapping mapping) + : this(source, null, arrayName, i, mapping, false, null) { } - internal Member(XmlSerializationReaderILGen outerClass, string source, string? arrayName, int i, MemberMapping mapping, string? choiceSource) - : this(outerClass, source, null, arrayName, i, mapping, false, choiceSource) + internal Member(string source, string? arrayName, int i, MemberMapping mapping, string? choiceSource) + : this(source, null, arrayName, i, mapping, false, choiceSource) { } - internal Member(XmlSerializationReaderILGen outerClass, string source, string? arraySource, string? arrayName, int i, MemberMapping mapping) - : this(outerClass, source, arraySource, arrayName, i, mapping, false, null) + internal Member(string source, string? arraySource, string? arrayName, int i, MemberMapping mapping) + : this(source, arraySource, arrayName, i, mapping, false, null) { } - internal Member(XmlSerializationReaderILGen outerClass, string source, string? arraySource, string? arrayName, int i, MemberMapping mapping, string? choiceSource) - : this(outerClass, source, arraySource, arrayName, i, mapping, false, choiceSource) + internal Member(string source, string? arraySource, string? arrayName, int i, MemberMapping mapping, string? choiceSource) + : this(source, arraySource, arrayName, i, mapping, false, choiceSource) { } - internal Member(XmlSerializationReaderILGen outerClass, string source, string? arrayName, int i, MemberMapping mapping, bool multiRef) - : this(outerClass, source, null, arrayName, i, mapping, multiRef, null) + internal Member(string source, string? arrayName, int i, MemberMapping mapping, bool multiRef) + : this(source, null, arrayName, i, mapping, multiRef, null) { } - internal Member(XmlSerializationReaderILGen outerClass, string source, string? arraySource, string? arrayName, int i, MemberMapping mapping, bool multiRef, string? choiceSource) + internal Member(string source, string? arraySource, string? arrayName, int i, MemberMapping mapping, bool multiRef, string? choiceSource) { _source = source; _arrayName = string.Create(CultureInfo.InvariantCulture, $"{arrayName}_{i}"); @@ -87,7 +87,7 @@ internal Member(XmlSerializationReaderILGen outerClass, string source, string? a string castString = $"({choiceTypeFullName}[])"; string init = $"{a} = {castString}EnsureArrayIndex({a}, {c}, {ReflectionAwareILGen.GetStringForTypeof(choiceTypeFullName)});"; - _choiceArraySource = init + ReflectionAwareILGen.GetStringForArrayMember(a, $"{c}++", mapping.ChoiceIdentifier.Mapping.TypeDesc); + _choiceArraySource = init + ReflectionAwareILGen.GetStringForArrayMember(a, $"{c}++"); } else { @@ -217,7 +217,7 @@ internal override void GenerateMethod(TypeMapping mapping) } [RequiresUnreferencedCode("calls GenerateReferencedMethods")] - internal void GenerateEnd(string[] methods, XmlMapping[] xmlMappings, Type[] types) + internal void GenerateEnd() { GenerateReferencedMethods(); GenerateInitCallbacksMethod(); @@ -374,11 +374,11 @@ private static string GetChoiceIdentifierSource(MemberMapping[] mappings, Member return choiceSource!; } - private static string GetChoiceIdentifierSource(MemberMapping mapping, string parent, TypeDesc parentTypeDesc) + private static string GetChoiceIdentifierSource(MemberMapping mapping, string parent) { if (mapping.ChoiceIdentifier == null) return ""; CodeIdentifier.CheckValidIdentifier(mapping.ChoiceIdentifier.MemberName); - return ReflectionAwareILGen.GetStringForMember(parent, mapping.ChoiceIdentifier.MemberName, parentTypeDesc); + return ReflectionAwareILGen.GetStringForMember(parent, mapping.ChoiceIdentifier.MemberName); } [RequiresUnreferencedCode("calls InitializeValueTypes")] @@ -442,8 +442,8 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping arraySource = $"(({mapping.TypeDesc!.CSharpName}){source})"; } string choiceSource = GetChoiceIdentifierSource(mappings, mapping); - Member member = new Member(this, source, arraySource, "a", i, mapping, choiceSource); - Member anyMember = new Member(this, source, null, "a", i, mapping, choiceSource); + Member member = new Member(source, arraySource, "a", i, mapping, choiceSource); + Member anyMember = new Member(source, null, "a", i, mapping, choiceSource); if (!mapping.IsSequence) member.ParamsReadSource = $"paramsRead[{i}]"; if (mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) @@ -648,7 +648,7 @@ private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) member.TypeDesc = mapping.TypeDesc; //member.ReadOnly = !mapping.TypeDesc.HasDefaultConstructor; member.Elements = new ElementAccessor[] { element }; - Member[] members = new Member[] { new Member(this, "o", "o", "a", 0, member) }; + Member[] members = new Member[] { new Member("o", "o", "a", 0, member) }; MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, @@ -1256,7 +1256,7 @@ private void WriteEnumAndArrayTypes() memberMapping.Elements = arrayMapping.Elements; string aVar = "a"; string zVar = "z"; - Member member = new Member(this, aVar, zVar, 0, memberMapping); + Member member = new Member(aVar, zVar, 0, memberMapping); TypeDesc td = arrayMapping.TypeDesc; LocalBuilder aLoc = ilg.DeclareLocal(arrayMapping.TypeDesc.Type!, aVar); @@ -1268,7 +1268,7 @@ private void WriteEnumAndArrayTypes() ilg.Load(null); ilg.Stloc(aLoc); - WriteArray(member.Source, member.ArrayName, arrayMapping, false, false, -1, 0); + WriteArray(member.Source, member.ArrayName, arrayMapping, false, false, 0); ilg.Ldloc(aLoc); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); @@ -1550,13 +1550,13 @@ private void WriteLiteralStructMethod(StructMapping structMapping) { MemberMapping mapping = mappings[i]; CodeIdentifier.CheckValidIdentifier(mapping.Name); - string source = ReflectionAwareILGen.GetStringForMember("o", mapping.Name, structMapping.TypeDesc); - Member member = new Member(this, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o", structMapping.TypeDesc)); + string source = ReflectionAwareILGen.GetStringForMember("o", mapping.Name); + Member member = new Member(source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o")); if (!mapping.IsSequence) member.ParamsReadSource = $"paramsRead[{i}]"; member.IsNullable = mapping.TypeDesc!.IsNullable; if (mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) - member.CheckSpecifiedSource = ReflectionAwareILGen.GetStringForMember("o", $"{mapping.Name}Specified", structMapping.TypeDesc); + member.CheckSpecifiedSource = ReflectionAwareILGen.GetStringForMember("o", $"{mapping.Name}Specified"); if (mapping.Text != null) anyText = member; if (mapping.Attribute != null && mapping.Attribute.Any) @@ -1581,7 +1581,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) } if (mapping.Attribute == null && mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping) { - Member arrayMember = new Member(this, source, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o", structMapping.TypeDesc)); + Member arrayMember = new Member(source, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o")); arrayMember.CheckSpecifiedSource = member.CheckSpecifiedSource; allMembersList.Add(arrayMember); } @@ -2271,7 +2271,7 @@ private void WriteMemberElements(Member[] members, string elementElseString, str WriteMemberElementsIf(members, anyElement, elementElseString); if (anyText != null) - WriteMemberText(anyText, elseString); + WriteMemberText(anyText); ilg.Else(); ILGenElseString(elseString); @@ -2279,7 +2279,7 @@ private void WriteMemberElements(Member[] members, string elementElseString, str } [RequiresUnreferencedCode("calls WriteText")] - private void WriteMemberText(Member anyText, string elseString) + private void WriteMemberText(Member anyText) { ilg.InitElseIf(); Label labelTrue = ilg.DefineLabel(); @@ -2337,7 +2337,7 @@ private void WriteText(Member member) if (text.Mapping is SpecialMapping special) { - WriteSourceBeginTyped(member.ArraySource, special.TypeDesc); + WriteSourceBeginTyped(member.ArraySource); switch (special.TypeDesc!.Kind) { case TypeKind.Node: @@ -2618,7 +2618,7 @@ private static string GetArraySource(TypeDesc typeDesc, string arrayName, bool m { string arrayTypeFullName = typeDesc.ArrayElementTypeDesc!.CSharpName; init = $"{init}{a} = ({arrayTypeFullName}[])EnsureArrayIndex({a}, {c}, {ReflectionAwareILGen.GetStringForTypeof(arrayTypeFullName)});"; - string arraySource = ReflectionAwareILGen.GetStringForArrayMember(a, $"{c}++", typeDesc); + string arraySource = ReflectionAwareILGen.GetStringForArrayMember(a, $"{c}++"); if (multiRef) { init = $"{init} soap[1] = {a};"; @@ -2628,7 +2628,7 @@ private static string GetArraySource(TypeDesc typeDesc, string arrayName, bool m } else { - return ReflectionAwareILGen.GetStringForMethod(arrayName, typeDesc.CSharpName, "Add"); + return ReflectionAwareILGen.GetStringForMethod(arrayName, "Add"); } } @@ -2699,7 +2699,7 @@ private void WriteMemberEnd(Member[] members, bool soapRefs) } } - private void WriteSourceBeginTyped(string source, TypeDesc? typeDesc) + private void WriteSourceBeginTyped(string source) { WriteSourceBegin(source); } @@ -2872,7 +2872,7 @@ private void WriteSourceEnd(string source, Type elementType, Type stackType) } [RequiresUnreferencedCode("calls WriteMemberBegin")] - private void WriteArray(string source, string? arrayName, ArrayMapping arrayMapping, bool readOnly, bool isNullable, int fixupIndex, int elementIndex) + private void WriteArray(string source, string? arrayName, ArrayMapping arrayMapping, bool readOnly, bool isNullable, int elementIndex) { MethodInfo XmlSerializationReader_ReadNull = typeof(XmlSerializationReader).GetMethod( "ReadNull", @@ -2893,7 +2893,7 @@ private void WriteArray(string source, string? arrayName, ArrayMapping arrayMapp Debug.Assert(memberInfos.ContainsKey(source.Substring(3))); memberMapping.MemberInfo = memberInfos[source.Substring(3)]; } - Member member = new Member(this, source, arrayName, elementIndex, memberMapping, false); + Member member = new Member(source, arrayName, elementIndex, memberMapping, false); member.IsNullable = false; //Note, IsNullable is set to false since null condition (xsi:nil) is already handled by 'ReadNull()' Member[] members = new Member[] { member }; @@ -2998,7 +2998,7 @@ private void WriteElement(string source, string? arrayName, string? choiceSource if (element.Mapping is ArrayMapping) { - WriteArray(source, arrayName, (ArrayMapping)element.Mapping, readOnly, element.IsNullable, fixupIndex, elementIndex); + WriteArray(source, arrayName, (ArrayMapping)element.Mapping, readOnly, element.IsNullable, elementIndex); } else if (element.Mapping is NullableMapping) { @@ -3205,7 +3205,7 @@ private void WriteElement(string source, string? arrayName, string? choiceSource { case TypeKind.Node: bool isDoc = special.TypeDesc.FullName == typeof(XmlDocument).FullName; - WriteSourceBeginTyped(source, special.TypeDesc); + WriteSourceBeginTyped(source); MethodInfo XmlSerializationReader_ReadXmlXXX = typeof(XmlSerializationReader).GetMethod( isDoc ? "ReadXmlDocument" : "ReadXmlNode", CodeGenerator.InstanceBindingFlags, @@ -3247,7 +3247,7 @@ private void WriteElement(string source, string? arrayName, string? choiceSource ilg.MarkLabel(labelEnd); ilg.If(); } - WriteSourceBeginTyped(source, sm.TypeDesc!); + WriteSourceBeginTyped(source); bool isWrappedAny = !element.Any && IsWildcard(sm); MethodInfo XmlSerializationReader_ReadSerializable = typeof(XmlSerializationReader).GetMethod( "ReadSerializable", @@ -3320,7 +3320,7 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp { if (head.Type!.IsAssignableFrom(derived.Type)) { - WriteSourceBeginTyped(source, head.TypeDesc!); + WriteSourceBeginTyped(source); MethodInfo XmlSerializationReader_ReadSerializable = typeof(XmlSerializationReader).GetMethod( "ReadSerializable", CodeGenerator.InstanceBindingFlags, diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs index ed849b76284ee..cfa361fa3f2a0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs @@ -39,7 +39,7 @@ public abstract class XmlSerializationWriter : XmlSerializationGeneratedCode private bool _escapeName = true; // this method must be called before any generated serialization methods are called - internal void Init(XmlWriter w, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? idBase, TempAssembly? tempAssembly) + internal void Init(XmlWriter w, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? idBase) { _w = w; _namespaces = namespaces; @@ -2386,7 +2386,7 @@ private void WriteEnumValue(EnumMapping mapping, string source) Writer.Write(")"); } - private void WritePrimitiveValue(TypeDesc typeDesc, string source, bool isElement) + private void WritePrimitiveValue(TypeDesc typeDesc, string source) { if (typeDesc == StringTypeDesc || typeDesc.FormatterName == "String") { @@ -2479,7 +2479,7 @@ private void WritePrimitive(string method, string name, string? ns, object? defa } else { - WritePrimitiveValue(typeDesc, source, isElement); + WritePrimitiveValue(typeDesc, source); } if (writeXsiType) @@ -3378,7 +3378,7 @@ private void WriteMember(string source, AttributeAccessor attribute, TypeDesc me if (attribute.Mapping is EnumMapping) WriteEnumValue((EnumMapping)attribute.Mapping, "ai"); else - WritePrimitiveValue(arrayElementTypeDesc, "ai", true); + WritePrimitiveValue(arrayElementTypeDesc, "ai"); Writer.WriteLine(");"); } else @@ -3860,7 +3860,7 @@ private void WriteText(string source, TextAccessor text) } else { - WritePrimitiveValue(primitive.TypeDesc!, source, false); + WritePrimitiveValue(primitive.TypeDesc!, source); } Writer.WriteLine(");"); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs index 1e74f8425a252..2779c633b70c5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs @@ -1036,7 +1036,7 @@ private void WriteStructMethod(StructMapping mapping) { MemberMapping member = members[xmlnsMember]; CodeIdentifier.CheckValidIdentifier(member.Name); - xmlnsSource = ReflectionAwareILGen.GetStringForMember("o", member.Name, mapping.TypeDesc); + xmlnsSource = ReflectionAwareILGen.GetStringForMember("o", member.Name); } ilg.Ldarg(0); @@ -1090,11 +1090,11 @@ private void WriteStructMethod(StructMapping mapping) } if (m.CheckSpecified != SpecifiedAccessor.None) { - string memberGet = ReflectionAwareILGen.GetStringForMember("o", $"{m.Name}Specified", mapping.TypeDesc); + string memberGet = ReflectionAwareILGen.GetStringForMember("o", $"{m.Name}Specified"); ILGenLoad(memberGet); ilg.If(); } - WriteMember(ReflectionAwareILGen.GetSourceForMember("o", m, mapping.TypeDesc, ilg), m.Attribute, m.TypeDesc!, "o"); + WriteMember(ReflectionAwareILGen.GetSourceForMember("o", m, ilg), m.Attribute, m.TypeDesc!, "o"); if (m.CheckSpecified != SpecifiedAccessor.None) { @@ -1123,7 +1123,7 @@ private void WriteStructMethod(StructMapping mapping) } if (m.CheckSpecified != SpecifiedAccessor.None) { - string memberGet = ReflectionAwareILGen.GetStringForMember("o", $"{m.Name}Specified", mapping.TypeDesc); + string memberGet = ReflectionAwareILGen.GetStringForMember("o", $"{m.Name}Specified"); ILGenLoad(memberGet); ilg.If(); } @@ -1132,10 +1132,10 @@ private void WriteStructMethod(StructMapping mapping) if (m.ChoiceIdentifier != null) { CodeIdentifier.CheckValidIdentifier(m.ChoiceIdentifier.MemberName); - choiceSource = ReflectionAwareILGen.GetStringForMember("o", m.ChoiceIdentifier.MemberName, mapping.TypeDesc); + choiceSource = ReflectionAwareILGen.GetStringForMember("o", m.ChoiceIdentifier.MemberName); } - WriteMember(ReflectionAwareILGen.GetSourceForMember("o", m, m.MemberInfo, mapping.TypeDesc, ilg), choiceSource, m.ElementsSortedByDerivation!, m.Text, m.ChoiceIdentifier, m.TypeDesc!, true); + WriteMember(ReflectionAwareILGen.GetSourceForMember("o", m, m.MemberInfo, ilg), choiceSource, m.ElementsSortedByDerivation!, m.Text, m.ChoiceIdentifier, m.TypeDesc!, true); if (m.CheckSpecified != SpecifiedAccessor.None) { @@ -1221,7 +1221,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes { LocalBuilder localI = ilg.DeclareOrGetLocal(typeof(int), iVar); ilg.For(localI, 0, ilg.GetLocal(aVar)); - WriteLocalDecl(aiVar, ReflectionAwareILGen.GetStringForArrayMember(aVar, iVar, memberTypeDesc), arrayElementTypeDesc.Type!); + WriteLocalDecl(aiVar, ReflectionAwareILGen.GetStringForArrayMember(aVar, iVar), arrayElementTypeDesc.Type!); } if (attribute.IsList) { @@ -1562,16 +1562,16 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor? text, Cho int count = elements.Length + (text == null ? 0 : 1); if (count > 1) { - WriteLocalDecl(arrayNamePlusI, ReflectionAwareILGen.GetStringForArrayMember(arrayName, iPlusArrayName, arrayTypeDesc), arrayElementTypeDesc.Type!); + WriteLocalDecl(arrayNamePlusI, ReflectionAwareILGen.GetStringForArrayMember(arrayName, iPlusArrayName), arrayElementTypeDesc.Type!); if (choice != null) { - WriteLocalDecl($"{choiceName}i", ReflectionAwareILGen.GetStringForArrayMember(choiceName, iPlusArrayName, choice.Mapping!.TypeDesc!), choice.Mapping.TypeDesc!.Type!); + WriteLocalDecl($"{choiceName}i", ReflectionAwareILGen.GetStringForArrayMember(choiceName, iPlusArrayName), choice.Mapping!.TypeDesc!.Type!); } WriteElements(new SourceInfo(arrayNamePlusI, null, null, arrayElementTypeDesc.Type, ilg), $"{choiceName}i", elements, text, choice, arrayNamePlusA, true, arrayElementTypeDesc.IsNullable); } else { - WriteElements(new SourceInfo(ReflectionAwareILGen.GetStringForArrayMember(arrayName, iPlusArrayName, arrayTypeDesc), null, null, arrayElementTypeDesc.Type, ilg), null, elements, text, choice, arrayNamePlusA, true, arrayElementTypeDesc.IsNullable); + WriteElements(new SourceInfo(ReflectionAwareILGen.GetStringForArrayMember(arrayName, iPlusArrayName), null, null, arrayElementTypeDesc.Type, ilg), null, elements, text, choice, arrayNamePlusA, true, arrayElementTypeDesc.IsNullable); } ilg.EndFor(); } @@ -1622,7 +1622,6 @@ private void WriteElements(SourceInfo source, string? enumSource, ElementAccesso } else if (choice != null) { - string fullTypeName = element.Mapping!.TypeDesc!.CSharpName; object? enumValue; string enumFullName = $"{enumTypeName}.@{FindChoiceEnumValue(element, (EnumMapping)choice.Mapping!, out enumValue)}"; @@ -1646,9 +1645,9 @@ private void WriteElements(SourceInfo source, string? enumSource, ElementAccesso } ilg.AndIf(); - WriteChoiceTypeCheck(source, fullTypeName, choice!, enumFullName, element.Mapping.TypeDesc); + WriteChoiceTypeCheck(source, choice!, enumFullName, element.Mapping!.TypeDesc!); - SourceInfo castedSource = source.CastTo(element.Mapping.TypeDesc); + SourceInfo castedSource = source.CastTo(element.Mapping.TypeDesc!); WriteElement(element.Any ? source : castedSource, element, arrayName, writeAccessors); } else @@ -2171,7 +2170,7 @@ private void WriteCheckDefault(SourceInfo source, object value, bool isNullable) } [RequiresUnreferencedCode("calls Load")] - private void WriteChoiceTypeCheck(SourceInfo source, string fullTypeName, ChoiceIdentifierAccessor choice, string enumName, TypeDesc typeDesc) + private void WriteChoiceTypeCheck(SourceInfo source, ChoiceIdentifierAccessor choice, string enumName, TypeDesc typeDesc) { Label labelFalse = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); @@ -2352,28 +2351,28 @@ internal static string GetStringForTypeof(string typeFullName) { return $"typeof({typeFullName})"; } - internal static string GetStringForMember(string obj, string memberName, TypeDesc typeDesc) + internal static string GetStringForMember(string obj, string memberName) { return $"{obj}.@{memberName}"; } - internal static SourceInfo GetSourceForMember(string obj, MemberMapping member, TypeDesc typeDesc, CodeGenerator ilg) + internal static SourceInfo GetSourceForMember(string obj, MemberMapping member, CodeGenerator ilg) { - return GetSourceForMember(obj, member, member.MemberInfo, typeDesc, ilg); + return GetSourceForMember(obj, member, member.MemberInfo, ilg); } - internal static SourceInfo GetSourceForMember(string obj, MemberMapping member, MemberInfo? memberInfo, TypeDesc typeDesc, CodeGenerator ilg) + internal static SourceInfo GetSourceForMember(string obj, MemberMapping member, MemberInfo? memberInfo, CodeGenerator ilg) { - return new SourceInfo(GetStringForMember(obj, member.Name, typeDesc), obj, memberInfo, member.TypeDesc!.Type, ilg); + return new SourceInfo(GetStringForMember(obj, member.Name), obj, memberInfo, member.TypeDesc!.Type, ilg); } internal static void ILGenForEnumMember(CodeGenerator ilg, Type type, string memberName) { ilg.Ldc(Enum.Parse(type, memberName, false)); } - internal static string GetStringForArrayMember(string? arrayName, string subscript, TypeDesc arrayTypeDesc) + internal static string GetStringForArrayMember(string? arrayName, string subscript) { return $"{arrayName}[{subscript}]"; } - internal static string GetStringForMethod(string obj, string typeFullName, string memberName) + internal static string GetStringForMethod(string obj, string memberName) { return $"{obj}.{memberName}("; } @@ -2399,11 +2398,11 @@ internal static void ILGenForCreateInstance(CodeGenerator ilg, Type type, bool c } return; } - ILGenForCreateInstance(ilg, type, cast ? type : null, ctorInaccessible); + ILGenForCreateInstance(ilg, type, cast ? type : null); } [RequiresUnreferencedCode("calls GetType")] - internal static void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type? cast, bool nonPublic) + internal static void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type? cast) { // Special case DBNull if (type == typeof(DBNull)) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs index c1c87a51dbd33..71bd696e6f0e5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs @@ -381,7 +381,7 @@ public void Serialize(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? n { // The contion for the block is never true, thus the block is never hit. XmlSerializationWriter writer = CreateWriter(); - writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id, _tempAssembly); + writer.Init(xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); Serialize(o, writer); } else @@ -473,7 +473,7 @@ private XmlMapping GetMapping() else if (_tempAssembly == null || _typedSerializer) { XmlSerializationReader reader = CreateReader(); - reader.Init(xmlReader, events, encodingStyle, _tempAssembly); + reader.Init(xmlReader, events, encodingStyle); return Deserialize(reader); } else @@ -823,7 +823,7 @@ internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping) private void SerializePrimitive(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces) { XmlSerializationPrimitiveWriter writer = new XmlSerializationPrimitiveWriter(); - writer.Init(xmlWriter, namespaces, null, null, null); + writer.Init(xmlWriter, namespaces, null, null); switch (Type.GetTypeCode(_primitiveType)) { case TypeCode.String: @@ -904,7 +904,7 @@ private void SerializePrimitive(XmlWriter xmlWriter, object? o, XmlSerializerNam private object? DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events) { XmlSerializationPrimitiveReader reader = new XmlSerializationPrimitiveReader(); - reader.Init(xmlReader, events, null, null); + reader.Init(xmlReader, events, null); object? o; switch (Type.GetTypeCode(_primitiveType)) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs index 557213c67f818..109b254dcdb76 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs @@ -70,7 +70,7 @@ public void Visit(QilExpression qil, GenerateHelper helper, MethodInfo methRoot) // Build the root expression _helper.MethodBegin(methRoot, null, true); - StartNestedIterator(qil.Root); + StartNestedIterator(); Visit(qil.Root); Debug.Assert(_iterCurr.Storage.Location == ItemLocation.None, "Root expression should have been pushed to the writer."); EndNestedIterator(qil.Root); @@ -141,7 +141,7 @@ private void VisitGlobalValues(QilList globalIterators) _helper.Emit(OpCodes.Brtrue, lblGetGlobal); // Compute value of global value - StartNestedIterator(iter); + StartNestedIterator(); if (param != null) { @@ -262,7 +262,7 @@ private void Function(QilFunction ndFunc) _helper.Emit(OpCodes.Brfalse, lblLocalComputed); // Compute default value of this parameter - StartNestedIterator(iter); + StartNestedIterator(); NestedVisitEnsureStack(iter.Binding, GetItemStorageType(iter), /*isCached:*/!iter.XmlType.IsSingleton); EndNestedIterator(iter); @@ -271,7 +271,7 @@ private void Function(QilFunction ndFunc) } } - StartNestedIterator(ndFunc); + StartNestedIterator(); // If function did not push results to writer, then function will return value(s) (rather than void) if (useWriter) @@ -624,19 +624,19 @@ protected override QilNode VisitAnd(QilBinary ndAnd) Label lblOnFalse; // Visit left branch - StartNestedIterator(ndAnd.Left); + StartNestedIterator(); lblOnFalse = StartConjunctiveTests(iterParent.CurrentBranchingContext, iterParent.LabelBranch); Visit(ndAnd.Left); EndNestedIterator(ndAnd.Left); // Visit right branch - StartNestedIterator(ndAnd.Right); + StartNestedIterator(); StartLastConjunctiveTest(iterParent.CurrentBranchingContext, iterParent.LabelBranch, lblOnFalse); Visit(ndAnd.Right); EndNestedIterator(ndAnd.Right); // End And expression - EndConjunctiveTests(iterParent.CurrentBranchingContext, iterParent.LabelBranch, lblOnFalse); + EndConjunctiveTests(iterParent.CurrentBranchingContext, lblOnFalse); return ndAnd; } @@ -689,7 +689,7 @@ private void StartLastConjunctiveTest(BranchingContext brctxt, Label lblBranch, /// /// Anchor any remaining labels. /// - private void EndConjunctiveTests(BranchingContext brctxt, Label lblBranch, Label lblOnFalse) + private void EndConjunctiveTests(BranchingContext brctxt, Label lblOnFalse) { switch (brctxt) { @@ -1080,7 +1080,7 @@ protected override QilNode VisitLength(QilUnary ndSetLen) // length = 0; _helper.Emit(OpCodes.Ldc_I4_0); - StartNestedIterator(ndSetLen.Child, lblOnEnd); + StartNestedIterator(lblOnEnd); // foreach (item in expr) { Visit(ndSetLen.Child); @@ -1391,7 +1391,7 @@ private QilNode CreateAggregator(QilUnary ndAgg, string aggName, XmlILStorageMet _helper.Call(methods.AggCreate!); // foreach (num in expr) { - StartNestedIterator(ndAgg.Child, lblOnEnd); + StartNestedIterator(lblOnEnd); _helper.Emit(OpCodes.Ldloca, locAgg); Visit(ndAgg.Child); @@ -1583,7 +1583,7 @@ private void GenerateConcat(QilNode ndStr, LocalBuilder locStringConcat) // str = each string; lblOnEnd = _helper.DefineLabel(); - StartNestedIterator(ndStr, lblOnEnd); + StartNestedIterator(lblOnEnd); Visit(ndStr); // strcat.Concat(str); @@ -1896,7 +1896,7 @@ protected override QilNode VisitFilter(QilLoop ndFilter) _iterCurr.SetIterator(_iterNested!); // If filter is false, skip the current item - StartNestedIterator(ndFilter.Body); + StartNestedIterator(); _iterCurr.SetBranching(BranchingContext.OnFalse, _iterCurr.ParentIterator!.GetLabelNext()); Visit(ndFilter.Body); EndNestedIterator(ndFilter.Body); @@ -2062,7 +2062,7 @@ private bool HandleFilterPatterns(QilLoop ndFilter) _helper.Emit(OpCodes.Ldloc, locIndex); // Generate code to iterate over the nodes which are being indexed ($iterNodes in the pattern) - StartNestedIterator(nodes, lblOnEnd); + StartNestedIterator(lblOnEnd); StartBinding(nodes); // Generate code to iterate over the keys for each node ($bindingKeys in the pattern) @@ -2141,9 +2141,9 @@ private void StartForBinding(QilIterator ndFor, OptimizerPatterns patt) // For expression iterator will be unnested as part of parent iterator if (_iterCurr.HasLabelNext) - StartNestedIterator(ndFor.Binding, _iterCurr.GetLabelNext()); + StartNestedIterator(_iterCurr.GetLabelNext()); else - StartNestedIterator(ndFor.Binding); + StartNestedIterator(); if (patt.MatchesPattern(OptimizerPatternName.IsPositional)) { @@ -2202,7 +2202,7 @@ public void StartLetBinding(QilIterator ndLet) Debug.Assert(!ndLet.XmlType!.IsSingleton); // Construct nested iterator - StartNestedIterator(ndLet); + StartNestedIterator(); // Allow base internal class to dispatch based on QilExpression node type NestedVisit(ndLet.Binding!, GetItemStorageType(ndLet), !ndLet.XmlType.IsSingleton); @@ -2280,7 +2280,7 @@ protected override QilNode VisitSort(QilLoop ndSort) // Construct nested iterator // foreach (item in sort-expr) { - StartNestedIterator(ndSort.Variable, lblOnEndSort); + StartNestedIterator(lblOnEndSort); StartBinding(ndSort.Variable); Debug.Assert(!_iterNested!.Storage.IsCached); @@ -2353,7 +2353,7 @@ private void VisitSortKey(QilSortKey ndKey, LocalBuilder locKeys) else { lblOnEndKey = _helper.DefineLabel(); - StartNestedIterator(ndKey.Key, lblOnEndKey); + StartNestedIterator(lblOnEndKey); Visit(ndKey.Key); _iterCurr.EnsureStackNoCache(); _iterCurr.EnsureItemStorageType(ndKey.Key.XmlType, GetItemStorageType(ndKey.Key)); @@ -2513,7 +2513,7 @@ private bool HandleDodPatterns(QilUnary ndDod) _helper.Call(XmlILMethods.DodMergeCreate); _helper.Emit(OpCodes.Ldloca, locMerge); - StartNestedIterator(ndDod.Child, lblOnEnd); + StartNestedIterator(lblOnEnd); // foreach (seq in expr) { Visit(ndDod.Child); @@ -3389,9 +3389,9 @@ protected override QilNode VisitIsEmpty(QilUnary ndIsEmpty) // Forward any LabelOnEnd jumps to LabelBranch if BranchingContext.OnTrue if (iterParent.CurrentBranchingContext == BranchingContext.OnTrue) - StartNestedIterator(ndIsEmpty.Child, _iterCurr.LabelBranch); + StartNestedIterator(_iterCurr.LabelBranch); else - StartNestedIterator(ndIsEmpty.Child, lblOnEnd); + StartNestedIterator(lblOnEnd); Visit(ndIsEmpty.Child); @@ -3451,7 +3451,7 @@ protected override QilNode VisitXPathNodeValue(QilUnary ndVal) lblOnEnd = _helper.DefineLabel(); // Construct nested iterator and iterate over results - StartNestedIterator(ndVal.Child, lblOnEnd); + StartNestedIterator(lblOnEnd); Visit(ndVal.Child); _iterCurr.EnsureStackNoCache(); @@ -3526,7 +3526,7 @@ protected override QilNode VisitXsltGenerateId(QilUnary ndGenId) lblOnEnd = _helper.DefineLabel(); // Construct nested iterator and iterate over results - StartNestedIterator(ndGenId.Child, lblOnEnd); + StartNestedIterator(lblOnEnd); Visit(ndGenId.Child); _iterCurr.EnsureStackNoCache(); _iterCurr.EnsureItemStorageType(ndGenId.Child.XmlType, typeof(XPathNavigator)); @@ -3995,7 +3995,7 @@ private void CreateContainerIterator(QilUnary ndDod, string iterName, Type iterT // Generate nested iterator (branch to lblOnEndNested when iteration is complete) lblOnEndNested = _helper.DefineLabel(); - StartNestedIterator(ndLoop, lblOnEndNested); + StartNestedIterator(lblOnEndNested); StartBinding(ndLoop.Variable); EndBinding(ndLoop.Variable); EndNestedIterator(ndLoop.Variable); @@ -4656,7 +4656,7 @@ private static bool IsNodeTypeUnion(XmlNodeKindFlags xmlTypes) /// current iterator. /// [MemberNotNull(nameof(_iterCurr))] - private void StartNestedIterator(QilNode? nd) + private void StartNestedIterator() { IteratorDescriptor? iterParent = _iterCurr; @@ -4679,9 +4679,9 @@ private void StartNestedIterator(QilNode? nd) /// Calls StartNestedIterator(nd) and also sets up the nested iterator to branch to "lblOnEnd" when iteration /// is complete. /// - private void StartNestedIterator(QilNode? nd, Label lblOnEnd) + private void StartNestedIterator(Label lblOnEnd) { - StartNestedIterator(nd); + StartNestedIterator(); _iterCurr.SetIterator(lblOnEnd, StorageDescriptor.None()); } @@ -4733,7 +4733,7 @@ private void NestedVisit(QilNode nd, Type itemStorageType, bool isCached) if (XmlILConstructInfo.Read(nd).PushToWriterLast) { // Push results to output, so nothing is left to store - StartNestedIterator(nd); + StartNestedIterator(); Visit(nd); EndNestedIterator(nd); _iterCurr.Storage = StorageDescriptor.None(); @@ -4741,7 +4741,7 @@ private void NestedVisit(QilNode nd, Type itemStorageType, bool isCached) else if (!isCached && nd.XmlType!.IsSingleton) { // Storage of result will be a non-cached singleton - StartNestedIterator(nd); + StartNestedIterator(); Visit(nd); _iterCurr.EnsureNoCache(); _iterCurr.EnsureItemStorageType(nd.XmlType, itemStorageType); @@ -4769,7 +4769,7 @@ private void NestedVisit(QilNode nd) private void NestedVisit(QilNode nd, Label lblOnEnd) { Debug.Assert(!XmlILConstructInfo.Read(nd).PushToWriterLast); - StartNestedIterator(nd, lblOnEnd); + StartNestedIterator(lblOnEnd); Visit(nd); _iterCurr.EnsureNoCache(); _iterCurr.EnsureItemStorageType(nd.XmlType!, GetItemStorageType(nd)); @@ -4822,7 +4822,7 @@ private void NestedVisitEnsureLocal(QilNode nd, LocalBuilder loc) private void NestedVisitWithBranch(QilNode nd, BranchingContext brctxt, Label lblBranch) { Debug.Assert(nd.XmlType!.IsSingleton && !XmlILConstructInfo.Read(nd).PushToWriterLast); - StartNestedIterator(nd); + StartNestedIterator(); _iterCurr.SetBranching(brctxt, lblBranch); Visit(nd); EndNestedIterator(nd); @@ -4845,7 +4845,7 @@ private void NestedVisitEnsureCache(QilNode nd, Type itemStorageType) // If bound expression will already be cached correctly, then don't create an XmlQuerySequence if (cachesResult) { - StartNestedIterator(nd); + StartNestedIterator(); Visit(nd); EndNestedIterator(nd); _iterCurr.Storage = _iterNested!.Storage; @@ -4890,7 +4890,7 @@ private void NestedVisitEnsureCache(QilNode nd, Type itemStorageType) _helper.Emit(OpCodes.Stloc, locCache); _helper.Emit(OpCodes.Ldloc, locCache); - StartNestedIterator(nd, lblOnEnd); + StartNestedIterator(lblOnEnd); if (cachesResult) _iterCurr.Storage = _iterCurr.ParentIterator!.Storage; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilFactory.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilFactory.cs index ccfac9993d9ff..8d116b332d17e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilFactory.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilFactory.cs @@ -238,7 +238,7 @@ public QilParameter Parameter(QilNode? defaultValue, QilNode? name, XmlQueryType public QilUnary PositionOf(QilNode child) { QilUnary n = new QilUnary(QilNodeType.PositionOf, child); - n.XmlType = QilTypeChecker.CheckPositionOf(n); + n.XmlType = QilTypeChecker.CheckPositionOf(); TraceNode(n); return n; } @@ -252,7 +252,7 @@ public QilUnary PositionOf(QilNode child) public QilNode True() { QilNode n = new QilNode(QilNodeType.True); - n.XmlType = QilTypeChecker.CheckTrue(n); + n.XmlType = QilTypeChecker.CheckTrue(); TraceNode(n); return n; } @@ -260,7 +260,7 @@ public QilNode True() public QilNode False() { QilNode n = new QilNode(QilNodeType.False); - n.XmlType = QilTypeChecker.CheckFalse(n); + n.XmlType = QilTypeChecker.CheckFalse(); TraceNode(n); return n; } @@ -390,7 +390,7 @@ public QilChoice Choice(QilNode expression, QilNode branches) public QilUnary Length(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Length, child); - n.XmlType = QilTypeChecker.CheckLength(n); + n.XmlType = QilTypeChecker.CheckLength(); TraceNode(n); return n; } @@ -710,7 +710,7 @@ public QilUnary Root(QilNode child) public QilNode XmlContext() { QilNode n = new QilNode(QilNodeType.XmlContext); - n.XmlType = QilTypeChecker.CheckXmlContext(n); + n.XmlType = QilTypeChecker.CheckXmlContext(); TraceNode(n); return n; } @@ -928,7 +928,7 @@ public QilTargetType IsType(QilNode source, QilNode targetType) public QilUnary IsEmpty(QilNode child) { QilUnary n = new QilUnary(QilNodeType.IsEmpty, child); - n.XmlType = QilTypeChecker.CheckIsEmpty(n); + n.XmlType = QilTypeChecker.CheckIsEmpty(); TraceNode(n); return n; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTypeChecker.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTypeChecker.cs index 3178d88d98d6f..75fc45da77543 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTypeChecker.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTypeChecker.cs @@ -44,10 +44,10 @@ public static XmlQueryType Check(QilNode n) QilNodeType.For => CheckFor((QilIterator)n), QilNodeType.Let => CheckLet((QilIterator)n), QilNodeType.Parameter => CheckParameter((QilParameter)n), - QilNodeType.PositionOf => CheckPositionOf((QilUnary)n), + QilNodeType.PositionOf => CheckPositionOf(), - QilNodeType.True => CheckTrue(n), - QilNodeType.False => CheckFalse(n), + QilNodeType.True => CheckTrue(), + QilNodeType.False => CheckFalse(), QilNodeType.LiteralString => CheckLiteralString((QilLiteral)n), QilNodeType.LiteralInt32 => CheckLiteralInt32((QilLiteral)n), QilNodeType.LiteralInt64 => CheckLiteralInt64((QilLiteral)n), @@ -64,7 +64,7 @@ public static XmlQueryType Check(QilNode n) QilNodeType.Conditional => CheckConditional((QilTernary)n), QilNodeType.Choice => CheckChoice((QilChoice)n), - QilNodeType.Length => CheckLength((QilUnary)n), + QilNodeType.Length => CheckLength(), QilNodeType.Sequence => CheckSequence((QilList)n), QilNodeType.Union => CheckUnion((QilBinary)n), QilNodeType.Intersection => CheckIntersection((QilBinary)n), @@ -110,7 +110,7 @@ public static XmlQueryType Check(QilNode n) QilNodeType.Attribute => CheckAttribute((QilBinary)n), QilNodeType.Parent => CheckParent((QilUnary)n), QilNodeType.Root => CheckRoot((QilUnary)n), - QilNodeType.XmlContext => CheckXmlContext(n), + QilNodeType.XmlContext => CheckXmlContext(), QilNodeType.Descendant => CheckDescendant((QilUnary)n), QilNodeType.DescendantOrSelf => CheckDescendantOrSelf((QilUnary)n), QilNodeType.Ancestor => CheckAncestor((QilUnary)n), @@ -138,7 +138,7 @@ public static XmlQueryType Check(QilNode n) QilNodeType.TypeAssert => CheckTypeAssert((QilTargetType)n), QilNodeType.IsType => CheckIsType((QilTargetType)n), - QilNodeType.IsEmpty => CheckIsEmpty((QilUnary)n), + QilNodeType.IsEmpty => CheckIsEmpty(), QilNodeType.XPathNodeValue => CheckXPathNodeValue((QilUnary)n), QilNodeType.XPathFollowing => CheckXPathFollowing((QilUnary)n), @@ -283,7 +283,7 @@ public static XmlQueryType CheckParameter(QilParameter node) return node.XmlType!; } - public static XmlQueryType CheckPositionOf(QilUnary node) + public static XmlQueryType CheckPositionOf() { return XmlQueryTypeFactory.IntX; } @@ -294,12 +294,12 @@ public static XmlQueryType CheckPositionOf(QilUnary node) //----------------------------------------------- // literals //----------------------------------------------- - public static XmlQueryType CheckTrue(QilNode node) + public static XmlQueryType CheckTrue() { return XmlQueryTypeFactory.BooleanX; } - public static XmlQueryType CheckFalse(QilNode node) + public static XmlQueryType CheckFalse() { return XmlQueryTypeFactory.BooleanX; } @@ -404,7 +404,7 @@ public static XmlQueryType CheckChoice(QilChoice node) //----------------------------------------------- // collection operators //----------------------------------------------- - public static XmlQueryType CheckLength(QilUnary node) + public static XmlQueryType CheckLength() { return XmlQueryTypeFactory.IntX; } @@ -707,7 +707,7 @@ public static XmlQueryType CheckRoot(QilUnary node) return XmlQueryTypeFactory.NodeNotRtf; } - public static XmlQueryType CheckXmlContext(QilNode node) + public static XmlQueryType CheckXmlContext() { return XmlQueryTypeFactory.NodeNotRtf; } @@ -884,7 +884,7 @@ public static XmlQueryType CheckIsType(QilTargetType node) return XmlQueryTypeFactory.BooleanX; } - public static XmlQueryType CheckIsEmpty(QilUnary node) + public static XmlQueryType CheckIsEmpty() { return XmlQueryTypeFactory.BooleanX; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs index f3021131a1a9f..ce0adbb961fd0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs @@ -1069,13 +1069,6 @@ internal static XPathNavigator SyncToNavigator(XPathNavigator? navigatorThis, XP /// public static int OnCurrentNodeChanged(XPathNavigator currentNode) { - IXmlLineInfo? lineInfo = currentNode as IXmlLineInfo; - - // In case of a namespace node, check whether it is inherited or locally defined - if (lineInfo != null && !(currentNode.NodeType == XPathNodeType.Namespace && IsInheritedNamespace(currentNode))) - { - OnCurrentNodeChanged2(currentNode.BaseURI, lineInfo.LineNumber, lineInfo.LinePosition); - } return 0; } @@ -1099,8 +1092,5 @@ private static bool IsInheritedNamespace(XPathNavigator node) } return true; } - - - private static void OnCurrentNodeChanged2(string baseUri, int lineNumber, int linePosition) { } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs index 1505819d3027f..c55df0af32c2f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs @@ -727,7 +727,7 @@ private QilNode CompileInstructions(IList instructions, int from, QilLi case XslNodeType.LiteralAttribute: result = CompileLiteralAttribute(node); break; case XslNodeType.LiteralElement: result = CompileLiteralElement(node); break; case XslNodeType.Message: result = CompileMessage(node); break; - case XslNodeType.Nop: result = CompileNop(node); break; + case XslNodeType.Nop: result = CompileNop(); break; case XslNodeType.Number: result = CompileNumber((Number)node); break; // case XslNodeType.Otherwise: wrapped by Choose // case XslNodeType.Param: already compiled by CompileProtoTemplate() @@ -781,7 +781,7 @@ private QilNode CompileList(XslNode node) return CompileInstructions(node.Content); } - private QilNode CompileNop(XslNode node) + private QilNode CompileNop() { return _f.Nop(_f.Sequence()); } @@ -2061,7 +2061,7 @@ private QilNode CompileGroupingSeparatorAttribute(string? attValue, bool fwdComp return result; } - private QilNode CompileGroupingSizeAttribute(string? attValue, bool fwdCompat) + private QilNode CompileGroupingSizeAttribute(string? attValue) { QilNode? result = CompileStringAvt(attValue); @@ -2128,7 +2128,7 @@ private QilNode CompileNumber(Number num) CompileLangAttributeToLcid(num.Lang, fwdCompat), CompileLetterValueAttribute(num.LetterValue, fwdCompat), CompileGroupingSeparatorAttribute(num.GroupingSeparator, fwdCompat), - CompileGroupingSizeAttribute(num.GroupingSize, fwdCompat) + CompileGroupingSizeAttribute(num.GroupingSize) )); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs index a0b2297a9bcd9..25fbf84a3fb9c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltLoader.cs @@ -417,11 +417,11 @@ private void LoadRealStylesheet() } else if (_input.IsKeyword(_atoms.Variable)) { - LoadGlobalVariableOrParameter(ctxInfo.nsList, XslNodeType.Variable); + LoadGlobalVariableOrParameter(ctxInfo.nsList); } else if (_input.IsKeyword(_atoms.Param)) { - LoadGlobalVariableOrParameter(ctxInfo.nsList, XslNodeType.Param); + LoadGlobalVariableOrParameter(ctxInfo.nsList); } else if (_input.IsKeyword(_atoms.Template)) { @@ -1118,7 +1118,7 @@ private void LoadAttributeSet(NsDecl? stylesheetNsList) set.AddContent(SetInfo(F.List(), LoadEndTag(content), ctxInfo)); } - private void LoadGlobalVariableOrParameter(NsDecl? stylesheetNsList, XslNodeType nodeType) + private void LoadGlobalVariableOrParameter(NsDecl? stylesheetNsList) { Debug.Assert(_curTemplate == null); Debug.Assert(_input.CanHaveApplyImports == false); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/AttributeAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/AttributeAction.cs index 5155e8931b80a..4da2d0d3ff4bb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/AttributeAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/AttributeAction.cs @@ -68,7 +68,7 @@ internal sealed class AttributeAction : ContainerAction internal override void Compile(Compiler compiler) { CompileAttributes(compiler); - CheckRequiredAttribute(compiler, _nameAvt, "name"); + CheckRequiredAttribute(_nameAvt, "name"); _name = PrecalculateAvt(ref _nameAvt); _nsUri = PrecalculateAvt(ref _nsAvt); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/AttributeSetAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/AttributeSetAction.cs index e21fe1f595f55..cea0912f2f8c9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/AttributeSetAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/AttributeSetAction.cs @@ -21,7 +21,7 @@ internal XmlQualifiedName? Name internal override void Compile(Compiler compiler) { CompileAttributes(compiler); - CheckRequiredAttribute(compiler, this.name, "name"); + CheckRequiredAttribute(this.name, "name"); CompileContent(compiler); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CallTemplateAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CallTemplateAction.cs index 1433b6af2e92c..fccac38af8317 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CallTemplateAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CallTemplateAction.cs @@ -17,7 +17,7 @@ internal sealed class CallTemplateAction : ContainerAction internal override void Compile(Compiler compiler) { CompileAttributes(compiler); - CheckRequiredAttribute(compiler, _name, "name"); + CheckRequiredAttribute(_name, "name"); CompileContent(compiler); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CompiledAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CompiledAction.cs index 6759b8fc7de03..05eed5b5ef6a8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CompiledAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CompiledAction.cs @@ -90,12 +90,12 @@ public static void CheckEmpty(Compiler compiler) } } - public static void CheckRequiredAttribute(Compiler compiler, object? attrValue, string attrName) + public static void CheckRequiredAttribute(object? attrValue, string attrName) { - CheckRequiredAttribute(compiler, attrValue != null, attrName); + CheckRequiredAttribute(attrValue != null, attrName); } - public static void CheckRequiredAttribute(Compiler compiler, bool attr, string attrName) + public static void CheckRequiredAttribute(bool attr, string attrName) { if (!attr) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs index 88482f1b7c66f..5e6efac9ff716 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Compiler.cs @@ -749,7 +749,7 @@ internal int AddBooleanQuery(string xpathQuery) // private readonly Hashtable[] _typeDeclsByLang = new Hashtable[] { new Hashtable(), new Hashtable(), new Hashtable() }; - internal void AddScript(string source, ScriptingLanguage lang, string ns, string fileName, int lineNumber) + internal void AddScript(ScriptingLanguage lang, string ns) { ValidateExtensionNamespace(ns); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ContainerAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ContainerAction.cs index 9c313860dcc33..991f48894f74b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ContainerAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ContainerAction.cs @@ -303,8 +303,8 @@ internal static void CompileNamespaceAlias(Compiler compiler) input.ToParent(); } - CheckRequiredAttribute(compiler, namespace1, "stylesheet-prefix"); - CheckRequiredAttribute(compiler, namespace2, "result-prefix"); + CheckRequiredAttribute(namespace1, "stylesheet-prefix"); + CheckRequiredAttribute(namespace2, "result-prefix"); CheckEmpty(compiler); //String[] resultarray = { prefix2, namespace2 }; @@ -353,9 +353,9 @@ internal static void CompileKey(Compiler compiler) input.ToParent(); } - CheckRequiredAttribute(compiler, MatchKey != Compiler.InvalidQueryKey, "match"); - CheckRequiredAttribute(compiler, UseKey != Compiler.InvalidQueryKey, "use"); - CheckRequiredAttribute(compiler, Name != null, "name"); + CheckRequiredAttribute(MatchKey != Compiler.InvalidQueryKey, "match"); + CheckRequiredAttribute(UseKey != Compiler.InvalidQueryKey, "use"); + CheckRequiredAttribute(Name != null, "name"); // It is a breaking change to check for emptiness, SQLBUDT 324364 //CheckEmpty(compiler); @@ -944,7 +944,7 @@ private static void AddScript(Compiler compiler) { throw XsltException.Create(SR.Xslt_ScriptEmpty); } - compiler.AddScript(input.Value, lang, implementsNamespace, input.BaseURI, input.LineNumber); + compiler.AddScript(lang, implementsNamespace); input.ToParent(); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyOfAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyOfAction.cs index ca8cc75c6a9fe..7a5d67d23dea2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyOfAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/CopyOfAction.cs @@ -19,7 +19,7 @@ internal sealed class CopyOfAction : CompiledAction internal override void Compile(Compiler compiler) { CompileAttributes(compiler); - CheckRequiredAttribute(compiler, _selectKey != Compiler.InvalidQueryKey, "select"); + CheckRequiredAttribute(_selectKey != Compiler.InvalidQueryKey, "select"); CheckEmpty(compiler); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ElementAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ElementAction.cs index a19d15990cbb4..9ddd3f452f9b0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ElementAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ElementAction.cs @@ -47,7 +47,7 @@ private static PrefixQName CreateElementQName(string name, string? nsUri, InputS internal override void Compile(Compiler compiler) { CompileAttributes(compiler); - CheckRequiredAttribute(compiler, _nameAvt, "name"); + CheckRequiredAttribute(_nameAvt, "name"); _name = PrecalculateAvt(ref _nameAvt); _nsUri = PrecalculateAvt(ref _nsAvt); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ForEachAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ForEachAction.cs index c9ae1d0b9ae15..5dd3007b853c4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ForEachAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ForEachAction.cs @@ -22,7 +22,7 @@ internal sealed class ForEachAction : ContainerAction internal override void Compile(Compiler compiler) { CompileAttributes(compiler); - CheckRequiredAttribute(compiler, _selectKey != Compiler.InvalidQueryKey, "select"); + CheckRequiredAttribute(_selectKey != Compiler.InvalidQueryKey, "select"); compiler.CanHaveApplyImports = false; if (compiler.Recurse()) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/IfAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/IfAction.cs index 3e31ad9897891..e90ce187478c4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/IfAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/IfAction.cs @@ -30,7 +30,7 @@ internal override void Compile(Compiler compiler) CompileAttributes(compiler); if (_type != ConditionType.ConditionOtherwise) { - CheckRequiredAttribute(compiler, _testKey != Compiler.InvalidQueryKey, "test"); + CheckRequiredAttribute(_testKey != Compiler.InvalidQueryKey, "test"); } if (compiler.Recurse()) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NumberAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NumberAction.cs index a862e985d4129..a9a3748305a8a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NumberAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/NumberAction.cs @@ -437,8 +437,6 @@ internal override void Execute(Processor processor, ActionFrame frame) /*CalculatingFormat:*/ frame.StoredOutput = Format(list, _formatAvt == null ? _formatTokens : ParseFormat(_formatAvt.Evaluate(processor, frame)), - _langAvt == null ? _lang : _langAvt.Evaluate(processor, frame), - _letterAvt == null ? _letter : ParseLetter(_letterAvt.Evaluate(processor, frame)), _groupingSepAvt == null ? _groupingSep : _groupingSepAvt.Evaluate(processor, frame), _groupingSizeAvt == null ? _groupingSize : _groupingSizeAvt.Evaluate(processor, frame) ); @@ -488,7 +486,7 @@ private static XPathNodeType BasicNodeType(XPathNodeType type) // in case of no AVTs we can build this object at compile time and reuse it on execution time. // even partial step in this derection will be usefull (when cFormats == 0) - private static string Format(ArrayList numberlist, List? tokens, string? lang, string? letter, string? groupingSep, string? groupingSize) + private static string Format(ArrayList numberlist, List? tokens, string? groupingSep, string? groupingSize) { StringBuilder result = new StringBuilder(); int cFormats = 0; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ProcessingInstructionAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ProcessingInstructionAction.cs index 4c11e72294099..42dfc0679f3d4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ProcessingInstructionAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ProcessingInstructionAction.cs @@ -20,7 +20,7 @@ internal ProcessingInstructionAction() { } internal override void Compile(Compiler compiler) { CompileAttributes(compiler); - CheckRequiredAttribute(compiler, _nameAvt, "name"); + CheckRequiredAttribute(_nameAvt, "name"); if (_nameAvt!.IsConstant) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ValueOfAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ValueOfAction.cs index 6c3f6b700a597..c174b09d20b1b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ValueOfAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ValueOfAction.cs @@ -26,7 +26,7 @@ internal static Action BuiltInRule() internal override void Compile(Compiler compiler) { CompileAttributes(compiler); - CheckRequiredAttribute(compiler, _selectKey != Compiler.InvalidQueryKey, "select"); + CheckRequiredAttribute(_selectKey != Compiler.InvalidQueryKey, "select"); CheckEmpty(compiler); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/VariableAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/VariableAction.cs index 3c3cfddf1b61a..e23f7c4498501 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/VariableAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/VariableAction.cs @@ -63,7 +63,7 @@ internal override void Compile(Compiler compiler) this.stylesheetid = compiler.Stylesheetid; this.baseUri = compiler.Input.BaseURI; CompileAttributes(compiler); - CheckRequiredAttribute(compiler, this.name, "name"); + CheckRequiredAttribute(this.name, "name"); if (compiler.Recurse()) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/WithParamAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/WithParamAction.cs index 7e5b659b4d9a2..7446f6a1370c7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/WithParamAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/WithParamAction.cs @@ -16,7 +16,7 @@ internal WithParamAction() : base(VariableType.WithParameter) { } internal override void Compile(Compiler compiler) { CompileAttributes(compiler); - CheckRequiredAttribute(compiler, this.name, "name"); + CheckRequiredAttribute(this.name, "name"); if (compiler.Recurse()) { CompileTemplate(compiler); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslCompiledTransform.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslCompiledTransform.cs index 4a734c289cb94..bc285e8844acf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslCompiledTransform.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XslCompiledTransform.cs @@ -139,7 +139,7 @@ private void LoadInternal(object stylesheet, XsltSettings? settings, XmlResolver } if (!settings.CheckOnly) { - CompileQilToMsil(settings); + CompileQilToMsil(); } } @@ -165,7 +165,7 @@ private void CompileXsltToQil(object stylesheet, XsltSettings settings, XmlResol return null; } - private void CompileQilToMsil(XsltSettings settings) + private void CompileQilToMsil() { _command = new XmlILGenerator().Generate(_qil!, null)!; OutputSettings = _command.StaticData.DefaultWriterSettings; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XsltContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XsltContext.cs index bd2b095cb4f4d..f34d4108d7d46 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XsltContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xslt/XsltContext.cs @@ -29,7 +29,7 @@ protected XsltContext(NameTable table) : base(table) { } protected XsltContext() : base(new NameTable()) { } // This dummy XsltContext that doesn't actualy initialize XmlNamespaceManager // is used by XsltCompileContext - internal XsltContext(bool dummy) : base() { } + internal XsltContext(bool _) : base() { } public abstract IXsltContextVariable ResolveVariable(string prefix, string name); public abstract IXsltContextFunction ResolveFunction(string prefix, string name, XPathResultType[] ArgTypes); public abstract bool Whitespace { get; } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/AttributeUtils.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/AttributeUtils.cs index 44be895c7f0af..deeda1521089e 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/AttributeUtils.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/AttributeUtils.cs @@ -88,7 +88,7 @@ public static object[] GetCustomAttributes(CustomReflectionContext context, Cust return CollectionServices.ConvertListToArray(results, attributeFilterType); } - public static object[] GetCustomAttributes(CustomReflectionContext context, CustomConstructorInfo constructor, Type attributeFilterType, bool inherit) + public static object[] GetCustomAttributes(CustomReflectionContext context, CustomConstructorInfo constructor, Type attributeFilterType) { ConstructorInfo provider = constructor.UnderlyingConstructor; IEnumerable attributes = GetFilteredAttributes(context, provider, attributeFilterType); @@ -96,7 +96,7 @@ public static object[] GetCustomAttributes(CustomReflectionContext context, Cust return CollectionServices.IEnumerableToArray(attributes, attributeFilterType); } - public static object[] GetCustomAttributes(CustomReflectionContext context, CustomPropertyInfo property, Type attributeFilterType, bool inherit) + public static object[] GetCustomAttributes(CustomReflectionContext context, CustomPropertyInfo property, Type attributeFilterType) { PropertyInfo provider = property.UnderlyingProperty; IEnumerable attributes = GetFilteredAttributes(context, provider, attributeFilterType); @@ -104,7 +104,7 @@ public static object[] GetCustomAttributes(CustomReflectionContext context, Cust return CollectionServices.IEnumerableToArray(attributes, attributeFilterType); } - public static object[] GetCustomAttributes(CustomReflectionContext context, CustomEventInfo evnt, Type attributeFilterType, bool inherit) + public static object[] GetCustomAttributes(CustomReflectionContext context, CustomEventInfo evnt, Type attributeFilterType) { EventInfo provider = evnt.UnderlyingEvent; IEnumerable attributes = GetFilteredAttributes(context, provider, attributeFilterType); @@ -112,7 +112,7 @@ public static object[] GetCustomAttributes(CustomReflectionContext context, Cust return CollectionServices.IEnumerableToArray(attributes, attributeFilterType); } - public static object[] GetCustomAttributes(CustomReflectionContext context, CustomFieldInfo field, Type attributeFilterType, bool inherit) + public static object[] GetCustomAttributes(CustomReflectionContext context, CustomFieldInfo field, Type attributeFilterType) { FieldInfo provider = field.UnderlyingField; IEnumerable attributes = GetFilteredAttributes(context, provider, attributeFilterType); @@ -120,7 +120,7 @@ public static object[] GetCustomAttributes(CustomReflectionContext context, Cust return CollectionServices.IEnumerableToArray(attributes, attributeFilterType); } - public static object[] GetCustomAttributes(CustomReflectionContext context, CustomParameterInfo parameter, Type attributeFilterType, bool inherit) + public static object[] GetCustomAttributes(CustomReflectionContext context, CustomParameterInfo parameter, Type attributeFilterType) { ParameterInfo provider = parameter.UnderlyingParameter; IEnumerable attributes = GetFilteredAttributes(context, provider, attributeFilterType); diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomConstructorInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomConstructorInfo.cs index f1a65cf18ec8c..bac273ecb6fb0 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomConstructorInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomConstructorInfo.cs @@ -24,7 +24,7 @@ public override object[] GetCustomAttributes(bool inherit) public override object[] GetCustomAttributes(Type attributeType, bool inherit) { - return AttributeUtils.GetCustomAttributes(ReflectionContext, this, attributeType, inherit); + return AttributeUtils.GetCustomAttributes(ReflectionContext, this, attributeType); } public override bool IsDefined(Type attributeType, bool inherit) diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomEventInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomEventInfo.cs index e14c82ef5616f..9b5f5890b3398 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomEventInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomEventInfo.cs @@ -24,7 +24,7 @@ public override object[] GetCustomAttributes(bool inherit) public override object[] GetCustomAttributes(Type attributeType, bool inherit) { - return AttributeUtils.GetCustomAttributes(ReflectionContext, this, attributeType, inherit); + return AttributeUtils.GetCustomAttributes(ReflectionContext, this, attributeType); } public override bool IsDefined(Type attributeType, bool inherit) diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomFieldInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomFieldInfo.cs index 764a9dcb46a9f..d799d1afcf224 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomFieldInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomFieldInfo.cs @@ -24,7 +24,7 @@ public override object[] GetCustomAttributes(bool inherit) public override object[] GetCustomAttributes(Type attributeType, bool inherit) { - return AttributeUtils.GetCustomAttributes(ReflectionContext, this, attributeType, inherit); + return AttributeUtils.GetCustomAttributes(ReflectionContext, this, attributeType); } public override bool IsDefined(Type attributeType, bool inherit) diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomParameterInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomParameterInfo.cs index ba2229c3ee730..a7dd2e5de53ec 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomParameterInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomParameterInfo.cs @@ -24,7 +24,7 @@ public override object[] GetCustomAttributes(bool inherit) public override object[] GetCustomAttributes(Type attributeType, bool inherit) { - return AttributeUtils.GetCustomAttributes(ReflectionContext, this, attributeType, inherit); + return AttributeUtils.GetCustomAttributes(ReflectionContext, this, attributeType); } public override bool IsDefined(Type attributeType, bool inherit) diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomPropertyInfo.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomPropertyInfo.cs index 396404af651dc..3bf458ef43a30 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomPropertyInfo.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Custom/CustomPropertyInfo.cs @@ -24,7 +24,7 @@ public override object[] GetCustomAttributes(bool inherit) public override object[] GetCustomAttributes(Type attributeType, bool inherit) { - return AttributeUtils.GetCustomAttributes(ReflectionContext, this, attributeType, inherit); + return AttributeUtils.GetCustomAttributes(ReflectionContext, this, attributeType); } public override bool IsDefined(Type attributeType, bool inherit) diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/PathUtilities.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/PathUtilities.cs index e00e510ff412a..b865428bc9aa4 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/PathUtilities.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/PathUtilities.cs @@ -46,7 +46,7 @@ internal static int IndexOfFileName(string path) /// Get file name from path. /// /// Unlike this method doesn't check for invalid path characters. - internal static string GetFileName(string path, bool includeExtension = true) + internal static string GetFileName(string path) { int fileNameStart = IndexOfFileName(path); return (fileNameStart <= 0) ? path : path.Substring(fileNameStart); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEHeaders.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEHeaders.cs index ac490b2ef19a8..9ea27a83cc998 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEHeaders.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEHeaders.cs @@ -104,7 +104,7 @@ public PEHeaders(Stream peStream, int size, bool isLoadedImage) if (!isCoffOnly) { int offset; - if (TryCalculateCorHeaderOffset(actualSize, out offset)) + if (TryCalculateCorHeaderOffset(out offset)) { _corHeaderStartOffset = offset; reader.Seek(offset); @@ -229,7 +229,7 @@ public bool IsExe } } - private bool TryCalculateCorHeaderOffset(long peStreamSize, out int startOffset) + private bool TryCalculateCorHeaderOffset(out int startOffset) { if (!TryGetDirectoryOffset(_peHeader!.CorHeaderTableDirectory, out startOffset, canCrossSectionBoundary: false)) { diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/CoreRtBridge.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/CoreRtBridge.cs index 7ed72567959e6..75a6ad93ccc90 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/CoreRtBridge.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/CoreRtBridge.cs @@ -16,8 +16,6 @@ internal static class RoShims { internal static RoType CastToRuntimeTypeInfo(this Type t) => (RoType)t; - internal static bool CanBrowseWithoutMissingMetadataExceptions(this Type t) => true; - internal static Type[] GetGenericTypeParameters(this Type t) { Debug.Assert(t.IsGenericTypeDefinition); @@ -33,7 +31,7 @@ internal static class ReflectionCoreExecution internal static class ExecutionDomain { // We'll never actually reach this since Ro type objects cannot trigger missing metadata exceptions. - internal static Exception CreateMissingMetadataException(Type t) => new Exception(); + internal static Exception CreateMissingMetadataException() => new Exception(); } } } diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/DefaultBinder.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/DefaultBinder.cs index 8d0dbcea5ec8a..e74384109ba34 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/DefaultBinder.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/DefaultBinder.cs @@ -269,7 +269,7 @@ public sealed override MethodBase BindToMethod( // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) - public static MethodBase? ExactBinding(MethodBase[] match, Type[] types, ParameterModifier[]? modifiers) + public static MethodBase? ExactBinding(MethodBase[] match, Type[] types) { if (match is null) { @@ -314,7 +314,7 @@ public sealed override MethodBase BindToMethod( // Return any exact bindings that may exist. (This method is not defined on the // Binder and is used by RuntimeType.) - public static PropertyInfo? ExactPropertyBinding(PropertyInfo[] match, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) + public static PropertyInfo? ExactPropertyBinding(PropertyInfo[] match, Type? returnType, Type[]? types) { if (match is null) { diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/QueriedMemberList.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/QueriedMemberList.cs index 2dd5adecadde1..8bc70504eabb3 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/QueriedMemberList.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/QueriedMemberList.cs @@ -50,7 +50,7 @@ public int TotalCount get { if (_typeThatBlockedBrowsing != null) - throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(_typeThatBlockedBrowsing); + throw ReflectionCoreExecution.ExecutionDomain.CreateMissingMetadataException(); return _totalCount; } } @@ -157,15 +157,6 @@ public static QueriedMemberList Create(RuntimeTypeInfo type, string? filter, } type = type.BaseType!.CastToRuntimeTypeInfo(); - if (type != null && !type.CanBrowseWithoutMissingMetadataExceptions()) - { - // If we got here, one of the base classes is missing metadata. We don't want to throw a MissingMetadataException now because we may be - // building a cached result for a caller who passed BindingFlags.DeclaredOnly. So we'll mark the results in a way that - // it will throw a MissingMetadataException if a caller attempts to iterate past the declared-only subset. - queriedMembers._typeThatBlockedBrowsing = type; - queriedMembers._totalCount = queriedMembers._declaredOnlyCount; - break; - } } return queriedMembers; diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/TypeExtensions.netstandard.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/TypeExtensions.netstandard.cs index bab4ee7c7353d..3ecea03111f93 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/TypeExtensions.netstandard.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/General/TypeExtensions.netstandard.cs @@ -9,7 +9,7 @@ namespace System.Reflection.TypeLoading internal static class NetCoreApiEmulators { // On NetStandard, have to do with slower emulations. - +#pragma warning disable IDE0060 public static bool IsSignatureType(this Type type) => false; public static bool IsSZArray(this Type type) => type.IsArray && type.GetArrayRank() == 1 && type.Name.EndsWith("[]", StringComparison.Ordinal); public static bool IsVariableBoundArray(this Type type) => type.IsArray && !type.IsSZArray(); @@ -17,6 +17,7 @@ internal static class NetCoreApiEmulators // Signature Types do not exist on NetStandard 2.0 but it's possible we could reach this if a NetCore app uses the NetStandard build of this library. public static Type MakeSignatureGenericType(this Type genericTypeDefinition, Type[] typeArguments) => throw new NotSupportedException(SR.NotSupported_MakeGenericType_SignatureTypes); +#pragma warning restore IDE0060 } /// diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.BindingFlags.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.BindingFlags.cs index 8644574be03fe..89e092d3dfe67 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.BindingFlags.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/RuntimeTypeInfo.BindingFlags.cs @@ -36,7 +36,7 @@ internal abstract partial class RoType } if ((bindingAttr & BindingFlags.ExactBinding) != 0) - return System.DefaultBinder.ExactBinding(candidates.ToArray(), types, modifiers) as ConstructorInfo; + return System.DefaultBinder.ExactBinding(candidates.ToArray(), types) as ConstructorInfo; binder ??= Loader.GetDefaultBinder(); @@ -153,7 +153,7 @@ internal abstract partial class RoType } if ((bindingAttr & BindingFlags.ExactBinding) != 0) - return System.DefaultBinder.ExactPropertyBinding(candidates.ToArray(), returnType, types, modifiers); + return System.DefaultBinder.ExactPropertyBinding(candidates.ToArray(), returnType, types); binder ??= Loader.GetDefaultBinder(); diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheMemoryMonitor.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheMemoryMonitor.cs index e0c0f4a42402c..a0294251fc5ba 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheMemoryMonitor.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheMemoryMonitor.cs @@ -60,7 +60,7 @@ private void InitDisposableMembers(int cacheMemoryLimitMegabytes) bool dispose = true; try { - _sizedRefMultiple = new SRefMultiple(_memoryCache.AllSRefTargets); + _sizedRefMultiple = new SRefMultiple(); SetLimit(cacheMemoryLimitMegabytes); InitHistory(); dispose = false; diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/Counters.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/Counters.cs index 7385f82d91280..8d3f7237d27af 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/Counters.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/Counters.cs @@ -23,10 +23,10 @@ internal sealed class Counters : EventSource internal Counters(string cacheName) : base(EVENT_SOURCE_NAME_ROOT + (cacheName ?? throw new ArgumentNullException(nameof(cacheName)))) { - InitDisposableMembers(cacheName); + InitDisposableMembers(); } - private void InitDisposableMembers(string cacheName) + private void InitDisposableMembers() { bool dispose = true; @@ -102,7 +102,7 @@ internal void Decrement(CounterName name) Interlocked.Decrement(ref _counterValues[idx]); } #else -#pragma warning disable CA1822 +#pragma warning disable CA1822, IDE0060 internal Counters(string cacheName) { } @@ -118,7 +118,7 @@ internal void IncrementBy(CounterName name, long value) internal void Decrement(CounterName name) { } -#pragma warning restore CA1822 +#pragma warning restore CA1822, IDE0060 #endif } } diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/SRef.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/SRef.cs index 118fe1f9c9190..9a09ba1d9781a 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/SRef.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/SRef.cs @@ -13,7 +13,7 @@ namespace System.Runtime.Caching // until then we provide a stub internal sealed class SRefMultiple { - internal SRefMultiple(object[] targets) + internal SRefMultiple() { } diff --git a/src/libraries/System.Runtime.CompilerServices.VisualC/src/System/Runtime/CompilerServices/Attributes.cs b/src/libraries/System.Runtime.CompilerServices.VisualC/src/System/Runtime/CompilerServices/Attributes.cs index 1261bee6b888a..b4651794acf55 100644 --- a/src/libraries/System.Runtime.CompilerServices.VisualC/src/System/Runtime/CompilerServices/Attributes.cs +++ b/src/libraries/System.Runtime.CompilerServices.VisualC/src/System/Runtime/CompilerServices/Attributes.cs @@ -6,6 +6,8 @@ // these types publicly. [assembly:System.Runtime.CompilerServices.InternalsVisibleTo("mscorlib, PublicKey=00000000000000000400000000000000")] +#pragma warning disable IDE0060 + namespace System.Runtime.CompilerServices { // Types used by the C++/CLI compiler during linking. diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportGenerator.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportGenerator.cs index 4a387419f8128..690038389d32e 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportGenerator.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/gen/JSImportGenerator/JSImportGenerator.cs @@ -103,7 +103,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context) .WithTrackingName(StepNames.CalculateStubInformation) .Combine(stubOptions) .Select( - static (data, ct) => GenerateSource(data.Left, data.Right) + static (data, ct) => GenerateSource(data.Left) ) .WithComparer(Comparers.GeneratedSyntax) .WithTrackingName(StepNames.GenerateSingleStub); @@ -222,8 +222,7 @@ private static IncrementalStubGenerationContext CalculateStubInformation( } private static (MemberDeclarationSyntax, ImmutableArray) GenerateSource( - IncrementalStubGenerationContext incrementalContext, - JSGeneratorOptions options) + IncrementalStubGenerationContext incrementalContext) { var diagnostics = new GeneratorDiagnostics(); diff --git a/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSObject.References.cs b/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSObject.References.cs index 0df7811b7960b..17622520a01a1 100644 --- a/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSObject.References.cs +++ b/src/libraries/System.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/JSObject.References.cs @@ -63,7 +63,7 @@ internal void ReleaseInFlight() /// public override string ToString() => $"(js-obj js '{JSHandle}')"; - private void Dispose(bool disposing) + private void DisposeThis() { if (!_isDisposed) { @@ -75,7 +75,7 @@ private void Dispose(bool disposing) ~JSObject() { - Dispose(disposing: false); + DisposeThis(); } /// @@ -83,7 +83,7 @@ private void Dispose(bool disposing) /// public void Dispose() { - Dispose(disposing: true); + DisposeThis(); GC.SuppressFinalize(this); } } diff --git a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/CustomMarshallerAttributeAnalyzer.cs b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/CustomMarshallerAttributeAnalyzer.cs index d9b513cc1769a..4dc6b87e10c07 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/CustomMarshallerAttributeAnalyzer.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/CustomMarshallerAttributeAnalyzer.cs @@ -984,7 +984,9 @@ private bool TryGetElementTypeFromSpanType(ITypeSymbol spanTypeMaybe, [NotNullWh return false; } +#pragma warning disable CA1822, IDE0060 private void AnalyzeStatefulMarshallerType(DiagnosticReporter diagnosticReporter, ITypeSymbol managedType, MarshalMode mode, INamedTypeSymbol marshallerType, bool isLinearCollectionMarshaller) +#pragma warning restore CA1822, IDE0060 { if (mode is MarshalMode.ElementIn or MarshalMode.ElementRef diff --git a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/CustomMarshallerAttributeFixer.cs b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/CustomMarshallerAttributeFixer.cs index 22d34aa852c66..f359104671542 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/CustomMarshallerAttributeFixer.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/CustomMarshallerAttributeFixer.cs @@ -156,6 +156,7 @@ private static void IgnoreArityMismatch(INamedTypeSymbol marshallerType, INamedT { } +#pragma warning disable IDE0060 private static async Task AddMissingMembers(Document doc, SyntaxNode node, HashSet missingMemberNames, CancellationToken ct) { var model = await doc.GetSemanticModelAsync(ct).ConfigureAwait(false); @@ -575,5 +576,6 @@ private static SyntaxNode DefaultMethodStatement(SyntaxGenerator generator, Comp generator.TypeExpression( compilation.GetTypeByMetadataName("System.NotImplementedException")))); } +#pragma warning disable IDE0060 } } diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshalUsingAttributeParser.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshalUsingAttributeParser.cs index 14d60d3c9ce90..e1bc06268be72 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshalUsingAttributeParser.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshalUsingAttributeParser.cs @@ -64,12 +64,12 @@ public MarshalUsingAttributeParser(Compilation compilation, IGeneratorDiagnostic UseSiteAttributeData IUseSiteAttributeParser.ParseAttribute(AttributeData attributeData, IElementInfoProvider elementInfoProvider, GetMarshallingInfoCallback marshallingInfoCallback) { ImmutableDictionary namedArgs = ImmutableDictionary.CreateRange(attributeData.NamedArguments); - CountInfo countInfo = ParseCountInfo(attributeData, namedArgs, elementInfoProvider, marshallingInfoCallback); + CountInfo countInfo = ParseCountInfo(attributeData, elementInfoProvider, marshallingInfoCallback); int elementIndirectionDepth = namedArgs.TryGetValue(ManualTypeMarshallingHelper.MarshalUsingProperties.ElementIndirectionDepth, out TypedConstant value) ? (int)value.Value! : 0; return new UseSiteAttributeData(elementIndirectionDepth, countInfo, attributeData); } - private CountInfo ParseCountInfo(AttributeData attributeData, ImmutableDictionary namedArguments, IElementInfoProvider elementInfoProvider, GetMarshallingInfoCallback marshallingInfoCallback) + private CountInfo ParseCountInfo(AttributeData attributeData, IElementInfoProvider elementInfoProvider, GetMarshallingInfoCallback marshallingInfoCallback) { int? constSize = null; string? elementName = null; diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshallerShape.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshallerShape.cs index e87b1cb903221..be8e9dd34a6f5 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshallerShape.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshallerShape.cs @@ -143,7 +143,7 @@ public static (MarshallerShape, MarshallerMethods) GetShapeForType(ITypeSymbol m // Unmanaged -> Managed IMethodSymbol? allocateManaged = LinearCollection.AllocateContainerForManagedElements(marshallerType, managedType); - IMethodSymbol? allocateManagedGuaranteed = LinearCollection.AllocateContainerForManagedElementsFinally(marshallerType, managedType, spanOfT); + IMethodSymbol? allocateManagedGuaranteed = LinearCollection.AllocateContainerForManagedElementsFinally(marshallerType, managedType); IMethodSymbol? managedDestination = LinearCollection.GetManagedValuesDestination(marshallerType, managedType, spanOfT); IMethodSymbol? unmanagedSource = LinearCollection.GetUnmanagedValuesSource(marshallerType, readOnlySpanOfT); if ((allocateManaged is not null || allocateManagedGuaranteed is not null) @@ -368,7 +368,7 @@ private static class LinearCollection && managedType.IsConstructedFromEqualTypes(m.ReturnType)); } - internal static IMethodSymbol? AllocateContainerForManagedElementsFinally(ITypeSymbol type, ITypeSymbol managedType, ITypeSymbol spanOfT) + internal static IMethodSymbol? AllocateContainerForManagedElementsFinally(ITypeSymbol type, ITypeSymbol managedType) { // static TCollection AllocateContainerForManagedElementsFinally(TNative unmanaged, int length); return type.GetMembers(ShapeMemberNames.LinearCollection.Stateless.AllocateContainerForManagedElementsFinally) @@ -498,7 +498,7 @@ public static (MarshallerShape shape, MarshallerMethods methods) GetShapeForType IMethodSymbol? unmanagedSource = null; if (isLinearCollectionMarshaller) { - managedDestination = LinearCollection.GetManagedValuesDestination(marshallerType, managedType, spanOfT); + managedDestination = LinearCollection.GetManagedValuesDestination(marshallerType, spanOfT); unmanagedSource = LinearCollection.GetUnmanagedValuesSource(marshallerType, readOnlySpanOfT); } @@ -700,7 +700,7 @@ private static class LinearCollection && SymbolEqualityComparer.Default.Equals(spanOfT, returnType.ConstructedFrom)); } - internal static IMethodSymbol? GetManagedValuesDestination(ITypeSymbol type, ITypeSymbol managedType, ITypeSymbol spanOfT) + internal static IMethodSymbol? GetManagedValuesDestination(ITypeSymbol type, ITypeSymbol spanOfT) { // static Span GetManagedValuesDestination(int numElements) return type.GetMembers(ShapeMemberNames.LinearCollection.Stateful.GetManagedValuesDestination) diff --git a/src/libraries/System.Runtime.Serialization.Formatters/src/System.Runtime.Serialization.Formatters.csproj b/src/libraries/System.Runtime.Serialization.Formatters/src/System.Runtime.Serialization.Formatters.csproj index a9438b21825df..bbb10a1f4ce4b 100644 --- a/src/libraries/System.Runtime.Serialization.Formatters/src/System.Runtime.Serialization.Formatters.csproj +++ b/src/libraries/System.Runtime.Serialization.Formatters/src/System.Runtime.Serialization.Formatters.csproj @@ -10,7 +10,7 @@ $(TargetFramework.SubString($([MSBuild]::Add($(TargetFramework.IndexOf('-')), 1)))) $(NoWarn);CS0649 - $(NoWarn);CA1822 + $(NoWarn);CA1822;IDE0060 diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/Rfc3161Accuracy.xml b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/Rfc3161Accuracy.xml index d415b623dd6c5..ebe9b772cd03f 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/Rfc3161Accuracy.xml +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/Rfc3161Accuracy.xml @@ -2,7 +2,8 @@ + namespace="System.Security.Cryptography.Pkcs.Asn1" + rebind="false"> - - + + diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/Asn1/ValidityAsn.xml.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/Asn1/ValidityAsn.xml.cs index 609da224e8f36..6d2eca88864a8 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/Asn1/ValidityAsn.xml.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/Asn1/ValidityAsn.xml.cs @@ -39,7 +39,7 @@ internal static ValidityAsn Decode(Asn1Tag expectedTag, ReadOnlyMemory enc { AsnValueReader reader = new AsnValueReader(encoded.Span, ruleSet); - DecodeCore(ref reader, expectedTag, encoded, out ValidityAsn decoded); + DecodeCore(ref reader, expectedTag, out ValidityAsn decoded); reader.ThrowIfNotEmpty(); return decoded; } @@ -49,16 +49,16 @@ internal static ValidityAsn Decode(Asn1Tag expectedTag, ReadOnlyMemory enc } } - internal static void Decode(ref AsnValueReader reader, ReadOnlyMemory rebind, out ValidityAsn decoded) + internal static void Decode(ref AsnValueReader reader, out ValidityAsn decoded) { - Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded); + Decode(ref reader, Asn1Tag.Sequence, out decoded); } - internal static void Decode(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out ValidityAsn decoded) + internal static void Decode(ref AsnValueReader reader, Asn1Tag expectedTag, out ValidityAsn decoded) { try { - DecodeCore(ref reader, expectedTag, rebind, out decoded); + DecodeCore(ref reader, expectedTag, out decoded); } catch (AsnContentException e) { @@ -66,13 +66,13 @@ internal static void Decode(ref AsnValueReader reader, Asn1Tag expectedTag, Read } } - private static void DecodeCore(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory rebind, out ValidityAsn decoded) + private static void DecodeCore(ref AsnValueReader reader, Asn1Tag expectedTag, out ValidityAsn decoded) { decoded = default; AsnValueReader sequenceReader = reader.ReadSequence(expectedTag); - System.Security.Cryptography.X509Certificates.Asn1.TimeAsn.Decode(ref sequenceReader, rebind, out decoded.NotBefore); - System.Security.Cryptography.X509Certificates.Asn1.TimeAsn.Decode(ref sequenceReader, rebind, out decoded.NotAfter); + System.Security.Cryptography.X509Certificates.Asn1.TimeAsn.Decode(ref sequenceReader, out decoded.NotBefore); + System.Security.Cryptography.X509Certificates.Asn1.TimeAsn.Decode(ref sequenceReader, out decoded.NotAfter); sequenceReader.ThrowIfNotEmpty(); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificatePal.NotSupported.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificatePal.NotSupported.cs index eb782130613cf..54c09916f5294 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificatePal.NotSupported.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificatePal.NotSupported.cs @@ -7,6 +7,7 @@ namespace System.Security.Cryptography.X509Certificates { internal static partial class CertificatePal { +#pragma warning disable IDE0060 internal static partial ICertificatePal FromHandle(IntPtr handle) { throw new PlatformNotSupportedException(SR.SystemSecurityCryptographyX509Certificates_PlatformNotSupported); @@ -32,5 +33,6 @@ internal static partial ICertificatePal FromFile( { throw new PlatformNotSupportedException(SR.SystemSecurityCryptographyX509Certificates_PlatformNotSupported); } +#pragma warning restore IDE0060 } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificatePolicy.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificatePolicy.cs index 321348e91968f..db1a0ae21dd43 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificatePolicy.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificatePolicy.cs @@ -375,7 +375,7 @@ private static List ReadCertPolicyMappingsExtension List mappings = new List(); while (sequenceReader.HasData) { - CertificatePolicyMappingAsn.Decode(ref sequenceReader, rawData, out CertificatePolicyMappingAsn mapping); + CertificatePolicyMappingAsn.Decode(ref sequenceReader, out CertificatePolicyMappingAsn mapping); mappings.Add(mapping); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Android.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Android.cs index 99f807e63fb20..63c4ff763dac7 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Android.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Android.cs @@ -13,6 +13,7 @@ namespace System.Security.Cryptography.X509Certificates { internal sealed partial class ChainPal { +#pragma warning disable IDE0060 internal static partial IChainPal FromHandle(IntPtr chainContext) { throw new PlatformNotSupportedException(); @@ -50,6 +51,7 @@ internal static partial bool ReleaseSafeX509ChainHandle(IntPtr handle) } return chainPal; +#pragma warning restore IDE0060 } private sealed class AndroidCertPath : IChainPal diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Apple.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Apple.cs index abcfad67c6206..7c3ab59031980 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Apple.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.Apple.cs @@ -548,6 +548,7 @@ private X509ChainErrorMapping(X509ChainStatusFlags flag) internal sealed partial class ChainPal { +#pragma warning disable IDE0060 internal static partial IChainPal FromHandle(IntPtr chainContext) { // This is possible to do on Apple's platform, but is tricky in execution. @@ -637,5 +638,6 @@ internal static partial bool ReleaseSafeX509ChainHandle(IntPtr handle) return chainPal; } +#pragma warning restore IDE0060 } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.NotSupported.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.NotSupported.cs index fd6bf95e4baa3..b687b3d4fc46a 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.NotSupported.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.NotSupported.cs @@ -5,6 +5,7 @@ namespace System.Security.Cryptography.X509Certificates { internal static partial class ChainPal { +#pragma warning disable IDE0060 internal static partial IChainPal FromHandle(IntPtr chainContext) { throw new PlatformNotSupportedException(SR.SystemSecurityCryptographyX509Certificates_PlatformNotSupported); @@ -31,5 +32,6 @@ internal static partial bool ReleaseSafeX509ChainHandle(IntPtr handle) { throw new PlatformNotSupportedException(SR.SystemSecurityCryptographyX509Certificates_PlatformNotSupported); } +#pragma warning restore IDE0060 } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.OpenSsl.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.OpenSsl.cs index 45504e5c706e7..e45e3d938b996 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.OpenSsl.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/ChainPal.OpenSsl.cs @@ -10,6 +10,7 @@ internal sealed partial class ChainPal { private static readonly TimeSpan s_maxUrlRetrievalTimeout = TimeSpan.FromMinutes(1); +#pragma warning disable IDE0060 internal static partial IChainPal FromHandle(IntPtr chainContext) { throw new PlatformNotSupportedException(); @@ -19,6 +20,7 @@ internal static partial bool ReleaseSafeX509ChainHandle(IntPtr handle) { return true; } +#pragma warning restore IDE0060 public static void FlushStores() { @@ -235,7 +237,7 @@ private static void SaveIntermediateCertificates(List download if (OpenSslX509ChainEventSource.Log.IsEnabled()) { - OpenSslX509ChainEventSource.Log.CachingIntermediateFailed(cert); + OpenSslX509ChainEventSource.Log.CachingIntermediateFailedMessage(); } } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/FindPal.NotSupported.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/FindPal.NotSupported.cs index 0c3dd97f84219..470eed27283e7 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/FindPal.NotSupported.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/FindPal.NotSupported.cs @@ -5,9 +5,11 @@ namespace System.Security.Cryptography.X509Certificates { internal static partial class FindPal { +#pragma warning disable IDE0060 private static partial IFindPal OpenPal(X509Certificate2Collection findFrom, X509Certificate2Collection copyTo, bool validOnly) { throw new PlatformNotSupportedException(SR.SystemSecurityCryptographyX509Certificates_PlatformNotSupported); } +#pragma warning restore IDE0060 } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/OpenSslX509ChainEventSource.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/OpenSslX509ChainEventSource.cs index 0fc2b4e8c1679..b8b105197980a 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/OpenSslX509ChainEventSource.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/OpenSslX509ChainEventSource.cs @@ -685,11 +685,11 @@ private void CachingIntermediate(string subjectName) } [NonEvent] - internal void CachingIntermediateFailed(X509Certificate2 certificate) + internal void CachingIntermediateFailedMessage() { if (IsEnabled()) { - CachingIntermediateFailed(certificate.Subject); + CachingIntermediateFailed(); } } @@ -697,7 +697,7 @@ internal void CachingIntermediateFailed(X509Certificate2 certificate) EventId_CachingIntermediateFailed, Level = EventLevel.Warning, Message = "Adding the downloaded intermediate '{0}' to the CurrentUser\\CA store failed.")] - private void CachingIntermediateFailed(string subjectName) + private void CachingIntermediateFailed() { WriteEvent(EventId_CachingIntermediateFailed); } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.NotSupported.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.NotSupported.cs index 2b7706b4a7a63..af02c918cda5a 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.NotSupported.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.NotSupported.cs @@ -7,6 +7,7 @@ namespace System.Security.Cryptography.X509Certificates { internal static partial class StorePal { +#pragma warning disable IDE0060 internal static partial IStorePal FromHandle(IntPtr storeHandle) { throw new PlatformNotSupportedException(SR.SystemSecurityCryptographyX509Certificates_PlatformNotSupported); @@ -46,5 +47,6 @@ internal static partial IStorePal FromSystemStore( { throw new PlatformNotSupportedException(SR.SystemSecurityCryptographyX509Certificates_PlatformNotSupported); } +#pragma warning restore IDE0060 } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.OpenSsl.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.OpenSsl.cs index e1c4a49284961..34b9a97dd2f4e 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.OpenSsl.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/StorePal.OpenSsl.cs @@ -10,10 +10,12 @@ namespace System.Security.Cryptography.X509Certificates { internal sealed partial class StorePal { +#pragma warning disable IDE0060 internal static partial IStorePal FromHandle(IntPtr storeHandle) { throw new PlatformNotSupportedException(); } +#pragma warning restore IDE0060 internal static partial ILoaderPal FromBlob(ReadOnlySpan rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { diff --git a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceBase.cs b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceBase.cs index ddc3e2ea601c5..870eff65a752f 100644 --- a/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceBase.cs +++ b/src/libraries/System.ServiceProcess.ServiceController/src/System/ServiceProcess/ServiceBase.cs @@ -458,7 +458,7 @@ private unsafe void DeferredPause() } } - private void DeferredPowerEvent(int eventType, IntPtr eventData) + private void DeferredPowerEvent(int eventType) { // Note: The eventData pointer might point to an invalid location // This might happen because, between the time the eventData ptr was @@ -699,7 +699,7 @@ private int ServiceCommandCallbackEx(int command, int eventType, IntPtr eventDat { case ControlOptions.CONTROL_POWEREVENT: { - ThreadPool.QueueUserWorkItem(_ => DeferredPowerEvent(eventType, eventData)); + ThreadPool.QueueUserWorkItem(_ => DeferredPowerEvent(eventType)); break; } diff --git a/src/libraries/System.Speech/src/System.Speech.csproj b/src/libraries/System.Speech/src/System.Speech.csproj index 22506f7bf966e..a7bbbc72ca2f3 100644 --- a/src/libraries/System.Speech/src/System.Speech.csproj +++ b/src/libraries/System.Speech/src/System.Speech.csproj @@ -5,7 +5,7 @@ - $(NoWarn);CS0649;SA1129;CA1846;CA1847;IDE0059;CA1822;CA1852 + $(NoWarn);CS0649;SA1129;CA1846;CA1847;IDE0059;IDE0060;CA1822;CA1852 annotations false true diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderBestFitFallback.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderBestFitFallback.cs index 571aa1f0b4294..c3bdc2c4ba690 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderBestFitFallback.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/DecoderBestFitFallback.cs @@ -140,16 +140,6 @@ public override unsafe void Reset() iCount = -1; } - // This version just counts the fallback and doesn't actually copy anything. - internal static unsafe int InternalFallback(byte[] bytes, byte* pBytes) - // Right now this has both bytes and bytes[], since we might have extra bytes, hence the - // array, and we might need the index, hence the byte* - { - // return our replacement string Length (always 1 for InternalDecoderBestFitFallback, either - // a best fit char or ? - return 1; - } - // private helper methods private char TryBestFit(byte[] bytesCheck) { diff --git a/src/libraries/System.Text.Encodings.Web/src/Polyfills/System.Text.Rune.netstandard20.cs b/src/libraries/System.Text.Encodings.Web/src/Polyfills/System.Text.Rune.netstandard20.cs index 774ee9e426c7e..77bb753ebb63d 100644 --- a/src/libraries/System.Text.Encodings.Web/src/Polyfills/System.Text.Rune.netstandard20.cs +++ b/src/libraries/System.Text.Encodings.Web/src/Polyfills/System.Text.Rune.netstandard20.cs @@ -51,7 +51,7 @@ public Rune(int value) } // non-validating ctor - private Rune(uint scalarValue, bool unused) + private Rune(uint scalarValue, bool _) { UnicodeDebug.AssertIsValidScalar(scalarValue); _value = scalarValue; diff --git a/src/libraries/System.Text.Json/Common/JsonSerializableAttribute.cs b/src/libraries/System.Text.Json/Common/JsonSerializableAttribute.cs index 1b689ba6cfb9a..6b2535269dc52 100644 --- a/src/libraries/System.Text.Json/Common/JsonSerializableAttribute.cs +++ b/src/libraries/System.Text.Json/Common/JsonSerializableAttribute.cs @@ -20,11 +20,13 @@ namespace System.Text.Json.Serialization #endif sealed class JsonSerializableAttribute : JsonAttribute { +#pragma warning disable IDE0060 /// /// Initializes a new instance of with the specified type. /// /// The type to generate source code for. public JsonSerializableAttribute(Type type) { } +#pragma warning restore IDE0060 /// /// The name of the property for the generated for diff --git a/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Parser.cs b/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Parser.cs index 0230408f89ade..cbb6e5b0ad047 100644 --- a/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Parser.cs +++ b/src/libraries/System.Text.Json/gen/JsonSourceGenerator.Parser.cs @@ -1216,7 +1216,6 @@ private PropertyGenerationSpec GetPropertyGenerationSpec( ProcessMember( memberInfo, - memberCLRType, hasJsonInclude, out bool isReadOnly, out bool isPublic, @@ -1382,7 +1381,6 @@ private void ProcessMemberCustomAttributes( private static void ProcessMember( MemberInfo memberInfo, - Type memberClrType, bool hasJsonInclude, out bool isReadOnly, out bool isPublic, diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonCollectionConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonCollectionConverter.cs index 976aae8adebb0..c2d25718ba63b 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonCollectionConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonCollectionConverter.cs @@ -163,7 +163,7 @@ internal override bool OnTryRead( // Dispatch to any polymorphic converters: should always be entered regardless of ObjectState progress if (state.Current.MetadataPropertyNames.HasFlag(MetadataPropertyName.Type) && state.Current.PolymorphicSerializationState != PolymorphicSerializationState.PolymorphicReEntryStarted && - ResolvePolymorphicConverter(jsonTypeInfo, options, ref state) is JsonConverter polymorphicConverter) + ResolvePolymorphicConverter(jsonTypeInfo, ref state) is JsonConverter polymorphicConverter) { Debug.Assert(!IsValueType); bool success = polymorphicConverter.OnTryReadAsObject(ref reader, options, ref state, out object? objectResult); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonDictionaryConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonDictionaryConverter.cs index a15be5d8ebd8e..0475b0a8848df 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonDictionaryConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/JsonDictionaryConverter.cs @@ -187,7 +187,7 @@ internal sealed override bool OnTryRead( // Dispatch to any polymorphic converters: should always be entered regardless of ObjectState progress if (state.Current.MetadataPropertyNames.HasFlag(MetadataPropertyName.Type) && state.Current.PolymorphicSerializationState != PolymorphicSerializationState.PolymorphicReEntryStarted && - ResolvePolymorphicConverter(jsonTypeInfo, options, ref state) is JsonConverter polymorphicConverter) + ResolvePolymorphicConverter(jsonTypeInfo, ref state) is JsonConverter polymorphicConverter) { Debug.Assert(!IsValueType); bool success = polymorphicConverter.OnTryReadAsObject(ref reader, options, ref state, out object? objectResult); @@ -201,7 +201,7 @@ internal sealed override bool OnTryRead( { if (state.Current.CanContainMetadata) { - JsonSerializer.ValidateMetadataForObjectConverter(this, ref reader, ref state); + JsonSerializer.ValidateMetadataForObjectConverter(ref state); } CreateCollection(ref reader, ref state); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectDefaultConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectDefaultConverter.cs index 4a2090f659a99..c3082bde9c419 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectDefaultConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectDefaultConverter.cs @@ -58,7 +58,7 @@ internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, // Read method would have thrown if otherwise. Debug.Assert(tokenType == JsonTokenType.PropertyName); - ReadOnlySpan unescapedPropertyName = JsonSerializer.GetPropertyName(ref state, ref reader, options); + ReadOnlySpan unescapedPropertyName = JsonSerializer.GetPropertyName(ref state, ref reader); JsonPropertyInfo jsonPropertyInfo = JsonSerializer.LookupProperty( obj, unescapedPropertyName, @@ -104,7 +104,7 @@ internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, // Dispatch to any polymorphic converters: should always be entered regardless of ObjectState progress if (state.Current.MetadataPropertyNames.HasFlag(MetadataPropertyName.Type) && state.Current.PolymorphicSerializationState != PolymorphicSerializationState.PolymorphicReEntryStarted && - ResolvePolymorphicConverter(jsonTypeInfo, options, ref state) is JsonConverter polymorphicConverter) + ResolvePolymorphicConverter(jsonTypeInfo, ref state) is JsonConverter polymorphicConverter) { Debug.Assert(!IsValueType); bool success = polymorphicConverter.OnTryReadAsObject(ref reader, options, ref state, out object? objectResult); @@ -117,7 +117,7 @@ internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, { if (state.Current.CanContainMetadata) { - JsonSerializer.ValidateMetadataForObjectConverter(this, ref reader, ref state); + JsonSerializer.ValidateMetadataForObjectConverter(ref state); } if (state.Current.MetadataPropertyNames == MetadataPropertyName.Ref) @@ -185,7 +185,7 @@ internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, // Read method would have thrown if otherwise. Debug.Assert(tokenType == JsonTokenType.PropertyName); - ReadOnlySpan unescapedPropertyName = JsonSerializer.GetPropertyName(ref state, ref reader, options); + ReadOnlySpan unescapedPropertyName = JsonSerializer.GetPropertyName(ref state, ref reader); jsonPropertyInfo = JsonSerializer.LookupProperty( obj, unescapedPropertyName, diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.cs index bf473d5c79053..d373ff9dfab6d 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.cs @@ -134,7 +134,7 @@ internal sealed override bool OnTryRead(ref Utf8JsonReader reader, Type typeToCo // Dispatch to any polymorphic converters: should always be entered regardless of ObjectState progress if (state.Current.MetadataPropertyNames.HasFlag(MetadataPropertyName.Type) && state.Current.PolymorphicSerializationState != PolymorphicSerializationState.PolymorphicReEntryStarted && - ResolvePolymorphicConverter(jsonTypeInfo, options, ref state) is JsonConverter polymorphicConverter) + ResolvePolymorphicConverter(jsonTypeInfo, ref state) is JsonConverter polymorphicConverter) { Debug.Assert(!IsValueType); bool success = polymorphicConverter.OnTryReadAsObject(ref reader, options, ref state, out object? objectResult); @@ -148,7 +148,7 @@ internal sealed override bool OnTryRead(ref Utf8JsonReader reader, Type typeToCo { if (state.Current.CanContainMetadata) { - JsonSerializer.ValidateMetadataForObjectConverter(this, ref reader, ref state); + JsonSerializer.ValidateMetadataForObjectConverter(ref state); } if (state.Current.MetadataPropertyNames == MetadataPropertyName.Ref) @@ -157,7 +157,7 @@ internal sealed override bool OnTryRead(ref Utf8JsonReader reader, Type typeToCo return true; } - BeginRead(ref state, ref reader, options); + BeginRead(ref state, options); state.Current.ObjectState = StackFrameObjectState.ConstructorArguments; } @@ -258,7 +258,7 @@ internal sealed override bool OnTryRead(ref Utf8JsonReader reader, Type typeToCo [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ReadConstructorArguments(scoped ref ReadStack state, ref Utf8JsonReader reader, JsonSerializerOptions options) { - BeginRead(ref state, ref reader, options); + BeginRead(ref state, options); while (true) { @@ -294,7 +294,7 @@ private void ReadConstructorArguments(scoped ref ReadStack state, ref Utf8JsonRe } else { - ReadOnlySpan unescapedPropertyName = JsonSerializer.GetPropertyName(ref state, ref reader, options); + ReadOnlySpan unescapedPropertyName = JsonSerializer.GetPropertyName(ref state, ref reader); JsonPropertyInfo jsonPropertyInfo = JsonSerializer.LookupProperty( obj: null!, unescapedPropertyName, @@ -386,7 +386,7 @@ private bool ReadConstructorArgumentsWithContinuation(scoped ref ReadStack state } else { - ReadOnlySpan unescapedPropertyName = JsonSerializer.GetPropertyName(ref state, ref reader, options); + ReadOnlySpan unescapedPropertyName = JsonSerializer.GetPropertyName(ref state, ref reader); jsonPropertyInfo = JsonSerializer.LookupProperty( obj: null!, unescapedPropertyName, @@ -537,7 +537,7 @@ private static bool HandlePropertyWithContinuation( } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void BeginRead(scoped ref ReadStack state, ref Utf8JsonReader reader, JsonSerializerOptions options) + private void BeginRead(scoped ref ReadStack state, JsonSerializerOptions options) { JsonTypeInfo jsonTypeInfo = state.Current.JsonTypeInfo; @@ -569,7 +569,7 @@ protected virtual bool TryLookupConstructorParameter( { Debug.Assert(state.Current.JsonTypeInfo.Kind == JsonTypeInfoKind.Object); - ReadOnlySpan unescapedPropertyName = JsonSerializer.GetPropertyName(ref state, ref reader, options); + ReadOnlySpan unescapedPropertyName = JsonSerializer.GetPropertyName(ref state, ref reader); jsonParameterInfo = state.Current.JsonTypeInfo.GetParameter( unescapedPropertyName, diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/EnumConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/EnumConverter.cs index 7b002db36f83b..e9b01aaf3d27f 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/EnumConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Value/EnumConverter.cs @@ -378,7 +378,7 @@ private static bool TryParseEnumCore(ref Utf8JsonReader reader, JsonSerializerOp return success; } #else - private static bool TryParseEnumCore(string? enumString, JsonSerializerOptions options, out T value) + private static bool TryParseEnumCore(string? enumString, JsonSerializerOptions _, out T value) { // Try parsing case sensitive first bool success = Enum.TryParse(enumString, out T result) || Enum.TryParse(enumString, ignoreCase: true, out result); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.MetadataHandling.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.MetadataHandling.cs index a507effee9556..74345fa12ccb7 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.MetadataHandling.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.MetadataHandling.cs @@ -11,7 +11,7 @@ public partial class JsonConverter /// /// Initializes the state for polymorphic cases and returns the appropriate derived converter. /// - internal JsonConverter? ResolvePolymorphicConverter(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options, ref ReadStack state) + internal JsonConverter? ResolvePolymorphicConverter(JsonTypeInfo jsonTypeInfo, ref ReadStack state) { Debug.Assert(!IsValueType); Debug.Assert(CanHaveMetadata); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.ReadAhead.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.ReadAhead.cs index b15deac8c486a..6f42bd414938f 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.ReadAhead.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.ReadAhead.cs @@ -25,10 +25,10 @@ internal static bool SingleValueReadWithReadAhead(bool requiresReadAhead, ref Ut return reader.Read(); } - return DoSingleValueReadWithReadAhead(ref reader, ref state); + return DoSingleValueReadWithReadAhead(ref reader); } - internal static bool DoSingleValueReadWithReadAhead(ref Utf8JsonReader reader, scoped ref ReadStack state) + internal static bool DoSingleValueReadWithReadAhead(ref Utf8JsonReader reader) { // When we're reading ahead we always have to save the state as we don't know if the next token // is an opening object or an array brace. diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs index 73cf9844ce392..c67f4ad6350c7 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandleMetadata.cs @@ -425,7 +425,7 @@ static string ReadAsStringMetadataValue(JsonNode? jsonNode) return refMetadataFound; } - internal static void ValidateMetadataForObjectConverter(JsonConverter converter, ref Utf8JsonReader reader, scoped ref ReadStack state) + internal static void ValidateMetadataForObjectConverter(ref ReadStack state) { if (state.Current.MetadataPropertyNames.HasFlag(MetadataPropertyName.Values)) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandlePropertyName.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandlePropertyName.cs index 6748f3a2d3280..c3d6916546ab4 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandlePropertyName.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.HandlePropertyName.cs @@ -72,8 +72,7 @@ internal static JsonPropertyInfo LookupProperty( [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static ReadOnlySpan GetPropertyName( scoped ref ReadStack state, - ref Utf8JsonReader reader, - JsonSerializerOptions options) + ref Utf8JsonReader reader) { ReadOnlySpan unescapedPropertyName; ReadOnlySpan propertyName = reader.GetSpan(); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptionsUpdateHandler.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptionsUpdateHandler.cs index 53031f1a3c34e..57a7e14ef72ba 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptionsUpdateHandler.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializerOptionsUpdateHandler.cs @@ -9,6 +9,8 @@ [assembly: MetadataUpdateHandler(typeof(JsonSerializerOptionsUpdateHandler))] +#pragma warning disable IDE0060 + namespace System.Text.Json { /// Handler used to clear JsonSerializerOptions reflection cache upon a metadata update. diff --git a/src/libraries/System.Text.RegularExpressions/gen/Stubs.cs b/src/libraries/System.Text.RegularExpressions/gen/Stubs.cs index badd7db2ce80c..5056318d01b6e 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/Stubs.cs +++ b/src/libraries/System.Text.RegularExpressions/gen/Stubs.cs @@ -9,6 +9,8 @@ using System.Runtime.InteropServices; using System.Text; +#pragma warning disable IDE0060 + // This file provides helpers used to help compile some Regex source code (e.g. RegexParser) as part of the netstandard2.0 generator assembly. namespace System.Text diff --git a/src/libraries/System.Text.RegularExpressions/gen/UpgradeToGeneratedRegexCodeFixer.cs b/src/libraries/System.Text.RegularExpressions/gen/UpgradeToGeneratedRegexCodeFixer.cs index 8489f20eb584d..bf98ce298ecff 100644 --- a/src/libraries/System.Text.RegularExpressions/gen/UpgradeToGeneratedRegexCodeFixer.cs +++ b/src/libraries/System.Text.RegularExpressions/gen/UpgradeToGeneratedRegexCodeFixer.cs @@ -56,7 +56,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) context.RegisterCodeFix( CodeAction.Create( SR.UseRegexSourceGeneratorTitle, - cancellationToken => ConvertToSourceGenerator(context.Document, root, nodeToFix, context.Diagnostics[0], cancellationToken), + cancellationToken => ConvertToSourceGenerator(context.Document, root, nodeToFix, cancellationToken), equivalenceKey: SR.UseRegexSourceGeneratorTitle), context.Diagnostics); } @@ -71,7 +71,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) /// The diagnostic to fix. /// The cancellation token for the async operation. /// The new document with the replaced nodes after applying the code fix. - private static async Task ConvertToSourceGenerator(Document document, SyntaxNode root, SyntaxNode nodeToFix, Diagnostic diagnostic, CancellationToken cancellationToken) + private static async Task ConvertToSourceGenerator(Document document, SyntaxNode root, SyntaxNode nodeToFix, CancellationToken cancellationToken) { // We first get the compilation object from the document SemanticModel? semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/TransactionShim.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/TransactionShim.cs index 349d051999f52..44f1ce32a6295 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/TransactionShim.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/TransactionShim.cs @@ -29,7 +29,7 @@ public void Abort() public void CreateVoter(OletxPhase1VolatileEnlistmentContainer managedIdentifier, out VoterBallotShim voterBallotShim) { var voterNotifyShim = new VoterNotifyShim(_shimFactory, managedIdentifier); - var voterShim = new VoterBallotShim(_shimFactory, voterNotifyShim); + var voterShim = new VoterBallotShim(voterNotifyShim); _shimFactory.VoterFactory.Create(Transaction, voterNotifyShim, out ITransactionVoterBallotAsync2 voterBallot); voterShim.VoterBallotAsync2 = voterBallot; voterBallotShim = voterShim; diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/VoterShim.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/VoterShim.cs index db354738f7fc1..ce307340e4adc 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/VoterShim.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/DtcProxyShim/VoterShim.cs @@ -11,7 +11,7 @@ internal sealed class VoterBallotShim internal ITransactionVoterBallotAsync2? VoterBallotAsync2 { get; set; } - internal VoterBallotShim(DtcProxyShimFactory shimFactory, VoterNotifyShim notifyShim) + internal VoterBallotShim(VoterNotifyShim notifyShim) => _voterNotifyShim = notifyShim; public void Vote(bool voteYes) diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/EnterpriseServices.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/EnterpriseServices.cs index 4afc501fa36c3..005763268e89e 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/EnterpriseServices.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/EnterpriseServices.cs @@ -15,7 +15,7 @@ internal static void VerifyEnterpriseServicesOk() } } - internal static Transaction? GetContextTransaction(ContextData contextData) + internal static Transaction? GetContextTransaction() { if (EnterpriseServicesOk) { @@ -29,7 +29,7 @@ internal static void VerifyEnterpriseServicesOk() internal static bool UseServiceDomainForCurrent() => false; - internal static void PushServiceDomain(Transaction? newCurrent) + internal static void PushServiceDomain() { ThrowNotSupported(); } diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/NonWindowsUnsupported.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/NonWindowsUnsupported.cs index 01d25a58cc96a..3513f1bd3df03 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/NonWindowsUnsupported.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/NonWindowsUnsupported.cs @@ -7,7 +7,7 @@ // This files contains non-Windows stubs for Windows-only functionality, so that Sys.Tx can build. The APIs below // are only ever called when a distributed transaction is needed, and throw PlatformNotSupportedException. -#pragma warning disable CA1822 +#pragma warning disable CA1822, IDE0060 namespace System.Transactions.Oletx { diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxResourceManager.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxResourceManager.cs index 42ca355645e2b..a59f2d1e5c682 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxResourceManager.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxResourceManager.cs @@ -362,7 +362,7 @@ internal OletxEnlistment Reenlist(byte[] prepareInfo, IEnlistmentNotificationInt Guid rmGuid = new(rmGuidArray); if (rmGuid != ResourceManagerIdentifier) { - throw TransactionException.Create(TraceSourceType.TraceSourceOleTx, SR.ResourceManagerIdDoesNotMatchRecoveryInformation, null); + throw TransactionException.Create(SR.ResourceManagerIdDoesNotMatchRecoveryInformation, null); } // Ask the proxy resource manager to reenlist. diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxTransaction.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxTransaction.cs index caa4982635395..40986ec5ac9fc 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxTransaction.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxTransaction.cs @@ -619,8 +619,7 @@ internal RealOletxTransaction( TransactionShim? transactionShim, OutcomeEnlistment? outcomeEnlistment, Guid identifier, - OletxTransactionIsolationLevel oletxIsoLevel, - bool isRoot) + OletxTransactionIsolationLevel oletxIsoLevel) { bool successful = false; diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxTransactionManager.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxTransactionManager.cs index da4ed6550518d..d2cc98ae9b9ac 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxTransactionManager.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/Oletx/OletxTransactionManager.cs @@ -463,8 +463,7 @@ internal OletxCommittableTransaction CreateTransaction(TransactionOptions proper transactionShim, outcomeEnlistment, txIdentifier, - oletxIsoLevel, - true); + oletxIsoLevel); tx = new OletxCommittableTransaction(realTransaction); TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/Transaction.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/Transaction.cs index 10eac90c862d3..f5c325033e25d 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/Transaction.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/Transaction.cs @@ -101,19 +101,19 @@ internal static EnterpriseServicesInteropOption InteropMode(TransactionScope? cu } else { - current = EnterpriseServices.GetContextTransaction(contextData); + current = EnterpriseServices.GetContextTransaction(); } } break; case EnterpriseServicesInteropOption.Full: - current = EnterpriseServices.GetContextTransaction(contextData); + current = EnterpriseServices.GetContextTransaction(); break; case EnterpriseServicesInteropOption.Automatic: if (EnterpriseServices.UseServiceDomainForCurrent()) { - current = EnterpriseServices.GetContextTransaction(contextData); + current = EnterpriseServices.GetContextTransaction(); } else { diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionException.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionException.cs index f08fd23d3092b..1e5b49146b196 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionException.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionException.cs @@ -29,16 +29,6 @@ internal static TransactionException Create(string? message, Exception? innerExc return new TransactionException(message, innerException); } - internal static TransactionException Create(TraceSourceType traceSource, string? message, Exception? innerException) - { - TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; - if (etwLog.IsEnabled()) - { - etwLog.TransactionExceptionTrace(TransactionExceptionType.TransactionException, message, innerException == null ? string.Empty : innerException.ToString()); - } - - return new TransactionException(message, innerException); - } internal static TransactionException CreateTransactionStateException(Exception? innerException) { return Create(SR.TransactionStateException, innerException); @@ -120,24 +110,6 @@ internal static TransactionException Create(string? message, Exception? innerExc return Create(messagewithTxId, innerException); } - internal static TransactionException Create(TraceSourceType traceSource, string? message, Exception? innerException, Guid distributedTxId) - { - string? messagewithTxId = message; - if (IncludeDistributedTxId(distributedTxId)) - messagewithTxId = SR.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId); - - return Create(traceSource, messagewithTxId, innerException); - } - - internal static TransactionException Create(TraceSourceType traceSource, string? message, Guid distributedTxId) - { - if (IncludeDistributedTxId(distributedTxId)) - { - return new TransactionException(SR.Format(SR.DistributedTxIDInTransactionException, message, distributedTxId)); - } - return new TransactionException(message); - } - internal static TransactionException CreateTransactionStateException(Exception? innerException, Guid distributedTxId) { return Create(SR.TransactionStateException, innerException, distributedTxId); @@ -251,7 +223,7 @@ protected TransactionAbortedException(SerializationInfo info, StreamingContext c [System.Runtime.CompilerServices.TypeForwardedFrom("System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class TransactionInDoubtException : TransactionException { - internal static new TransactionInDoubtException Create(TraceSourceType traceSource, string? message, Exception? innerException, Guid distributedTxId) + internal static TransactionInDoubtException Create(TraceSourceType traceSource, string? message, Exception? innerException, Guid distributedTxId) { string? messagewithTxId = message; if (IncludeDistributedTxId(distributedTxId)) @@ -260,7 +232,7 @@ public class TransactionInDoubtException : TransactionException return TransactionInDoubtException.Create(traceSource, messagewithTxId, innerException); } - internal static new TransactionInDoubtException Create(TraceSourceType traceSource, string? message, Exception? innerException) + internal static TransactionInDoubtException Create(TraceSourceType traceSource, string? message, Exception? innerException) { TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs index a8983b5afad2b..e2da43f0edb9c 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs @@ -167,8 +167,7 @@ public static Transaction GetTransactionFromExportCookie(byte[] cookie) transactionShim, outcomeEnlistment, txIdentifier, - oletxIsoLevel, - false); + oletxIsoLevel); // Now create the associated OletxTransaction. oleTx = new OletxTransaction(realTx); @@ -385,8 +384,7 @@ public static Transaction GetTransactionFromDtcTransaction(IDtcTransaction trans transactionShim, outcomeEnlistment, txIdentifier, - oletxIsoLevel, - false); + oletxIsoLevel); oleTx = new OletxTransaction(realTx); @@ -403,8 +401,7 @@ public static Transaction GetTransactionFromDtcTransaction(IDtcTransaction trans null, null, txIdentifier, - OletxTransactionIsolationLevel.ISOLATIONLEVEL_SERIALIZABLE, - false); + OletxTransactionIsolationLevel.ISOLATIONLEVEL_SERIALIZABLE); oleTx = new OletxTransaction(realTx); transaction = new Transaction(oleTx); @@ -511,8 +508,7 @@ internal static OletxTransaction GetOletxTransactionFromTransmitterPropagationTo transactionShim, outcomeEnlistment, identifier, - oletxIsoLevel, - false); + oletxIsoLevel); return new OletxTransaction(realTx); } diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs index 0ca05d76d4bb7..b761e13c0c2de 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs @@ -857,7 +857,7 @@ private static void TimerCallback(object? state) etwLog.InternalError("TransactionScopeTimerObjectInvalid"); } - throw TransactionException.Create(TraceSourceType.TraceSourceBase, SR.InternalError + SR.TransactionScopeTimerObjectInvalid, null); + throw TransactionException.Create(SR.InternalError + SR.TransactionScopeTimerObjectInvalid, null); } scope.Timeout(); @@ -1054,7 +1054,7 @@ private void SetCurrent(Transaction? newCurrent) EnterpriseServices.VerifyEnterpriseServicesOk(); if (EnterpriseServices.UseServiceDomainForCurrent()) { - EnterpriseServices.PushServiceDomain(newCurrent); + EnterpriseServices.PushServiceDomain(); } else { @@ -1064,7 +1064,7 @@ private void SetCurrent(Transaction? newCurrent) case EnterpriseServicesInteropOption.Full: EnterpriseServices.VerifyEnterpriseServicesOk(); - EnterpriseServices.PushServiceDomain(newCurrent); + EnterpriseServices.PushServiceDomain(); break; } } diff --git a/src/mono/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipe.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipe.Mono.cs index 21db2adac4212..5c036998e378a 100644 --- a/src/mono/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipe.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventPipe.Mono.cs @@ -87,7 +87,7 @@ internal enum RuntimeCounters [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern ulong GetRuntimeCounterValue(RuntimeCounters counterID); #else - internal static ulong GetRuntimeCounterValue(RuntimeCounters counterID) + internal static ulong GetRuntimeCounterValue(RuntimeCounters _ /*counterID*/) { return 0; } diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.Mono.cs index 7583cbad8e34d..7c5de218b3c3c 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/AssemblyBuilder.Mono.cs @@ -273,7 +273,7 @@ public ModuleBuilder DefineDynamicModule(string name) internal static AssemblyBuilder InternalDefineDynamicAssembly( AssemblyName name, AssemblyBuilderAccess access, - Assembly? callingAssembly, + Assembly? _ /*callingAssembly*/, AssemblyLoadContext? assemblyLoadContext, IEnumerable? assemblyAttributes) { diff --git a/src/mono/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs index 72f3cc28a70be..1025e77ebe481 100644 --- a/src/mono/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs @@ -1,5 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Tracing; using System.Runtime.Serialization; @@ -146,12 +148,16 @@ internal static bool ObjectHasReferences(object obj) // Mono uses a conservative GC so there is no need for this API to be full implemented. internal unsafe ref struct GCFrameRegistration { +#pragma warning disable IDE0060 public GCFrameRegistration(void* allocation, uint elemCount, bool areByRefs = true) { } +#pragma warning restore IDE0060 } + [Conditional("unnecessary")] internal static unsafe void RegisterForGCReporting(GCFrameRegistration* pRegistration) { /* nop */ } + [Conditional("unnecessary")] internal static unsafe void UnregisterForGCReporting(GCFrameRegistration* pRegistration) { /* nop */ } public static object GetUninitializedObject( diff --git a/src/mono/System.Private.CoreLib/src/System/RuntimeType.Mono.cs b/src/mono/System.Private.CoreLib/src/System/RuntimeType.Mono.cs index 08484d246a504..cbedc793bb2e7 100644 --- a/src/mono/System.Private.CoreLib/src/System/RuntimeType.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/RuntimeType.Mono.cs @@ -1767,9 +1767,9 @@ private CheckValueStatus TryConvertToType(ref object? value) } // Stub method to allow for shared code with CoreClr. -#pragma warning disable CA1822 +#pragma warning disable CA1822, IDE0060 internal bool TryByRefFastPath(ref object arg, ref bool isValueType) => false; -#pragma warning restore CA1822 +#pragma warning restore CA1822, IDE0060 // Binder uses some incompatible conversion rules. For example // int value cannot be used with decimal parameter but in other diff --git a/src/mono/System.Private.CoreLib/src/System/Threading/ThreadPool.Browser.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Threading/ThreadPool.Browser.Mono.cs index e9d27a6c3987d..a5e54288a2920 100644 --- a/src/mono/System.Private.CoreLib/src/System/Threading/ThreadPool.Browser.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Threading/ThreadPool.Browser.Mono.cs @@ -9,6 +9,8 @@ using System.Diagnostics.CodeAnalysis; using Microsoft.Win32.SafeHandles; +#pragma warning disable IDE0060 + namespace System.Threading { #if !FEATURE_WASM_THREADS @@ -84,12 +86,6 @@ internal static void NotifyWorkItemProgress() { } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static bool NotifyWorkItemComplete(object? threadLocalCompletionCountObject, int currentTimeMs) - { - return true; - } - internal static bool NotifyThreadBlocked() => false; internal static void NotifyThreadUnblocked() @@ -98,6 +94,11 @@ internal static void NotifyThreadUnblocked() internal static object? GetOrCreateThreadLocalCompletionCountObject() => null; + internal static bool NotifyWorkItemComplete(object? threadLocalCompletionCountObject, int currentTimeMs) + { + return true; + } + private static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle? waitObject, WaitOrTimerCallback? callBack, diff --git a/src/mono/System.Private.CoreLib/src/System/Threading/ThreadPoolBoundHandle.Browser.Threads.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Threading/ThreadPoolBoundHandle.Browser.Threads.Mono.cs index c1bcfa75b8c2f..6d06335953dca 100644 --- a/src/mono/System.Private.CoreLib/src/System/Threading/ThreadPoolBoundHandle.Browser.Threads.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Threading/ThreadPoolBoundHandle.Browser.Threads.Mono.cs @@ -7,9 +7,11 @@ namespace System.Threading { public sealed partial class ThreadPoolBoundHandle : IDisposable { +#pragma warning disable IDE0060 private static ThreadPoolBoundHandle BindHandleCore(SafeHandle handle) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_OverlappedIO); } +#pragma warning restore IDE0060 } } diff --git a/src/mono/System.Private.CoreLib/src/System/Threading/TimerQueue.Browser.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Threading/TimerQueue.Browser.Mono.cs index 153783fa1707c..580df53de2a8d 100644 --- a/src/mono/System.Private.CoreLib/src/System/Threading/TimerQueue.Browser.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Threading/TimerQueue.Browser.Mono.cs @@ -23,7 +23,7 @@ internal partial class TimerQueue private bool _isScheduled; private long _scheduledDueTimeMs; - private TimerQueue(int id) + private TimerQueue(int _) { } diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs b/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs index 3911d8a30691d..effd7e06e451d 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs @@ -482,7 +482,7 @@ public ParameterInfo[] GetParametersInfo() return paramsInfo; } - public void UpdateEnC(MetadataReader asmMetadataReader, MetadataReader pdbMetadataReaderParm, int methodIdx) + public void UpdateEnC(MetadataReader pdbMetadataReaderParm, int methodIdx) { this.DebugInformation = pdbMetadataReaderParm.GetMethodDebugInformation(MetadataTokens.MethodDebugInformationHandle(methodIdx)); this.pdbMetadataReader = pdbMetadataReaderParm; @@ -836,14 +836,14 @@ internal sealed class AssemblyInfo private readonly Dictionary _documentIdToSourceFileTable = new Dictionary(); - public AssemblyInfo(string name, ILogger logger) + public AssemblyInfo(ILogger logger) { debugId = -1; this.id = Interlocked.Increment(ref next_id); this.logger = logger; } - public unsafe AssemblyInfo(MonoProxy monoProxy, SessionId sessionId, string url, byte[] assembly, byte[] pdb, ILogger logger, CancellationToken token) + public unsafe AssemblyInfo(MonoProxy monoProxy, SessionId sessionId, byte[] assembly, byte[] pdb, ILogger logger, CancellationToken token) { debugId = -1; this.id = Interlocked.Increment(ref next_id); @@ -974,7 +974,7 @@ private void PopulateEnC(MetadataReader asmMetadataReaderParm, MetadataReader pd var typeDefinition = asmMetadataReaderParm.GetTypeDefinition(MetadataTokens.TypeDefinitionHandle(typeDefIdx)); StringHandle name = MetadataTokens.StringHandle(typeDefinition.Name.GetHashCode() & 127); - typeInfo = CreateTypeInfo(typeHandle, typeDefinition, asmMetadataReaderParm); + typeInfo = CreateTypeInfo(typeHandle, typeDefinition); } } else if (entry.Operation == EditAndContinueOperation.Default) @@ -986,7 +986,7 @@ private void PopulateEnC(MetadataReader asmMetadataReaderParm, MetadataReader pd int methodIdx = GetMethodDebugInformationIdx(pdbMetadataReaderParm, entryRow); if (methods.TryGetValue(entryRow, out MethodInfo method)) { - method.UpdateEnC(asmMetadataReaderParm, pdbMetadataReaderParm, methodIdx); + method.UpdateEnC(pdbMetadataReaderParm, methodIdx); } else if (typeInfo != null) { @@ -1041,7 +1041,7 @@ private void Populate() foreach (TypeDefinitionHandle type in asmMetadataReader.TypeDefinitions) { var typeDefinition = asmMetadataReader.GetTypeDefinition(type); - var typeInfo = CreateTypeInfo(type, typeDefinition, asmMetadataReader); + var typeInfo = CreateTypeInfo(type, typeDefinition); foreach (MethodDefinitionHandle method in typeDefinition.GetMethods()) { @@ -1113,7 +1113,7 @@ private Uri GetSourceLinkUrl(string document) return null; } - public TypeInfo CreateTypeInfo(TypeDefinitionHandle typeHandle, TypeDefinition type, MetadataReader metadataReader) + public TypeInfo CreateTypeInfo(TypeDefinitionHandle typeHandle, TypeDefinition type) { var typeInfo = new TypeInfo(this, typeHandle, type, asmMetadataReader, logger); TypesByName[typeInfo.FullName] = typeInfo; @@ -1394,12 +1394,12 @@ public static IEnumerable GetEnCMethods(AssemblyInfo asm) } } - public IEnumerable Add(SessionId id, string name, byte[] assembly_data, byte[] pdb_data, CancellationToken token) + public IEnumerable Add(SessionId id, byte[] assembly_data, byte[] pdb_data, CancellationToken token) { AssemblyInfo assembly; try { - assembly = new AssemblyInfo(monoProxy, id, name, assembly_data, pdb_data, logger, token); + assembly = new AssemblyInfo(monoProxy, id, assembly_data, pdb_data, logger, token); } catch (Exception e) { @@ -1493,7 +1493,7 @@ public async IAsyncEnumerable Load(SessionId id, string[] loaded_fil logger.LogDebug($"Bytes from assembly {step.Url} is NULL"); continue; } - assembly = new AssemblyInfo(monoProxy, id, step.Url, bytes[0], bytes[1], logger, token); + assembly = new AssemblyInfo(monoProxy, id, bytes[0], bytes[1], logger, token); } catch (Exception e) { diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/Firefox/FirefoxMonoProxy.cs b/src/mono/wasm/debugger/BrowserDebugProxy/Firefox/FirefoxMonoProxy.cs index e80bd1492ed0c..ecea374bb195d 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/Firefox/FirefoxMonoProxy.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/Firefox/FirefoxMonoProxy.cs @@ -478,7 +478,7 @@ protected override async Task AcceptCommand(MessageId sessionId, JObject a from = args["to"].Value() }); if (args["type"].Value() == "prototypeAndProperties") - o.Add("prototype", GetPrototype(objectId, args)); + o.Add("prototype", GetPrototype(args)); await SendEvent(sessionId, "", o, token); return true; } @@ -488,7 +488,7 @@ protected override async Task AcceptCommand(MessageId sessionId, JObject a return false; var o = JObject.FromObject(new { - prototype = GetPrototype(objectId, args), + prototype = GetPrototype(args), from = args["to"].Value() }); await SendEvent(sessionId, "", o, token); @@ -726,7 +726,7 @@ private async Task SendPauseToBrowser(SessionId sessionId, JObject args, C return true; } - private static JObject GetPrototype(DotnetObjectId objectId, JObject args) + private static JObject GetPrototype(JObject args) { var o = JObject.FromObject(new { diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/JObjectValueCreator.cs b/src/mono/wasm/debugger/BrowserDebugProxy/JObjectValueCreator.cs index 03783a7466e8d..89fef59f95113 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/JObjectValueCreator.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/JObjectValueCreator.cs @@ -345,7 +345,6 @@ public async Task ReadAsValueType( initialPos, className, typeId, - numValues, isEnum, includeStatic, token); diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/MonoProxy.cs b/src/mono/wasm/debugger/BrowserDebugProxy/MonoProxy.cs index 3af8a9db0e203..5b6bf24290f73 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/MonoProxy.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/MonoProxy.cs @@ -1272,7 +1272,7 @@ private async Task OnAssemblyLoadedJSEvent(SessionId sessionId, JObject ev var pdb_data = string.IsNullOrEmpty(pdb_b64) ? null : Convert.FromBase64String(pdb_b64); var context = GetContext(sessionId); - foreach (var source in store.Add(sessionId, assembly_name, assembly_data, pdb_data, token)) + foreach (var source in store.Add(sessionId, assembly_data, pdb_data, token)) { await OnSourceFileAdded(sessionId, source, context, token); } diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/MonoSDBHelper.cs b/src/mono/wasm/debugger/BrowserDebugProxy/MonoSDBHelper.cs index 3c3746eee63df..6e46d7693f188 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/MonoSDBHelper.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/MonoSDBHelper.cs @@ -849,7 +849,7 @@ public async Task GetAssemblyInfo(int assemblyId, CancellationToke asm = store.GetAssemblyByName(assemblyName); if (asm == null) { - asm = new AssemblyInfo(assemblyName, logger); + asm = new AssemblyInfo(logger); logger.LogDebug($"Created assembly without debug information: {assemblyName}"); } } @@ -2240,7 +2240,7 @@ public ValueTypeClass GetValueTypeClass(int valueTypeId) throw new ArgumentException($"Could not find any valuetype with id: {valueTypeId}", nameof(valueTypeId)); } - public Task GetTypeMemberValues(DotnetObjectId dotnetObjectId, GetObjectCommandOptions getObjectOptions, CancellationToken token, bool sortByAccessLevel = false) + public Task GetTypeMemberValues(DotnetObjectId dotnetObjectId, GetObjectCommandOptions getObjectOptions, CancellationToken token) => dotnetObjectId.IsValueType ? MemberObjectsExplorer.GetValueTypeMemberValues(this, dotnetObjectId.Value, getObjectOptions, token) : MemberObjectsExplorer.GetObjectMemberValues(this, dotnetObjectId.Value, getObjectOptions, token); diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/ValueTypeClass.cs b/src/mono/wasm/debugger/BrowserDebugProxy/ValueTypeClass.cs index b0977d4facd79..4de4a378451f1 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/ValueTypeClass.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/ValueTypeClass.cs @@ -52,7 +52,6 @@ public static async Task CreateFromReader( long initialPos, string className, int typeId, - int numValues, bool isEnum, bool includeStatic, CancellationToken token) diff --git a/src/mono/wasm/host/JSEngineHost.cs b/src/mono/wasm/host/JSEngineHost.cs index 5d41a248c4d59..fc77d69818a41 100644 --- a/src/mono/wasm/host/JSEngineHost.cs +++ b/src/mono/wasm/host/JSEngineHost.cs @@ -26,9 +26,9 @@ public JSEngineHost(JSEngineArguments args, ILogger logger) } public static async Task InvokeAsync(CommonConfiguration commonArgs, - ILoggerFactory loggerFactory, + ILoggerFactory _, ILogger logger, - CancellationToken token) + CancellationToken _1) { var args = new JSEngineArguments(commonArgs); args.Validate();