diff --git a/eng/CodeAnalysis.src.globalconfig b/eng/CodeAnalysis.src.globalconfig index e4d3c09e15b49..fc4c46fe7651d 100644 --- a/eng/CodeAnalysis.src.globalconfig +++ b/eng/CodeAnalysis.src.globalconfig @@ -306,7 +306,8 @@ dotnet_diagnostic.CA1820.severity = none dotnet_diagnostic.CA1821.severity = warning # CA1822: Mark members as static -dotnet_diagnostic.CA1822.severity = none +dotnet_diagnostic.CA1822.severity = warning +dotnet_code_quality.CA1822.api_surface = private, internal # CA1823: Avoid unused private fields dotnet_diagnostic.CA1823.severity = warning @@ -825,7 +826,7 @@ dotnet_diagnostic.CA5400.severity = none # CA5401: Do not use CreateEncryptor with non-default IV dotnet_diagnostic.CA5401.severity = none -# CA5402: Use CreateEncryptor with the default IV +# CA5402: Use CreateEncryptor with the default IV dotnet_diagnostic.CA5402.severity = none # CA5403: Do not hard-code certificate diff --git a/src/coreclr/nativeaot/Common/src/System/Collections/Concurrent/ConcurrentUnifier.cs b/src/coreclr/nativeaot/Common/src/System/Collections/Concurrent/ConcurrentUnifier.cs index 888522ccbea48..237895a8c0711 100644 --- a/src/coreclr/nativeaot/Common/src/System/Collections/Concurrent/ConcurrentUnifier.cs +++ b/src/coreclr/nativeaot/Common/src/System/Collections/Concurrent/ConcurrentUnifier.cs @@ -253,7 +253,6 @@ private static int ComputeBucket(int hashCode, int numBuckets) [Conditional("DEBUG")] public void VerifyUnifierConsistency() { -#if DEBUG // There's a point at which this check becomes gluttonous, even by checked build standards... if (_nextFreeEntry >= 5000 && (0 != (_nextFreeEntry % 100))) return; @@ -287,7 +286,6 @@ public void VerifyUnifierConsistency() // The assertion is "<=" rather than "==" because we allow an entry to "leak" until the next resize if // a thread died between the time between we allocated the entry and the time we link it into the bucket stack. Debug.Assert(numEntriesEncountered <= _nextFreeEntry); -#endif //DEBUG } private readonly int[] _buckets; diff --git a/src/coreclr/nativeaot/Common/src/System/Collections/Concurrent/ConcurrentUnifierW.cs b/src/coreclr/nativeaot/Common/src/System/Collections/Concurrent/ConcurrentUnifierW.cs index 1d805e0081bc1..049ce1ee078ab 100644 --- a/src/coreclr/nativeaot/Common/src/System/Collections/Concurrent/ConcurrentUnifierW.cs +++ b/src/coreclr/nativeaot/Common/src/System/Collections/Concurrent/ConcurrentUnifierW.cs @@ -337,7 +337,6 @@ private static int ComputeBucket(int hashCode, int numBuckets) [Conditional("DEBUG")] public void VerifyUnifierConsistency() { -#if DEBUG // There's a point at which this check becomes gluttonous, even by checked build standards... if (_nextFreeEntry >= 5000 || (0 != (_nextFreeEntry % 100))) return; @@ -372,7 +371,6 @@ public void VerifyUnifierConsistency() // The assertion is "<=" rather than "==" because we allow an entry to "leak" until the next resize if // a thread died between the time between we allocated the entry and the time we link it into the bucket stack. Debug.Assert(numEntriesEncountered <= _nextFreeEntry); -#endif //DEBUG } private readonly int[] _buckets; 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 c85567e76c407..49938feb8afa0 100644 --- a/src/coreclr/nativeaot/Common/src/System/Collections/Concurrent/ConcurrentUnifierWKeyed.cs +++ b/src/coreclr/nativeaot/Common/src/System/Collections/Concurrent/ConcurrentUnifierWKeyed.cs @@ -326,7 +326,6 @@ private static int ComputeBucket(int hashCode, int numBuckets) [Conditional("DEBUG")] public void VerifyUnifierConsistency() { -#if DEBUG // There's a point at which this check becomes gluttonous, even by checked build standards... if (_nextFreeEntry >= 5000 && (0 != (_nextFreeEntry % 100))) return; @@ -367,7 +366,6 @@ public void VerifyUnifierConsistency() // The assertion is "<=" rather than "==" because we allow an entry to "leak" until the next resize if // a thread died between the time between we allocated the entry and the time we link it into the bucket stack. Debug.Assert(numEntriesEncountered <= _nextFreeEntry); -#endif //DEBUG } private readonly int[] _buckets; diff --git a/src/coreclr/nativeaot/Runtime.Base/src/System/AttributeUsageAttribute.cs b/src/coreclr/nativeaot/Runtime.Base/src/System/AttributeUsageAttribute.cs index bd9ef45df7520..7c2ac82d779c4 100644 --- a/src/coreclr/nativeaot/Runtime.Base/src/System/AttributeUsageAttribute.cs +++ b/src/coreclr/nativeaot/Runtime.Base/src/System/AttributeUsageAttribute.cs @@ -29,7 +29,7 @@ public AttributeUsageAttribute(AttributeTargets validOn, bool allowMultiple, boo // Allowing the set properties as it allows a more readable syntax in the specifiers (and are commonly used) // The get properties will be needed only if these attributes are used at Runtime, however, the compiler // is getting an internal error if the gets are not defined. - +#pragma warning disable CA1822 public bool AllowMultiple { get { return false; } @@ -41,5 +41,6 @@ public bool Inherited get { return false; } set { } } +#pragma warning restore CA1822 } } diff --git a/src/coreclr/nativeaot/Runtime.Base/src/System/Runtime/MethodTable.Runtime.cs b/src/coreclr/nativeaot/Runtime.Base/src/System/Runtime/MethodTable.Runtime.cs index 4f538d555f819..7d4b3a9178ce2 100644 --- a/src/coreclr/nativeaot/Runtime.Base/src/System/Runtime/MethodTable.Runtime.cs +++ b/src/coreclr/nativeaot/Runtime.Base/src/System/Runtime/MethodTable.Runtime.cs @@ -11,6 +11,7 @@ namespace Internal.Runtime // Extensions to MethodTable that are specific to the use in Runtime.Base. internal unsafe partial struct MethodTable { +#pragma warning disable CA1822 internal MethodTable* GetArrayEEType() { #if INPLACE_RUNTIME @@ -46,6 +47,7 @@ internal Exception GetClasslibException(ExceptionIDs id) return EH.GetClasslibExceptionFromEEType(id, GetAssociatedModuleAddress()); #endif } +#pragma warning restore CA1822 internal IntPtr GetClasslibFunction(ClassLibFunctionId id) { diff --git a/src/coreclr/nativeaot/Runtime.Base/src/System/Runtime/ThunkPool.cs b/src/coreclr/nativeaot/Runtime.Base/src/System/Runtime/ThunkPool.cs index de50016e469b5..aed8ea05e51dc 100644 --- a/src/coreclr/nativeaot/Runtime.Base/src/System/Runtime/ThunkPool.cs +++ b/src/coreclr/nativeaot/Runtime.Base/src/System/Runtime/ThunkPool.cs @@ -269,7 +269,7 @@ private bool IsThunkInHeap(IntPtr thunkAddress) return false; } - private IntPtr TryGetThunkDataAddress(IntPtr thunkAddress) + private static IntPtr TryGetThunkDataAddress(IntPtr thunkAddress) { nuint thunkAddressValue = (nuint)(nint)ClearThumbBit(thunkAddress); diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Reflection/Extensions/NonPortable/CustomAttributeSearcher.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Reflection/Extensions/NonPortable/CustomAttributeSearcher.cs index dc332681127a2..bc9a9d770bc65 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Reflection/Extensions/NonPortable/CustomAttributeSearcher.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/Internal/Reflection/Extensions/NonPortable/CustomAttributeSearcher.cs @@ -184,7 +184,7 @@ private IEnumerable GetMatchingCustomAttributesIterator(E e // // Internal helper to compute the AttributeUsage. This must be coded specially to avoid an infinite recursion. // - private AttributeUsageAttribute GetAttributeUsage(Type attributeType) + private static AttributeUsageAttribute GetAttributeUsage(Type attributeType) { // This is only invoked when the seacher is called with "inherit: true", thus calling the searcher again // with "inherit: false" will not cause infinite recursion. diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Array.CoreRT.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Array.CoreRT.cs index 3fa434bc55b43..520ca327207fa 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Array.CoreRT.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Array.CoreRT.cs @@ -1146,14 +1146,16 @@ public bool MoveNext() return false; } - public void Dispose() + public object Clone() { + return MemberwiseClone(); } - public object Clone() +#pragma warning disable CA1822 // https://github.com/dotnet/roslyn-analyzers/issues/5911 + public void Dispose() { - return MemberwiseClone(); } +#pragma warning restore CA1822 } // diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Exception.CoreRT.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Exception.CoreRT.cs index c9239b10f4de8..5cf74def19dcd 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Exception.CoreRT.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Exception.CoreRT.cs @@ -26,9 +26,9 @@ public MethodBase? TargetSite } } - private IDictionary CreateDataContainer() => new ListDictionaryInternal(); + private static IDictionary CreateDataContainer() => new ListDictionaryInternal(); - private string? SerializationWatsonBuckets => null; + private static string? SerializationWatsonBuckets => null; private string? CreateSourceName() => HasBeenThrown ? "" : null; diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/MulticastDelegate.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/MulticastDelegate.cs index b05af345fe296..c678b52f00697 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/MulticastDelegate.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/MulticastDelegate.cs @@ -163,7 +163,7 @@ private MulticastDelegate NewMulticastDelegate(Delegate[] invocationList, int in return result; } - private bool TrySetSlot(Delegate[] a, int index, Delegate o) + private static bool TrySetSlot(Delegate[] a, int index, Delegate o) { if (a[index] == null && System.Threading.Interlocked.CompareExchange(ref a[index], o, null) == null) return true; @@ -297,7 +297,7 @@ private Delegate[] DeleteFromInvocationList(Delegate[] invocationList, int invoc return newInvocationList; } - private bool EqualInvocationLists(Delegate[] a, Delegate[] b, int start, int count) + private static bool EqualInvocationLists(Delegate[] a, Delegate[] b, int start, int count) { for (int i = 0; i < count; i++) { diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/CriticalHandle.CoreRT.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/CriticalHandle.CoreRT.cs index 15f17d3af19ce..85ef806cef847 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/CriticalHandle.CoreRT.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/InteropServices/CriticalHandle.CoreRT.cs @@ -7,10 +7,6 @@ namespace System.Runtime.InteropServices { public abstract partial class CriticalHandle : CriticalFinalizerObject, IDisposable { - internal void ReleaseHandleFailed() - { - } - internal void SetHandleInternal(IntPtr handle) { SetHandle(handle); diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreRT.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreRT.cs index 095cf17930f3f..b14bc6e0ffe03 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreRT.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Runtime/Loader/AssemblyLoadContext.CoreRT.cs @@ -40,17 +40,19 @@ public void StartProfileOptimization(string profile) { } - private Assembly InternalLoadFromPath(string? assemblyPath, string? nativeImagePath) + private static Assembly InternalLoadFromPath(string? assemblyPath, string? nativeImagePath) { // TODO: This is not passing down the AssemblyLoadContext, // so it won't actually work properly when multiple assemblies with the same identity get loaded. return ReflectionAugments.ReflectionCoreCallbacks.Load(assemblyPath); } +#pragma warning disable CA1822 internal Assembly InternalLoad(byte[] arrAssembly, byte[] arrSymbols) { return ReflectionAugments.ReflectionCoreCallbacks.Load(arrAssembly, arrSymbols); } +#pragma warning restore CA1822 private void ReferenceUnreferencedEvents() { diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs index 3c5745bcc873a..4922be6e4fd50 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/RuntimeFieldHandle.cs @@ -43,7 +43,7 @@ public bool Equals(RuntimeFieldHandle handle) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private int _rotl(int value, int shift) + private static int _rotl(int value, int shift) { return (int)(((uint)value << shift) | ((uint)value >> (32 - shift))); } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs index b8d50df26a0f7..6bb32c2db2db1 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/RuntimeMethodHandle.cs @@ -63,7 +63,7 @@ public bool Equals(RuntimeMethodHandle handle) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private int _rotl(int value, int shift) + private static int _rotl(int value, int shift) { return (int)(((uint)value << shift) | ((uint)value >> (32 - shift))); } diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.CoreRT.Unix.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.CoreRT.Unix.cs index a45adb76fc711..55d016d3ce418 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.CoreRT.Unix.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.CoreRT.Unix.cs @@ -28,6 +28,7 @@ private void PlatformSpecificInitializeExistingThread() _stopped = new ManualResetEvent(false); } +#pragma warning disable CA1822 private ThreadPriority GetPriorityLive() { return ThreadPriority.Normal; @@ -37,6 +38,7 @@ private bool SetPriorityLive(ThreadPriority priority) { return true; } +#pragma warning restore CA1822 [UnmanagedCallersOnly] private static void OnThreadExit() @@ -132,9 +134,7 @@ private static bool SetApartmentStateUnchecked(ApartmentState state, bool throwO return true; } - private void InitializeComOnNewThread() - { - } + partial void InitializeComOnNewThread(); internal static void InitializeComForFinalizerThread() { diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.CoreRT.Windows.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.CoreRT.Windows.cs index 9f31a0c2c6d9d..6382e21922029 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.CoreRT.Windows.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.CoreRT.Windows.cs @@ -28,9 +28,7 @@ public sealed partial class Thread private static volatile bool s_comInitializedOnFinalizerThread; - private void PlatformSpecificInitialize() - { - } + partial void PlatformSpecificInitialize(); // Platform-specific initialization of foreign threads, i.e. threads not created by Thread.Start private void PlatformSpecificInitializeExistingThread() diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.CoreRT.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.CoreRT.cs index cc6b2c3e62c2d..3416d6cae3db6 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.CoreRT.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/Threading/Thread.CoreRT.cs @@ -60,7 +60,7 @@ private void Initialize() RegisterThreadExitCallback(); } - private unsafe void RegisterThreadExitCallback() + private static unsafe void RegisterThreadExitCallback() { RuntimeImports.RhSetThreadExitCallback(&OnThreadExit); } @@ -196,10 +196,8 @@ public int ManagedThreadId get => _managedThreadId.Id; } - partial void ThreadNameChanged(string? value) - { - // TODO: Inform the debugger and the profiler - } + // TODO: Inform the debugger and the profiler + // private void ThreadNameChanged(string? value) {} public ThreadPriority Priority { diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/WeakReference.CoreRT.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/WeakReference.CoreRT.cs index 5fc7acd35b617..090dac14df2c4 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/WeakReference.CoreRT.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/WeakReference.CoreRT.cs @@ -153,7 +153,7 @@ public virtual object? Target /// and gets\create a new RCW in case it is alive. /// /// - private object? TryGetComTarget() + private static object? TryGetComTarget() { #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; @@ -174,7 +174,7 @@ public virtual object? Target /// go from the managed weak reference to the actual native object even though the managed counterpart might have been collected. /// /// - private void TrySetComTarget(object? target) + private static void TrySetComTarget(object? target) { #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; diff --git a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/WeakReference.T.CoreRT.cs b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/WeakReference.T.CoreRT.cs index 680e9bb46b4d3..ab5a5bdfa842a 100644 --- a/src/coreclr/nativeaot/System.Private.CoreLib/src/System/WeakReference.T.CoreRT.cs +++ b/src/coreclr/nativeaot/System.Private.CoreLib/src/System/WeakReference.T.CoreRT.cs @@ -78,7 +78,7 @@ private T? Target /// and gets\create a new RCW in case it is alive. /// /// - private object? TryGetComTarget() + private static object? TryGetComTarget() { #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; @@ -99,7 +99,7 @@ private T? Target /// go from the managed weak reference to the actual native object even though the managed counterpart might have been collected. /// /// - private void TrySetComTarget(object? target) + private static void TrySetComTarget(object? target) { #if ENABLE_WINRT WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks; diff --git a/src/coreclr/nativeaot/System.Private.DisabledReflection/src/Internal/Reflection/RuntimeTypeInfo.cs b/src/coreclr/nativeaot/System.Private.DisabledReflection/src/Internal/Reflection/RuntimeTypeInfo.cs index 7ff617784fc7e..07f9cd7143c96 100644 --- a/src/coreclr/nativeaot/System.Private.DisabledReflection/src/Internal/Reflection/RuntimeTypeInfo.cs +++ b/src/coreclr/nativeaot/System.Private.DisabledReflection/src/Internal/Reflection/RuntimeTypeInfo.cs @@ -23,11 +23,11 @@ public RuntimeTypeInfo(RuntimeTypeHandle typeHandle) _typeHandle = typeHandle; } - private bool DoNotThrowForNames => AppContext.TryGetSwitch("Switch.System.Reflection.Disabled.DoNotThrowForNames", out bool doNotThrow) && doNotThrow; + private static bool DoNotThrowForNames => AppContext.TryGetSwitch("Switch.System.Reflection.Disabled.DoNotThrowForNames", out bool doNotThrow) && doNotThrow; - private bool DoNotThrowForAssembly => AppContext.TryGetSwitch("Switch.System.Reflection.Disabled.DoNotThrowForAssembly", out bool doNotThrow) && doNotThrow; + private static bool DoNotThrowForAssembly => AppContext.TryGetSwitch("Switch.System.Reflection.Disabled.DoNotThrowForAssembly", out bool doNotThrow) && doNotThrow; - private bool DoNotThrowForAttributes => AppContext.TryGetSwitch("Switch.System.Reflection.Disabled.DoNotThrowForAttributes", out bool doNotThrow) && doNotThrow; + private static bool DoNotThrowForAttributes => AppContext.TryGetSwitch("Switch.System.Reflection.Disabled.DoNotThrowForAttributes", out bool doNotThrow) && doNotThrow; public override RuntimeTypeHandle TypeHandle => _typeHandle; diff --git a/src/coreclr/nativeaot/System.Private.Interop/src/Internal/Runtime/CompilerHelpers/RuntimeInteropData.CoreRT.cs b/src/coreclr/nativeaot/System.Private.Interop/src/Internal/Runtime/CompilerHelpers/RuntimeInteropData.CoreRT.cs index 1f6fa5f89c83d..ff9b6b08dceea 100644 --- a/src/coreclr/nativeaot/System.Private.Interop/src/Internal/Runtime/CompilerHelpers/RuntimeInteropData.CoreRT.cs +++ b/src/coreclr/nativeaot/System.Private.Interop/src/Internal/Runtime/CompilerHelpers/RuntimeInteropData.CoreRT.cs @@ -91,7 +91,7 @@ private static unsafe bool TryGetNativeReaderForBlob(NativeFormatModuleInfo modu return false; } - private unsafe bool GetMarshallersForDelegate(RuntimeTypeHandle delegateTypeHandle, out IntPtr openStub, out IntPtr closedStub, out IntPtr delegateCreationStub) + private static unsafe bool GetMarshallersForDelegate(RuntimeTypeHandle delegateTypeHandle, out IntPtr openStub, out IntPtr closedStub, out IntPtr delegateCreationStub) { int delegateHashcode = delegateTypeHandle.GetHashCode(); openStub = IntPtr.Zero; @@ -127,7 +127,7 @@ private unsafe bool GetMarshallersForDelegate(RuntimeTypeHandle delegateTypeHand return false; } - private unsafe bool TryGetStructData(RuntimeTypeHandle structTypeHandle, out ExternalReferencesTable externalReferences, out NativeParser entryParser) + private static unsafe bool TryGetStructData(RuntimeTypeHandle structTypeHandle, out ExternalReferencesTable externalReferences, out NativeParser entryParser) { int structHashcode = structTypeHandle.GetHashCode(); externalReferences = default(ExternalReferencesTable); @@ -156,7 +156,7 @@ private unsafe bool TryGetStructData(RuntimeTypeHandle structTypeHandle, out Ext return false; } - private unsafe bool TryGetMarshallersForStruct(RuntimeTypeHandle structTypeHandle, out IntPtr marshalStub, out IntPtr unmarshalStub, out IntPtr destroyStub, out bool hasInvalidLayout, out int size) + private static unsafe bool TryGetMarshallersForStruct(RuntimeTypeHandle structTypeHandle, out IntPtr marshalStub, out IntPtr unmarshalStub, out IntPtr destroyStub, out bool hasInvalidLayout, out int size) { marshalStub = IntPtr.Zero; unmarshalStub = IntPtr.Zero; diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/Internal/Reflection/Core/Execution/ExecutionDomain.cs b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/Internal/Reflection/Core/Execution/ExecutionDomain.cs index 2227d4a59682b..f2065074d78b3 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/Internal/Reflection/Core/Execution/ExecutionDomain.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/Internal/Reflection/Core/Execution/ExecutionDomain.cs @@ -357,7 +357,7 @@ public bool SupportsReflection(Type type) internal ReflectionDomainSetup ReflectionDomainSetup { get; } - internal IEnumerable PrimitiveTypes => s_primitiveTypes; + internal static IEnumerable PrimitiveTypes => s_primitiveTypes; private static readonly Type[] s_primitiveTypes = { diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.GetTypeCore.CaseSensitive.cs b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.GetTypeCore.CaseSensitive.cs index a9ef45fbd207e..f082c7ce50c62 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.GetTypeCore.CaseSensitive.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/Assemblies/NativeFormat/NativeFormatRuntimeAssembly.GetTypeCore.CaseSensitive.cs @@ -68,7 +68,7 @@ internal sealed override RuntimeTypeInfo UncachedGetTypeCoreCaseSensitive(string return null; } - private bool TryResolveNamespaceDefinitionCaseSensitive(MetadataReader reader, string[] namespaceParts, ScopeDefinitionHandle scopeDefinitionHandle, out NamespaceDefinition namespaceDefinition) + private static bool TryResolveNamespaceDefinitionCaseSensitive(MetadataReader reader, string[] namespaceParts, ScopeDefinitionHandle scopeDefinitionHandle, out NamespaceDefinition namespaceDefinition) { namespaceDefinition = scopeDefinitionHandle.GetScopeDefinition(reader).RootNamespaceDefinition.GetNamespaceDefinition(reader); NamespaceDefinitionHandleCollection candidates = namespaceDefinition.NamespaceDefinitions; diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/EventPolicies.cs b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/EventPolicies.cs index 8b2716dfce9f1..59262a3315552 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/EventPolicies.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/EventPolicies.cs @@ -62,7 +62,7 @@ public sealed override bool OkToIgnoreAmbiguity(EventInfo m1, EventInfo m2) return false; } - private MethodInfo GetAccessorMethod(EventInfo e) + private static MethodInfo GetAccessorMethod(EventInfo e) { MethodInfo accessor = e.AddMethod; return accessor; diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/PropertyPolicies.cs b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/PropertyPolicies.cs index 458b4f7166525..ee162bdfe9898 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/PropertyPolicies.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/BindingFlagSupport/PropertyPolicies.cs @@ -85,7 +85,7 @@ public sealed override bool OkToIgnoreAmbiguity(PropertyInfo m1, PropertyInfo m2 return false; } - private MethodInfo GetAccessorMethod(PropertyInfo property) + private static MethodInfo GetAccessorMethod(PropertyInfo property) { MethodInfo accessor = property.GetMethod; if (accessor == null) diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/ReflectionCoreCallbacksImplementation.cs b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/ReflectionCoreCallbacksImplementation.cs index fe3c3202467a7..0b211124f26b8 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/ReflectionCoreCallbacksImplementation.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/General/ReflectionCoreCallbacksImplementation.cs @@ -160,7 +160,7 @@ public sealed override PropertyInfo GetImplicitlyOverriddenBaseClassProperty(Pro return p.GetImplicitlyOverriddenBaseClassMember(); } - private FieldInfo GetFieldInfo(RuntimeTypeHandle declaringTypeHandle, FieldHandle fieldHandle) + private static FieldInfo GetFieldInfo(RuntimeTypeHandle declaringTypeHandle, FieldHandle fieldHandle) { RuntimeTypeInfo contextTypeInfo = declaringTypeHandle.GetTypeForRuntimeTypeHandle(); NativeFormatRuntimeNamedTypeInfo definingTypeInfo = contextTypeInfo.AnchoringTypeDefinitionForDeclaredMembers.CastToNativeFormatRuntimeNamedTypeInfo(); diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/RuntimeArrayTypeInfo.cs b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/RuntimeArrayTypeInfo.cs index 040b29b333d75..b2bf8de7f712b 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/RuntimeArrayTypeInfo.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/RuntimeArrayTypeInfo.cs @@ -293,7 +293,7 @@ protected sealed override string Suffix // // Arrays don't have a true typedef behind them but for the purpose of reporting base classes and interfaces, we can create a pretender. // - private RuntimeTypeInfo TypeDefInfoProjectionForArrays + private static RuntimeTypeInfo TypeDefInfoProjectionForArrays { get { diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.cs b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.cs index 877f39f4b2d09..66222d901baa6 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Core/src/System/Reflection/Runtime/TypeInfos/RuntimeTypeInfo.cs @@ -894,7 +894,7 @@ private TypeClassification Classification if (baseType == valueType && this != enumType) { classification |= TypeClassification.IsValueType; - foreach (Type primitiveType in ReflectionCoreExecution.ExecutionDomain.PrimitiveTypes) + foreach (Type primitiveType in ExecutionDomain.PrimitiveTypes) { if (this.Equals(primitiveType)) { diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.ManifestResources.cs b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.ManifestResources.cs index c7b65fdf99eab..ffc3b72e8a113 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.ManifestResources.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.ManifestResources.cs @@ -66,7 +66,7 @@ public sealed override Stream GetManifestResourceStream(Assembly assembly, strin return null; } - private unsafe Stream ReadResourceFromBlob(ResourceInfo resourceInfo) + private static unsafe Stream ReadResourceFromBlob(ResourceInfo resourceInfo) { byte* pBlob; uint cbBlob; @@ -81,9 +81,9 @@ private unsafe Stream ReadResourceFromBlob(ResourceInfo resourceInfo) return new UnmanagedMemoryStream(pBlob + resourceInfo.Index, resourceInfo.Length); } - private LowLevelList GetExtractedResources(Assembly assembly) + private static LowLevelList GetExtractedResources(Assembly assembly) { - LowLevelDictionary> extractedResourceDictionary = this.ExtractedResourceDictionary; + LowLevelDictionary> extractedResourceDictionary = ExtractedResourceDictionary; string assemblyName = assembly.GetName().FullName; LowLevelList resourceInfos; if (!extractedResourceDictionary.TryGetValue(assemblyName, out resourceInfos)) @@ -91,7 +91,7 @@ private LowLevelList GetExtractedResources(Assembly assembly) return resourceInfos; } - private LowLevelDictionary> ExtractedResourceDictionary + private static LowLevelDictionary> ExtractedResourceDictionary { get { diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.MappingTables.cs b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.MappingTables.cs index d086fbd41e9c8..c415c1fc99fa6 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.MappingTables.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ExecutionEnvironmentImplementation.MappingTables.cs @@ -43,7 +43,7 @@ namespace Internal.Reflection.Execution //========================================================================================================== internal sealed partial class ExecutionEnvironmentImplementation : ExecutionEnvironment { - private RuntimeTypeHandle GetOpenTypeDefinition(RuntimeTypeHandle typeHandle, out RuntimeTypeHandle[] typeArgumentsHandles) + private static RuntimeTypeHandle GetOpenTypeDefinition(RuntimeTypeHandle typeHandle, out RuntimeTypeHandle[] typeArgumentsHandles) { if (RuntimeAugments.IsGenericType(typeHandle)) { @@ -54,7 +54,7 @@ private RuntimeTypeHandle GetOpenTypeDefinition(RuntimeTypeHandle typeHandle, ou return typeHandle; } - private RuntimeTypeHandle GetTypeDefinition(RuntimeTypeHandle typeHandle) + private static RuntimeTypeHandle GetTypeDefinition(RuntimeTypeHandle typeHandle) { if (RuntimeAugments.IsGenericType(typeHandle)) return RuntimeAugments.GetGenericDefinition(typeHandle); @@ -475,7 +475,7 @@ private unsafe void GetDynamicMethodInvokeMethodInfo(NativeFormatModuleInfo modu } } - private IntPtr GetDynamicMethodInvokerThunk(MethodBase methodInfo) + private static IntPtr GetDynamicMethodInvokerThunk(MethodBase methodInfo) { MethodParametersInfo methodParamsInfo = new MethodParametersInfo(methodInfo); return CallConverterThunk.MakeThunk( @@ -488,7 +488,7 @@ private IntPtr GetDynamicMethodInvokerThunk(MethodBase methodInfo) null); } - private RuntimeTypeHandle[] GetDynamicInvokeInstantiationArguments(MethodBase reflectionMethodBase) + private static RuntimeTypeHandle[] GetDynamicInvokeInstantiationArguments(MethodBase reflectionMethodBase) { // The DynamicInvoke method is a generic method with arguments that match the arguments of the target method. // Prepare the list of arguments so that we can use it to instantiate the method. @@ -528,7 +528,7 @@ private static RuntimeTypeHandle[] GetTypeSequence(ref ExternalReferencesTable e return result; } - private IntPtr TryGetVirtualResolveData(NativeFormatModuleInfo module, + private static IntPtr TryGetVirtualResolveData(NativeFormatModuleInfo module, RuntimeTypeHandle methodHandleDeclaringType, QMethodDefinition methodHandle, RuntimeTypeHandle[] genericArgs, ref MethodSignatureComparer methodSignatureComparer) { @@ -696,7 +696,7 @@ private static IntPtr GetCallingConventionConverterForMethodEntrypoint(MetadataR } } - private RuntimeTypeHandle GetExactDeclaringType(RuntimeTypeHandle dstType, RuntimeTypeHandle srcType) + private static RuntimeTypeHandle GetExactDeclaringType(RuntimeTypeHandle dstType, RuntimeTypeHandle srcType) { // The fact that for generic types we rely solely on the template type in the mapping table causes // trouble for lookups from method pointer to the declaring type and method metadata handle. @@ -1224,7 +1224,7 @@ private static FunctionPointersToOffsets ComputeLdftnReverseLookup_ExactInstanti return functionPointerToOffsetInInvokeMap; } - private unsafe bool TryGetMethodForOriginalLdFtnResult_ExactInstantiation_Inner(NativeFormatModuleInfo mappingTableModule, bool forStartAddress, IntPtr canonOriginalLdFtnResult, uint parserOffset, ref RuntimeTypeHandle declaringTypeHandle, out QMethodDefinition methodHandle, out RuntimeTypeHandle[] genericMethodTypeArgumentHandles) + private static unsafe bool TryGetMethodForOriginalLdFtnResult_ExactInstantiation_Inner(NativeFormatModuleInfo mappingTableModule, bool forStartAddress, IntPtr canonOriginalLdFtnResult, uint parserOffset, ref RuntimeTypeHandle declaringTypeHandle, out QMethodDefinition methodHandle, out RuntimeTypeHandle[] genericMethodTypeArgumentHandles) { methodHandle = default(QMethodDefinition); genericMethodTypeArgumentHandles = null; @@ -1281,7 +1281,7 @@ private unsafe bool TryGetMethodForOriginalLdFtnResult_ExactInstantiation_Inner( return false; } - private unsafe bool TryGetMethodForOriginalLdFtnResult_GenericMethodWithInstantiationArgument(IntPtr instantiationArgument, ref RuntimeTypeHandle declaringTypeHandle, out QMethodDefinition methodHandle, out RuntimeTypeHandle[] genericMethodTypeArgumentHandles) + private static unsafe bool TryGetMethodForOriginalLdFtnResult_GenericMethodWithInstantiationArgument(IntPtr instantiationArgument, ref RuntimeTypeHandle declaringTypeHandle, out QMethodDefinition methodHandle, out RuntimeTypeHandle[] genericMethodTypeArgumentHandles) { MethodNameAndSignature nameAndSig; bool success = TypeLoaderEnvironment.Instance.TryGetGenericMethodComponents(instantiationArgument, out declaringTypeHandle, out nameAndSig, out genericMethodTypeArgumentHandles); @@ -1451,7 +1451,7 @@ public sealed override bool TryGetFieldFromHandleAndType(RuntimeFieldHandle runt /// Locate the static constructor context given the runtime type handle (MethodTable) for the type in question. /// /// MethodTable of the type to look up - internal unsafe IntPtr TryGetStaticClassConstructionContext(RuntimeTypeHandle typeHandle) + internal static unsafe IntPtr TryGetStaticClassConstructionContext(RuntimeTypeHandle typeHandle) { return TypeLoaderEnvironment.TryGetStaticClassConstructionContext(typeHandle); } diff --git a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ReflectionExecutionDomainCallbacksImplementation.cs b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ReflectionExecutionDomainCallbacksImplementation.cs index 991e19791f2b5..9955490999955 100644 --- a/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ReflectionExecutionDomainCallbacksImplementation.cs +++ b/src/coreclr/nativeaot/System.Private.Reflection.Execution/src/Internal/Reflection/Execution/ReflectionExecutionDomainCallbacksImplementation.cs @@ -115,7 +115,7 @@ public sealed override Assembly GetAssemblyForHandle(RuntimeTypeHandle typeHandl public sealed override IntPtr TryGetStaticClassConstructionContext(RuntimeTypeHandle runtimeTypeHandle) { - return _executionEnvironment.TryGetStaticClassConstructionContext(runtimeTypeHandle); + return ExecutionEnvironmentImplementation.TryGetStaticClassConstructionContext(runtimeTypeHandle); } /// diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Reflection/Execution/AssemblyBinderImplementation.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Reflection/Execution/AssemblyBinderImplementation.cs index 3d2cb24adcbaa..f839a2a48511d 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Reflection/Execution/AssemblyBinderImplementation.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Reflection/Execution/AssemblyBinderImplementation.cs @@ -130,7 +130,7 @@ public sealed override IList GetLoadedAssemblies() // // Encapsulates the assembly ref->def matching policy. // - private bool AssemblyNameMatches(RuntimeAssemblyName refName, RuntimeAssemblyName defName, ref Exception preferredException) + private static bool AssemblyNameMatches(RuntimeAssemblyName refName, RuntimeAssemblyName defName, ref Exception preferredException) { // // The defName came from trusted metadata so it should be fully specified. @@ -231,7 +231,7 @@ private KeyValuePair[] ScopeGroups } } - private void AddScopesFromReaderToGroups(LowLevelDictionaryWithIEnumerable groups, MetadataReader reader) + private static void AddScopesFromReaderToGroups(LowLevelDictionaryWithIEnumerable groups, MetadataReader reader) { foreach (ScopeDefinitionHandle scopeDefinitionHandle in reader.ScopeDefinitions) { diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.CallConversionInfo.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.CallConversionInfo.cs index 5562a771af20e..fba34514576c8 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.CallConversionInfo.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.CallConversionInfo.cs @@ -125,7 +125,7 @@ public bool Equals(CallConversionInfo other) return false; } - private bool ArraysAreEqual(T[] array1, T[] array2) + private static bool ArraysAreEqual(T[] array1, T[] array2) { if (array1 == null) return array2 == null; diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.CallConversionParameters.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.CallConversionParameters.cs index 2d27a3f35893a..716d818906af4 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.CallConversionParameters.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.CallConversionParameters.cs @@ -300,7 +300,7 @@ private void ComputeCalleeFlagsAndFunctionPointerForReflectionInvokeThunk() _callerArgs.Reset(); } - internal void ResetPinnedObjects() + internal static void ResetPinnedObjects() { // Reset all pinned gchandles to null. // Freeing of gchandles is done in the destructor of GCHandleContainer when the thread dies. diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.cs index 28197a93abd6e..a806f6f660ddd 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallConverterThunk.cs @@ -512,7 +512,7 @@ private static unsafe IntPtr CallConversionThunk(IntPtr callerTransitionBlockPar } finally { - conversionParams.ResetPinnedObjects(); + CallConversionParameters.ResetPinnedObjects(); } } diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallingConventions.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallingConventions.cs index b4388c891b17a..f6fe938e49bc9 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallingConventions.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/CallingConventions.cs @@ -110,6 +110,7 @@ public unsafe uint GetSize() return (uint)IntPtr.Size; } +#pragma warning disable CA1822 public bool RequiresAlign8() { #if !TARGET_ARM @@ -151,6 +152,7 @@ public CorElementType GetHFAType() #endif return CorElementType.ELEMENT_TYPE_R4; } +#pragma warning restore CA1822 public CorElementType GetCorElementType() { 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 e76c189796bb7..68b8ffcf9b3a0 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 @@ -513,7 +513,7 @@ internal override void Prepare(TypeBuilder builder) internal override IntPtr Create(TypeBuilder builder) { - IntPtr result = TypeLoaderEnvironment.Instance.TryGetDefaultConstructorForType(Type); + IntPtr result = TypeLoaderEnvironment.TryGetDefaultConstructorForType(Type); if (result == IntPtr.Zero) @@ -580,11 +580,11 @@ internal unsafe override void Prepare(TypeBuilder builder) canUseRetrieveExactFunctionPointerIfPossible = true; else if (!Method.OwningType.IsValueType) // If the owning type isn't a valuetype, concerns about unboxing stubs are moot canUseRetrieveExactFunctionPointerIfPossible = true; - else if (TypeLoaderEnvironment.Instance.IsStaticMethodSignature(MethodSignature)) // Static methods don't have unboxing stub concerns + else if (TypeLoaderEnvironment.IsStaticMethodSignature(MethodSignature)) // Static methods don't have unboxing stub concerns canUseRetrieveExactFunctionPointerIfPossible = true; if (canUseRetrieveExactFunctionPointerIfPossible && - builder.RetrieveExactFunctionPointerIfPossible(Method, out exactFunctionPointer)) + TypeBuilder.RetrieveExactFunctionPointerIfPossible(Method, out exactFunctionPointer)) { // If we succeed in finding a non-shareable function pointer for this method, it means // that we found a method body for it that was statically compiled. We'll use that body @@ -748,7 +748,7 @@ private bool NeedsDictionaryParameterToCallCanonicalVersion(MethodDesc method) if (Method is NoMetadataMethodDesc) { // If the method does not have metadata, use the NameAndSignature property which should work in that case. - if (TypeLoaderEnvironment.Instance.IsStaticMethodSignature(Method.NameAndSignature.Signature)) + if (TypeLoaderEnvironment.IsStaticMethodSignature(Method.NameAndSignature.Signature)) return true; } else @@ -784,7 +784,7 @@ internal unsafe override IntPtr Create(TypeBuilder builder) if (Method.FunctionPointer != IntPtr.Zero) { if (Method.Instantiation.Length > 0 - || TypeLoaderEnvironment.Instance.IsStaticMethodSignature(MethodSignature) + || TypeLoaderEnvironment.IsStaticMethodSignature(MethodSignature) || (Method.OwningType.IsValueType && !Method.UnboxingStub)) { Debug.Assert(methodDictionary != IntPtr.Zero); @@ -1813,7 +1813,7 @@ internal static GenericDictionaryCell ParseAndCreateCell(NativeLayoutInfoLoadCon break; default: - parser.ThrowBadImageFormatException(); + NativeParser.ThrowBadImageFormatException(); cell = null; break; } diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutFieldAlgorithm.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutFieldAlgorithm.cs index 7c2d1958a40af..054a5ec9956db 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutFieldAlgorithm.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutFieldAlgorithm.cs @@ -138,7 +138,7 @@ public override ComputedStaticFieldLayout ComputeStaticFieldLayout(DefType type, return layout; } - private ComputedStaticFieldLayout ParseStaticRegionSizesFromNativeLayout(TypeDesc type) + private static ComputedStaticFieldLayout ParseStaticRegionSizesFromNativeLayout(TypeDesc type) { LayoutInt nonGcDataSize = LayoutInt.Zero; LayoutInt gcDataSize = LayoutInt.Zero; @@ -271,7 +271,7 @@ private static NativeLayoutFieldDesc[] ParseFieldLayout(DefType owningType, /// Type we are computing layout for /// What the initial Instance size should be /// What is the basic alignment requirement of the base type or 1 if there is no base type to consider - internal void ComputeTypeSizeBeforeFields(TypeDesc type, out LayoutInt initialSize, out LayoutInt alignRequired) + internal static void ComputeTypeSizeBeforeFields(TypeDesc type, out LayoutInt initialSize, out LayoutInt alignRequired) { // Account for the MethodTable pointer in objects... initialSize = new LayoutInt(IntPtr.Size); @@ -298,7 +298,7 @@ internal void ComputeTypeSizeBeforeFields(TypeDesc type, out LayoutInt initialSi /// the conceptual location of the field /// what sort of load was requested /// - internal bool ShouldProcessField(NativeFormat.FieldStorage fieldStorage, FieldLoadState loadRequested) + internal static bool ShouldProcessField(NativeFormat.FieldStorage fieldStorage, FieldLoadState loadRequested) { if (fieldStorage == (int)NativeFormat.FieldStorage.Instance) { diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutInfoLoadContext.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutInfoLoadContext.cs index 887a9b9b06289..e6aca0b7755de 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutInfoLoadContext.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/NativeLayoutInfoLoadContext.cs @@ -56,7 +56,7 @@ private TypeDesc GetModifierType(ref NativeParser parser, TypeModifierKind modif return _typeSystemContext.GetPointerType(typeParameter); default: - parser.ThrowBadImageFormatException(); + NativeParser.ThrowBadImageFormatException(); return null; } } @@ -151,11 +151,11 @@ internal TypeDesc GetType(ref NativeParser parser) case TypeSignatureKind.FunctionPointer: Debug.Fail("NYI!"); - parser.ThrowBadImageFormatException(); + NativeParser.ThrowBadImageFormatException(); return null; default: - parser.ThrowBadImageFormatException(); + NativeParser.ThrowBadImageFormatException(); return null; } } @@ -169,7 +169,7 @@ internal MethodDesc GetMethod(ref NativeParser parser, out RuntimeSignature meth functionPointer = GetExternalReferencePointer(parser.GetUnsigned()); DefType containingType = (DefType)GetType(ref parser); - MethodNameAndSignature nameAndSignature = TypeLoaderEnvironment.Instance.GetMethodNameAndSignature(ref parser, _module.Handle, out methodNameSig, out methodSig); + MethodNameAndSignature nameAndSignature = TypeLoaderEnvironment.GetMethodNameAndSignature(ref parser, _module.Handle, out methodNameSig, out methodSig); bool unboxingStub = (flags & MethodFlags.IsUnboxingStub) != 0; diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/SerializedDebugData.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/SerializedDebugData.cs index a9543aa562b89..483742c926fa1 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/SerializedDebugData.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/SerializedDebugData.cs @@ -242,7 +242,7 @@ private unsafe void ThreadSafeWriteBytes(byte[] src) } // Helper method to serialize the data-blob type and flags - public void SerializeDataBlobTypeAndFlags(ref NativePrimitiveEncoder encoder, SerializedDataBlobKind blobType, byte flags) + public static void SerializeDataBlobTypeAndFlags(ref NativePrimitiveEncoder encoder, SerializedDataBlobKind blobType, byte flags) { // make sure that blobType fits in 2 bits and flags fits in 6 bits Debug.Assert(blobType < SerializedDataBlobKind.Limit); @@ -320,7 +320,7 @@ public static void RegisterDebugDataForType(TypeBuilder typeBuilder, DefType def sharedTypeFlags |= SerializedDebugData.SharedTypeFlags.HasStaticFields; } - Instance.SerializeDataBlobTypeAndFlags(ref encoder, SerializedDataBlobKind.SharedType, (byte)sharedTypeFlags); + SerializeDataBlobTypeAndFlags(ref encoder, SerializedDataBlobKind.SharedType, (byte)sharedTypeFlags); // // The order of these writes is a contract shared between the runtime and debugger engine. @@ -443,7 +443,7 @@ public static void RegisterDebugDataForNativeFormatType(TypeBuilder typeBuilder, byte nativeFormatTypeFlags = 0; - Instance.SerializeDataBlobTypeAndFlags( + SerializeDataBlobTypeAndFlags( ref encoder, SerializedDataBlobKind.NativeFormatType, nativeFormatTypeFlags); @@ -468,7 +468,7 @@ public static void RegisterDebugDataForMethod(TypeBuilder typeBuilder, Instantia byte sharedMethodFlags = 0; sharedMethodFlags |= (byte)(method.OwningType.IsGeneric() ? SharedMethodFlags.HasDeclaringTypeHandle : 0); - Instance.SerializeDataBlobTypeAndFlags(ref encoder, SerializedDataBlobKind.SharedMethod, sharedMethodFlags); + SerializeDataBlobTypeAndFlags(ref encoder, SerializedDataBlobKind.SharedMethod, sharedMethodFlags); encoder.WriteUnsignedLong((ulong)method.RuntimeMethodDictionary.ToInt64()); encoder.WriteUnsigned((uint)method.Instantiation.Length); @@ -502,7 +502,7 @@ public static void RegisterTailCallThunk(IntPtr thunk) // Write out the size of thunks used by the calling convention converter // Make sure that this is called only once encoder.Init(); - Instance.SerializeDataBlobTypeAndFlags(ref encoder, + SerializeDataBlobTypeAndFlags(ref encoder, SerializedDataBlobKind.StepThroughStubSize, (byte)StepThroughStubFlags.IsTailCallStub); encoder.WriteUnsigned((uint)RuntimeAugments.GetThunkSize()); @@ -513,7 +513,7 @@ public static void RegisterTailCallThunk(IntPtr thunk) } encoder.Init(); - Instance.SerializeDataBlobTypeAndFlags(ref encoder, + SerializeDataBlobTypeAndFlags(ref encoder, SerializedDataBlobKind.StepThroughStubAddress, (byte)StepThroughStubFlags.IsTailCallStub); encoder.WriteUnsignedLong((ulong)thunk.ToInt64()); diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TemplateLocator.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TemplateLocator.cs index 2a3fa2e363eaf..e36e67a158bd8 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TemplateLocator.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TemplateLocator.cs @@ -22,7 +22,7 @@ internal struct TemplateLocator // // Returns the template type handle for a generic instantation type // - public TypeDesc TryGetTypeTemplate(TypeDesc concreteType, ref NativeLayoutInfo nativeLayoutInfo) + public static TypeDesc TryGetTypeTemplate(TypeDesc concreteType, ref NativeLayoutInfo nativeLayoutInfo) { #if GENERICS_FORCE_USG return TryGetUniversalTypeTemplate(concreteType, ref nativeLayoutInfo); @@ -38,7 +38,7 @@ public TypeDesc TryGetTypeTemplate(TypeDesc concreteType, ref NativeLayoutInfo n #endif } - public TypeDesc TryGetUniversalTypeTemplate(TypeDesc concreteType, ref NativeLayoutInfo nativeLayoutInfo) + public static TypeDesc TryGetUniversalTypeTemplate(TypeDesc concreteType, ref NativeLayoutInfo nativeLayoutInfo) { return TryGetTypeTemplate_Internal(concreteType, CanonicalFormKind.Universal, out nativeLayoutInfo.Module, out nativeLayoutInfo.Offset); } @@ -53,7 +53,7 @@ public TypeDesc TryGetNonUniversalTypeTemplate(TypeDesc concreteType, ref Native /// /// Get the NativeLayout for a type from a ReadyToRun image. /// - public bool TryGetMetadataNativeLayout(TypeDesc concreteType, out NativeFormatModuleInfo nativeLayoutInfoModule, out uint nativeLayoutInfoToken) + public static bool TryGetMetadataNativeLayout(TypeDesc concreteType, out NativeFormatModuleInfo nativeLayoutInfoModule, out uint nativeLayoutInfoToken) { nativeLayoutInfoModule = null; nativeLayoutInfoToken = 0; @@ -109,7 +109,7 @@ public bool TryGetMetadataNativeLayout(TypeDesc concreteType, out NativeFormatMo /// /// Get the NativeLayout for a method from a ReadyToRun image. /// - public bool TryGetMetadataNativeLayout(MethodDesc concreteMethod, out NativeFormatModuleInfo nativeLayoutInfoModule, out uint nativeLayoutInfoToken) + public static bool TryGetMetadataNativeLayout(MethodDesc concreteMethod, out NativeFormatModuleInfo nativeLayoutInfoModule, out uint nativeLayoutInfoToken) { nativeLayoutInfoModule = null; nativeLayoutInfoToken = 0; @@ -161,7 +161,7 @@ public bool TryGetMetadataNativeLayout(MethodDesc concreteMethod, out NativeForm return false; } - private TypeDesc TryGetTypeTemplate_Internal(TypeDesc concreteType, CanonicalFormKind kind, out NativeFormatModuleInfo nativeLayoutInfoModule, out uint nativeLayoutInfoToken) + private static TypeDesc TryGetTypeTemplate_Internal(TypeDesc concreteType, CanonicalFormKind kind, out NativeFormatModuleInfo nativeLayoutInfoModule, out uint nativeLayoutInfoToken) { nativeLayoutInfoModule = null; nativeLayoutInfoToken = 0; @@ -212,7 +212,7 @@ private TypeDesc TryGetTypeTemplate_Internal(TypeDesc concreteType, CanonicalFor // // Returns the template method for a generic method instantation // - public InstantiatedMethod TryGetGenericMethodTemplate(InstantiatedMethod concreteMethod, out NativeFormatModuleInfo nativeLayoutInfoModule, out uint nativeLayoutInfoToken) + public static InstantiatedMethod TryGetGenericMethodTemplate(InstantiatedMethod concreteMethod, out NativeFormatModuleInfo nativeLayoutInfoModule, out uint nativeLayoutInfoToken) { // First, see if there is a specific canonical template InstantiatedMethod result = TryGetGenericMethodTemplate_Internal(concreteMethod, CanonicalFormKind.Specific, out nativeLayoutInfoModule, out nativeLayoutInfoToken); @@ -223,7 +223,7 @@ public InstantiatedMethod TryGetGenericMethodTemplate(InstantiatedMethod concret return result; } - private InstantiatedMethod TryGetGenericMethodTemplate_Internal(InstantiatedMethod concreteMethod, CanonicalFormKind kind, out NativeFormatModuleInfo nativeLayoutInfoModule, out uint nativeLayoutInfoToken) + private static InstantiatedMethod TryGetGenericMethodTemplate_Internal(InstantiatedMethod concreteMethod, CanonicalFormKind kind, out NativeFormatModuleInfo nativeLayoutInfoModule, out uint nativeLayoutInfoToken) { nativeLayoutInfoModule = null; nativeLayoutInfoToken = 0; @@ -232,7 +232,7 @@ private InstantiatedMethod TryGetGenericMethodTemplate_Internal(InstantiatedMeth foreach (NativeFormatModuleInfo moduleInfo in ModuleList.EnumerateModules()) { - NativeReader nativeLayoutReader = TypeLoaderEnvironment.Instance.GetNativeLayoutInfoReader(moduleInfo.Handle); + NativeReader nativeLayoutReader = TypeLoaderEnvironment.GetNativeLayoutInfoReader(moduleInfo.Handle); if (nativeLayoutReader == null) continue; @@ -286,7 +286,7 @@ private InstantiatedMethod TryGetGenericMethodTemplate_Internal(InstantiatedMeth } // Lazy loadings of hashtables (load on-demand only) - private unsafe NativeHashtable LoadHashtable(NativeFormatModuleInfo module, ReflectionMapBlob hashtableBlobId, out ExternalReferencesTable externalFixupsTable) + private static unsafe NativeHashtable LoadHashtable(NativeFormatModuleInfo module, ReflectionMapBlob hashtableBlobId, out ExternalReferencesTable externalFixupsTable) { // Load the common fixups table externalFixupsTable = default(ExternalReferencesTable); 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 d7ba8aabd1ee8..49bfd039339e6 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 @@ -106,7 +106,7 @@ internal class MissingTemplateException : Exception } - private bool CheckAllHandlesValidForMethod(MethodDesc method) + private static bool CheckAllHandlesValidForMethod(MethodDesc method) { if (!method.OwningType.RetrieveRuntimeTypeHandleIfPossible()) return false; @@ -118,7 +118,7 @@ private bool CheckAllHandlesValidForMethod(MethodDesc method) return true; } - internal bool RetrieveExactFunctionPointerIfPossible(MethodDesc method, out IntPtr result) + internal static bool RetrieveExactFunctionPointerIfPossible(MethodDesc method, out IntPtr result) { result = IntPtr.Zero; @@ -132,7 +132,7 @@ internal bool RetrieveExactFunctionPointerIfPossible(MethodDesc method, out IntP return TypeLoaderEnvironment.Instance.TryLookupExactMethodPointerForComponents(method.OwningType.RuntimeTypeHandle, method.NameAndSignature, genMethodArgs, out result); } - internal bool RetrieveMethodDictionaryIfPossible(InstantiatedMethod method) + internal static bool RetrieveMethodDictionaryIfPossible(InstantiatedMethod method) { if (method.RuntimeMethodDictionary != IntPtr.Zero) return true; @@ -274,7 +274,7 @@ internal void PrepareType(TypeDesc type) { // This call to ComputeTemplate will find the native layout info for the type, and the template // For metadata loaded types, a template will not exist, but we may find the NativeLayout describing the generic dictionary - typeAsDefType.ComputeTemplate(state, false); + TypeDesc.ComputeTemplate(state, false); Debug.Assert(state.TemplateType == null || (state.TemplateType is DefType && !state.TemplateType.RuntimeTypeHandle.IsNull())); @@ -305,7 +305,7 @@ internal void PrepareType(TypeDesc type) if (typeAsArrayType.IsSzArray && !typeAsArrayType.ElementType.IsPointer) { - typeAsArrayType.ComputeTemplate(state); + TypeDesc.ComputeTemplate(state); Debug.Assert(state.TemplateType != null && state.TemplateType is ArrayType && !state.TemplateType.RuntimeTypeHandle.IsNull()); ParseNativeLayoutInfo(state, type); @@ -384,7 +384,7 @@ private void ProcessTypesNeedingPreparation() } } - private GenericDictionaryCell[] GetGenericMethodDictionaryCellsForMetadataBasedLoad(InstantiatedMethod method, InstantiatedMethod nonTemplateMethod) + private static GenericDictionaryCell[] GetGenericMethodDictionaryCellsForMetadataBasedLoad(InstantiatedMethod method, InstantiatedMethod nonTemplateMethod) { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING uint r2rNativeLayoutInfoToken; @@ -433,7 +433,7 @@ internal void ParseNativeLayoutInfo(InstantiatedMethod method) uint nativeLayoutInfoToken; NativeFormatModuleInfo nativeLayoutModule; - MethodDesc templateMethod = (new TemplateLocator()).TryGetGenericMethodTemplate(nonTemplateMethod, out nativeLayoutModule, out nativeLayoutInfoToken); + MethodDesc templateMethod = TemplateLocator.TryGetGenericMethodTemplate(nonTemplateMethod, out nativeLayoutModule, out nativeLayoutInfoToken); // If the templateMethod found in the static image is missing or universal, see if the R2R layout // can provide something more specific. @@ -465,7 +465,7 @@ internal void ParseNativeLayoutInfo(InstantiatedMethod method) // its template MUST be a universal canonical template method Debug.Assert(!method.IsNonSharableMethod || (method.IsNonSharableMethod && templateMethod.IsCanonicalMethod(CanonicalFormKind.Universal))); - NativeReader nativeLayoutInfoReader = TypeLoaderEnvironment.Instance.GetNativeLayoutInfoReader(nativeLayoutModule.Handle); + NativeReader nativeLayoutInfoReader = TypeLoaderEnvironment.GetNativeLayoutInfoReader(nativeLayoutModule.Handle); var methodInfoParser = new NativeParser(nativeLayoutInfoReader, nativeLayoutInfoToken); var context = new NativeLayoutInfoLoadContext @@ -986,7 +986,7 @@ private unsafe void AllocateRuntimeType(TypeDesc type) TypeLoaderLogger.WriteLine("Allocated new type " + type.ToString() + " with hashcode value = 0x" + type.GetHashCode().LowLevelToString() + " with MethodTable = " + rtt.ToIntPtr().LowLevelToString() + " of size " + rtt.ToEETypePtr()->BaseSize.LowLevelToString()); } - private void AllocateRuntimeMethodDictionary(InstantiatedMethod method) + private static void AllocateRuntimeMethodDictionary(InstantiatedMethod method) { Debug.Assert(method.RuntimeMethodDictionary == IntPtr.Zero && method.Dictionary != null); @@ -1084,6 +1084,7 @@ private unsafe void FinishVTableCallingConverterThunks(TypeDesc type, TypeBuilde // Returns either the registered type handle or half-baked type handle. This method should be only called // during final phase of type building. // +#pragma warning disable CA1822 public RuntimeTypeHandle GetRuntimeTypeHandle(TypeDesc type) { #if DEBUG @@ -1098,6 +1099,7 @@ public RuntimeTypeHandle GetRuntimeTypeHandle(TypeDesc type) Debug.Assert(!rtth.IsNull()); return rtth; } +#pragma warning restore CA1822 public RuntimeTypeHandle[] GetRuntimeTypeHandles(Instantiation types) { @@ -1634,7 +1636,7 @@ internal void BuildType(TypeDesc type) FinishTypeAndMethodBuilding(); } - internal bool TryComputeFieldOffset(DefType declaringType, uint fieldOrdinal, out int fieldOffset) + internal static bool TryComputeFieldOffset(DefType declaringType, uint fieldOrdinal, out int fieldOffset) { TypeLoaderLogger.WriteLine("Computing offset of field #" + fieldOrdinal.LowLevelToString() + " on type " + declaringType.ToString()); @@ -1692,7 +1694,7 @@ private unsafe IntPtr BuildGenericLookupTarget(TypeSystemContext typeSystemConte IntPtr** lazySignature = (IntPtr**)signature.ToPointer(); typeManager = new TypeManagerHandle(lazySignature[0][0]); offset = checked((uint)new IntPtr(lazySignature[1]).ToInt32()); - reader = TypeLoaderEnvironment.Instance.GetNativeLayoutInfoReader(typeManager); + reader = TypeLoaderEnvironment.GetNativeLayoutInfoReader(typeManager); NativeParser parser = new NativeParser(reader, offset); @@ -1911,11 +1913,11 @@ private unsafe IntPtr BuildFloatingDictionary(TypeSystemContext typeSystemContex uint nativeLayoutInfoToken; NativeFormatModuleInfo nativeLayoutModule; - MethodDesc templateMethod = (new TemplateLocator()).TryGetGenericMethodTemplate(methodContext, out nativeLayoutModule, out nativeLayoutInfoToken); + MethodDesc templateMethod = TemplateLocator.TryGetGenericMethodTemplate(methodContext, out nativeLayoutModule, out nativeLayoutInfoToken); if (templateMethod == null) throw new TypeBuilder.MissingTemplateException(); - NativeReader nativeLayoutInfoReader = TypeLoaderEnvironment.Instance.GetNativeLayoutInfoReader(nativeLayoutModule.Handle); + NativeReader nativeLayoutInfoReader = TypeLoaderEnvironment.GetNativeLayoutInfoReader(nativeLayoutModule.Handle); nativeLayoutParser = new NativeParser(nativeLayoutInfoReader, nativeLayoutInfoToken); nlilContext = new NativeLayoutInfoLoadContext @@ -2191,7 +2193,7 @@ public static bool TryGetFieldOffset(RuntimeTypeHandle declaringTypeHandle, uint DefType declaringType = (DefType)context.ResolveRuntimeTypeHandle(declaringTypeHandle); Debug.Assert(declaringType.HasInstantiation); - bool success = new TypeBuilder().TryComputeFieldOffset(declaringType, fieldOrdinal, out fieldOffset); + bool success = TypeBuilder.TryComputeFieldOffset(declaringType, fieldOrdinal, out fieldOffset); TypeSystemContextFactory.Recycle(context); diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs index 8105f9d168754..85037bae3fa1e 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeBuilderState.cs @@ -126,7 +126,7 @@ public TypeDesc TemplateType } // Locate the template type and native layout info - _templateType = TypeBeingBuilt.Context.TemplateLookup.TryGetTypeTemplate(TypeBeingBuilt, ref _nativeLayoutInfo); + _templateType = TemplateLocator.TryGetTypeTemplate(TypeBeingBuilt, ref _nativeLayoutInfo); Debug.Assert(_templateType == null || !_templateType.RuntimeTypeHandle.IsNull()); _templateTypeLoaderNativeLayout = true; @@ -159,7 +159,7 @@ private void EnsureNativeLayoutInfoComputed() } if (!_nativeLayoutTokenComputed) { - TypeBeingBuilt.Context.TemplateLookup.TryGetMetadataNativeLayout(TypeBeingBuilt, out _r2rnativeLayoutInfo.Module, out _r2rnativeLayoutInfo.Offset); + TemplateLocator.TryGetMetadataNativeLayout(TypeBeingBuilt, out _r2rnativeLayoutInfo.Module, out _r2rnativeLayoutInfo.Offset); if (_r2rnativeLayoutInfo.Module != null) _readyToRunNativeLayout = true; @@ -208,7 +208,7 @@ private static void FinishInitNativeLayoutInfo(TypeDesc type, ref NativeLayoutIn nativeLayoutInfoLoadContext._methodArgumentHandles = new Instantiation(null); - nativeLayoutInfo.Reader = TypeLoaderEnvironment.Instance.GetNativeLayoutInfoReader(nativeLayoutInfo.Module.Handle); + nativeLayoutInfo.Reader = TypeLoaderEnvironment.GetNativeLayoutInfoReader(nativeLayoutInfo.Module.Handle); nativeLayoutInfo.LoadContext = nativeLayoutInfoLoadContext; } @@ -252,7 +252,7 @@ public NativeParser GetParserForUniversalNativeLayoutInfo(out NativeLayoutInfoLo { universalLayoutInfo = new NativeLayoutInfo(); universalLayoutLoadContext = null; - TypeDesc universalTemplate = TypeBeingBuilt.Context.TemplateLookup.TryGetUniversalTypeTemplate(TypeBeingBuilt, ref universalLayoutInfo); + TypeDesc universalTemplate = TemplateLocator.TryGetUniversalTypeTemplate(TypeBeingBuilt, ref universalLayoutInfo); if (universalTemplate == null) return new NativeParser(); @@ -788,7 +788,7 @@ private IEnumerable GetFieldsForGCLayout() /// /// /// - private unsafe TypeBuilder.GCLayout GetInstanceGCLayout(TypeDesc type) + private static unsafe TypeBuilder.GCLayout GetInstanceGCLayout(TypeDesc type) { Debug.Assert(!type.IsCanonicalSubtype(CanonicalFormKind.Any)); Debug.Assert(!type.IsValueType); @@ -821,7 +821,7 @@ private unsafe TypeBuilder.GCLayout GetInstanceGCLayout(TypeDesc type) /// NOTE: if the fieldtype is a reference type, this function will return GCLayout.None /// Consumers of the api must handle that special case. /// - private unsafe TypeBuilder.GCLayout GetFieldGCLayout(TypeDesc fieldType) + private static unsafe TypeBuilder.GCLayout GetFieldGCLayout(TypeDesc fieldType) { if (!fieldType.IsValueType) { @@ -1064,6 +1064,7 @@ public uint NullableValueOffset } } +#pragma warning disable CA1822 public bool IsHFA { get @@ -1083,6 +1084,7 @@ public bool IsHFA #endif } } +#pragma warning restore CA1822 public VTableLayoutInfo[] VTableMethodSignatures; public int NumSealedVTableMethodSignatures; diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.ConstructedGenericMethodsLookup.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.ConstructedGenericMethodsLookup.cs index f41f37821909d..2210d3f6b9ece 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.ConstructedGenericMethodsLookup.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.ConstructedGenericMethodsLookup.cs @@ -361,9 +361,8 @@ public bool TryGetGenericVirtualMethodPointer(RuntimeTypeHandle targetTypeHandle } // If we cannot find an exact method entry point, look for an equivalent template and compute the generic dictinoary - TemplateLocator templateLocator = new TemplateLocator(); NativeLayoutInfo nativeLayoutInfo = new NativeLayoutInfo(); - InstantiatedMethod templateMethod = templateLocator.TryGetGenericMethodTemplate(method, out nativeLayoutInfo.Module, out nativeLayoutInfo.Offset); + InstantiatedMethod templateMethod = TemplateLocator.TryGetGenericMethodTemplate(method, out nativeLayoutInfo.Module, out nativeLayoutInfo.Offset); if (templateMethod == null) return false; @@ -444,7 +443,7 @@ private bool TryGetDynamicGenericMethodDictionaryForComponents(GenericMethodLook return true; } } - private bool TryGetStaticGenericMethodDictionaryForComponents(GenericMethodLookupData lookupData, out IntPtr result) + private static bool TryGetStaticGenericMethodDictionaryForComponents(GenericMethodLookupData lookupData, out IntPtr result) { // Search the hashtable for a generic instantiation match diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.ConstructedGenericTypesLookup.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.ConstructedGenericTypesLookup.cs index 4ebc79b218955..aa54690ca942d 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.ConstructedGenericTypesLookup.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.ConstructedGenericTypesLookup.cs @@ -288,7 +288,7 @@ private unsafe bool TryGetDynamicGenericTypeForComponents(GenericTypeLookupData } } - internal unsafe bool TryGetStaticGenericTypeForComponents(GenericTypeLookupData lookupData, out RuntimeTypeHandle runtimeTypeHandle) + internal static unsafe bool TryGetStaticGenericTypeForComponents(GenericTypeLookupData lookupData, out RuntimeTypeHandle runtimeTypeHandle) { // Search the hashtable for a generic instantiation match // TODO multi-file: consider whether we can limit the search somehow, 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 a0a0854ec2da7..e521b9ef3a792 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 @@ -125,7 +125,7 @@ private static unsafe bool TryGetFieldAccessMetadataFromFieldAccessMap( { CanonicallyEquivalentEntryLocator canonWrapper = new CanonicallyEquivalentEntryLocator(declaringTypeHandle, canonFormKind); string fieldName = null; - RuntimeTypeHandle declaringTypeHandleDefinition = Instance.GetTypeDefinition(declaringTypeHandle); + RuntimeTypeHandle declaringTypeHandleDefinition = TypeLoaderEnvironment.GetTypeDefinition(declaringTypeHandle); foreach (NativeFormatModuleInfo mappingTableModule in ModuleList.EnumerateModules(RuntimeAugments.GetModuleFromTypeHandle(declaringTypeHandle))) { diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.GVMResolution.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.GVMResolution.cs index c586cccadc9b6..99f7272b3ec9d 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.GVMResolution.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.GVMResolution.cs @@ -101,7 +101,7 @@ public bool TryGetGenericVirtualTargetForTypeAndSlot(RuntimeTypeHandle targetHan } } - private MethodNameAndSignature GetMethodNameAndSignatureFromNativeReader(NativeReader nativeLayoutReader, TypeManagerHandle moduleHandle, uint nativeLayoutOffset) + private static MethodNameAndSignature GetMethodNameAndSignatureFromNativeReader(NativeReader nativeLayoutReader, TypeManagerHandle moduleHandle, uint nativeLayoutOffset) { NativeParser parser = new NativeParser(nativeLayoutReader, nativeLayoutOffset); @@ -116,7 +116,7 @@ private MethodNameAndSignature GetMethodNameAndSignatureFromNativeReader(NativeR return new MethodNameAndSignature(methodName, methodSig); } - private RuntimeTypeHandle GetOpenTypeDefinition(RuntimeTypeHandle typeHandle, out RuntimeTypeHandle[] typeArgumentsHandles) + private static RuntimeTypeHandle GetOpenTypeDefinition(RuntimeTypeHandle typeHandle, out RuntimeTypeHandle[] typeArgumentsHandles) { if (RuntimeAugments.IsGenericType(typeHandle)) return RuntimeAugments.GetGenericInstantiation(typeHandle, out typeArgumentsHandles); @@ -125,7 +125,7 @@ private RuntimeTypeHandle GetOpenTypeDefinition(RuntimeTypeHandle typeHandle, ou return typeHandle; } - private RuntimeTypeHandle GetTypeDefinition(RuntimeTypeHandle typeHandle) + private static RuntimeTypeHandle GetTypeDefinition(RuntimeTypeHandle typeHandle) { if (RuntimeAugments.IsGenericType(typeHandle)) return RuntimeAugments.GetGenericDefinition(typeHandle); @@ -133,7 +133,7 @@ private RuntimeTypeHandle GetTypeDefinition(RuntimeTypeHandle typeHandle) return typeHandle; } - private bool FindMatchingInterfaceSlot(NativeFormatModuleInfo module, NativeReader nativeLayoutReader, ref NativeParser entryParser, ref ExternalReferencesTable extRefs, ref RuntimeTypeHandle declaringType, ref MethodNameAndSignature methodNameAndSignature, RuntimeTypeHandle instanceTypeHandle, RuntimeTypeHandle openTargetTypeHandle, RuntimeTypeHandle[] targetTypeInstantiation, bool variantDispatch, bool defaultMethods) + private static bool FindMatchingInterfaceSlot(NativeFormatModuleInfo module, NativeReader nativeLayoutReader, ref NativeParser entryParser, ref ExternalReferencesTable extRefs, ref RuntimeTypeHandle declaringType, ref MethodNameAndSignature methodNameAndSignature, RuntimeTypeHandle instanceTypeHandle, RuntimeTypeHandle openTargetTypeHandle, RuntimeTypeHandle[] targetTypeInstantiation, bool variantDispatch, bool defaultMethods) { uint numTargetImplementations = entryParser.GetUnsigned(); @@ -280,7 +280,7 @@ private bool FindMatchingInterfaceSlot(NativeFormatModuleInfo module, NativeRead return false; } - private bool ResolveInterfaceGenericVirtualMethodSlot(RuntimeTypeHandle targetTypeHandle, bool lookForDefaultImplementation, ref RuntimeTypeHandle declaringType, ref MethodNameAndSignature methodNameAndSignature) + private static bool ResolveInterfaceGenericVirtualMethodSlot(RuntimeTypeHandle targetTypeHandle, bool lookForDefaultImplementation, ref RuntimeTypeHandle declaringType, ref MethodNameAndSignature methodNameAndSignature) { if (IsPregeneratedOrTemplateRuntimeTypeHandle(targetTypeHandle)) { @@ -328,7 +328,7 @@ private bool ResolveInterfaceGenericVirtualMethodSlot(RuntimeTypeHandle targetTy } } - private bool ResolveInterfaceGenericVirtualMethodSlot_Static(RuntimeTypeHandle targetTypeHandle, bool lookForDefaultImplementation, ref RuntimeTypeHandle declaringType, ref MethodNameAndSignature methodNameAndSignature) + private static bool ResolveInterfaceGenericVirtualMethodSlot_Static(RuntimeTypeHandle targetTypeHandle, bool lookForDefaultImplementation, ref RuntimeTypeHandle declaringType, ref MethodNameAndSignature methodNameAndSignature) { // Get the open type definition of the containing type of the generic virtual method being resolved RuntimeTypeHandle openCallingTypeHandle = GetTypeDefinition(declaringType); diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.Metadata.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.Metadata.cs index 820ea6ddb7dec..bc1b0b3e7eca7 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.Metadata.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.Metadata.cs @@ -384,7 +384,7 @@ public bool TryGetArrayTypeHandleForNonDynamicArrayTypeFromTemplateTable(ArrayTy } // Lazy loadings of hashtables (load on-demand only) - private unsafe NativeHashtable LoadHashtable(NativeFormatModuleInfo module, ReflectionMapBlob hashtableBlobId, out ExternalReferencesTable externalFixupsTable) + private static unsafe NativeHashtable LoadHashtable(NativeFormatModuleInfo module, ReflectionMapBlob hashtableBlobId, out ExternalReferencesTable externalFixupsTable) { // Load the common fixups table externalFixupsTable = default(ExternalReferencesTable); @@ -491,7 +491,7 @@ private static unsafe bool TryGetNativeReaderForBlob(NativeFormatModuleInfo modu /// /// TypeDesc for the type in question /// Function pointer representing the constructor, IntPtr.Zero when not found - internal IntPtr TryGetDefaultConstructorForType(TypeDesc type) + internal static IntPtr TryGetDefaultConstructorForType(TypeDesc type) { // Try to find the default constructor in metadata first IntPtr result = IntPtr.Zero; @@ -589,7 +589,7 @@ public IntPtr TryGetDefaultConstructorForType(RuntimeTypeHandle runtimeTypeHandl /// /// Lookup default constructor via the typesystem api surface and such /// - private IntPtr TryGetDefaultConstructorForTypeViaMetadata_Inner(TypeDesc type) + private static IntPtr TryGetDefaultConstructorForTypeViaMetadata_Inner(TypeDesc type) { IntPtr metadataLookupResult = IntPtr.Zero; @@ -616,7 +616,7 @@ private IntPtr TryGetDefaultConstructorForTypeViaMetadata_Inner(TypeDesc type) /// Module to search for the constructor /// Canonically equivalent entry locator representing the type /// Function pointer representing the constructor, IntPtr.Zero when not found - internal unsafe IntPtr TryGetDefaultConstructorForType_Inner(NativeFormatModuleInfo mappingTableModule, ref CanonicallyEquivalentEntryLocator canonHelper) + internal static unsafe IntPtr TryGetDefaultConstructorForType_Inner(NativeFormatModuleInfo mappingTableModule, ref CanonicallyEquivalentEntryLocator canonHelper) { NativeReader invokeMapReader; if (TryGetNativeReaderForBlob(mappingTableModule, ReflectionMapBlob.InvokeMap, out invokeMapReader)) diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.MethodAddress.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.MethodAddress.cs index f91e640f6f6a2..d43a4dc2891ec 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.MethodAddress.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.MethodAddress.cs @@ -229,7 +229,7 @@ private static DispatchCellInfo ConvertDispatchCellInfo_Inner(NativeFormatModule /// /// Resolve a dispatch on an interface MethodTable/slot index pair to a function pointer /// - private unsafe bool TryResolveTypeSlotDispatch_Inner(MethodTable* pTargetType, MethodTable* pInterfaceType, ushort slot, out IntPtr methodAddress) + private static unsafe bool TryResolveTypeSlotDispatch_Inner(MethodTable* pTargetType, MethodTable* pInterfaceType, ushort slot, out IntPtr methodAddress) { methodAddress = IntPtr.Zero; 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 e27d2336ffcfb..06a7ade1eaa85 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 @@ -163,7 +163,7 @@ public bool TryGetMethodNameAndSignatureFromNativeLayoutOffset(TypeManagerHandle return true; } - internal MethodNameAndSignature GetMethodNameAndSignature(ref NativeParser parser, TypeManagerHandle moduleHandle, out RuntimeSignature methodNameSig, out RuntimeSignature methodSig) + internal static MethodNameAndSignature GetMethodNameAndSignature(ref NativeParser parser, TypeManagerHandle moduleHandle, out RuntimeSignature methodNameSig, out RuntimeSignature methodSig) { methodNameSig = RuntimeSignature.CreateFromNativeLayoutSignature(moduleHandle, parser.Offset); string methodName = parser.GetString(); @@ -177,7 +177,7 @@ internal MethodNameAndSignature GetMethodNameAndSignature(ref NativeParser parse return new MethodNameAndSignature(methodName, methodSig); } - internal bool IsStaticMethodSignature(RuntimeSignature methodSig) + internal static bool IsStaticMethodSignature(RuntimeSignature methodSig) { if (methodSig.IsNativeLayoutSignature) { @@ -526,7 +526,7 @@ private bool TypeSignatureHasVarsNeedingCallingConventionConverter(ref NativePar return false; default: - parser.ThrowBadImageFormatException(); + NativeParser.ThrowBadImageFormatException(); return true; } } @@ -557,7 +557,7 @@ private bool TryGetTypeFromSimpleTypeSignature(ref NativeParser parser, NativeFo return false; } - private RuntimeTypeHandle GetExternalTypeHandle(NativeFormatModuleInfo moduleHandle, uint typeIndex) + private static RuntimeTypeHandle GetExternalTypeHandle(NativeFormatModuleInfo moduleHandle, uint typeIndex) { Debug.Assert(moduleHandle != null); @@ -578,7 +578,7 @@ private RuntimeTypeHandle GetExternalTypeHandle(NativeFormatModuleInfo moduleHan return result; } - private uint GetGenericArgCountFromSig(NativeParser parser) + private static uint GetGenericArgCountFromSig(NativeParser parser) { MethodCallingConvention callingConvention = (MethodCallingConvention)parser.GetUnsigned(); diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.StaticsLookup.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.StaticsLookup.cs index db22977baba40..95a09386f40e9 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.StaticsLookup.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.StaticsLookup.cs @@ -264,7 +264,7 @@ public void RegisterDynamicThreadStaticsInfo(RuntimeTypeHandle runtimeTypeHandle #region Privates // get the statics hash table, external references, and static info table for a module // TODO multi-file: consider whether we want to cache this info - private unsafe bool GetStaticsInfoHashtable(NativeFormatModuleInfo module, out NativeHashtable staticsInfoHashtable, out ExternalReferencesTable externalReferencesLookup, out ExternalReferencesTable staticInfoLookup) + private static unsafe bool GetStaticsInfoHashtable(NativeFormatModuleInfo module, out NativeHashtable staticsInfoHashtable, out ExternalReferencesTable externalReferencesLookup, out ExternalReferencesTable staticInfoLookup) { byte* pBlob; uint cbBlob; @@ -290,7 +290,7 @@ private unsafe bool GetStaticsInfoHashtable(NativeFormatModuleInfo module, out N return true; } - private NativeParser GetStaticInfo(RuntimeTypeHandle instantiatedType, out ExternalReferencesTable staticsInfoLookup) + private static NativeParser GetStaticInfo(RuntimeTypeHandle instantiatedType, out ExternalReferencesTable staticsInfoLookup) { TypeManagerHandle moduleHandle = RuntimeAugments.GetModuleFromTypeHandle(instantiatedType); NativeFormatModuleInfo module = ModuleList.Instance.GetModuleInfoByHandle(moduleHandle); @@ -316,7 +316,7 @@ private NativeParser GetStaticInfo(RuntimeTypeHandle instantiatedType, out Exter return new NativeParser(); } - private unsafe IntPtr TryCreateDictionaryCellWithValue(uint value) + private static unsafe IntPtr TryCreateDictionaryCellWithValue(uint value) { return PermanentAllocatedMemoryBlobs.GetPointerToUInt(value); } diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.cs index 361311060cd18..6ab6f7c4fb3b0 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/Runtime/TypeLoader/TypeLoaderEnvironment.cs @@ -107,7 +107,7 @@ public static IntPtr NativeLayoutSignature(this RuntimeSignature signature) if (!signature.IsNativeLayoutSignature) Environment.FailFast("Not a valid native layout signature"); - NativeReader reader = TypeLoaderEnvironment.Instance.GetNativeLayoutInfoReader(signature); + NativeReader reader = TypeLoaderEnvironment.GetNativeLayoutInfoReader(signature); return reader.OffsetToAddress(signature.NativeLayoutOffset); } } @@ -318,7 +318,7 @@ internal bool GetMethodFromSignatureAndContext(ref NativeParser parser, TypeMana // // Returns the native layout info reader // - internal unsafe NativeReader GetNativeLayoutInfoReader(NativeFormatModuleInfo module) + internal static unsafe NativeReader GetNativeLayoutInfoReader(NativeFormatModuleInfo module) { return GetNativeLayoutInfoReader(module.Handle); } @@ -326,7 +326,7 @@ internal unsafe NativeReader GetNativeLayoutInfoReader(NativeFormatModuleInfo mo // // Returns the native layout info reader // - internal unsafe NativeReader GetNativeLayoutInfoReader(RuntimeSignature signature) + internal static unsafe NativeReader GetNativeLayoutInfoReader(RuntimeSignature signature) { Debug.Assert(signature.IsNativeLayoutSignature); return GetNativeLayoutInfoReader(new TypeManagerHandle(signature.ModuleHandle)); @@ -335,7 +335,7 @@ internal unsafe NativeReader GetNativeLayoutInfoReader(RuntimeSignature signatur // // Returns the native layout info reader // - internal unsafe NativeReader GetNativeLayoutInfoReader(TypeManagerHandle moduleHandle) + internal static unsafe NativeReader GetNativeLayoutInfoReader(TypeManagerHandle moduleHandle) { Debug.Assert(!moduleHandle.IsNull); @@ -409,7 +409,7 @@ public bool TryGetArrayTypeForElementType(RuntimeTypeHandle elementTypeHandle, b } // Looks up an array RuntimeTypeHandle given an element's RuntimeTypeHandle and rank. A rank of -1 indicates SzArray - internal bool TryGetArrayTypeForElementType_LookupOnly(RuntimeTypeHandle elementTypeHandle, bool isMdArray, int rank, out RuntimeTypeHandle arrayTypeHandle) + internal static bool TryGetArrayTypeForElementType_LookupOnly(RuntimeTypeHandle elementTypeHandle, bool isMdArray, int rank, out RuntimeTypeHandle arrayTypeHandle) { if (isMdArray && (rank < MDArray.MinRank) && (rank > MDArray.MaxRank)) { @@ -619,7 +619,7 @@ public bool ConversionToCanonFormIsAChange(RuntimeTypeHandle[] genericArgHandles // get the generics hash table and external references table for a module // TODO multi-file: consider whether we want to cache this info - private unsafe bool GetHashtableFromBlob(NativeFormatModuleInfo module, ReflectionMapBlob blobId, out NativeHashtable hashtable, out ExternalReferencesTable externalReferencesLookup) + private static unsafe bool GetHashtableFromBlob(NativeFormatModuleInfo module, ReflectionMapBlob blobId, out NativeHashtable hashtable, out ExternalReferencesTable externalReferencesLookup) { byte* pBlob; uint cbBlob; @@ -683,7 +683,7 @@ public bool TryComputeHasInstantiationDeterminedSize(RuntimeTypeHandle typeHandl return TryComputeHasInstantiationDeterminedSize(type, out hasInstantiationDeterminedSize); } - internal bool TryComputeHasInstantiationDeterminedSize(DefType type, out bool hasInstantiationDeterminedSize) + internal static bool TryComputeHasInstantiationDeterminedSize(DefType type, out bool hasInstantiationDeterminedSize) { Debug.Assert(type.HasInstantiation); diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/ExceptionTypeNameFormatter.Runtime.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/ExceptionTypeNameFormatter.Runtime.cs index 9cdd08202ab23..d6e9a2530e105 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/ExceptionTypeNameFormatter.Runtime.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/ExceptionTypeNameFormatter.Runtime.cs @@ -5,7 +5,7 @@ namespace Internal.TypeSystem { partial class ExceptionTypeNameFormatter { - private string GetTypeName(DefType type) + private static string GetTypeName(DefType type) { if (type is NoMetadata.NoMetadataType) return ((NoMetadata.NoMetadataType)type).NameForDiagnostics; @@ -13,7 +13,7 @@ private string GetTypeName(DefType type) return type.Name; } - private string GetTypeNamespace(DefType type) + private static string GetTypeNamespace(DefType type) { if (type is NoMetadata.NoMetadataType) return ((NoMetadata.NoMetadataType)type).NamespaceForDiagnostics; diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeDesc.Runtime.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeDesc.Runtime.cs index 8d92aaafbf825..fb7637e913a54 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeDesc.Runtime.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeDesc.Runtime.cs @@ -163,7 +163,7 @@ internal bool RetrieveRuntimeTypeHandleIfPossible() { RuntimeTypeHandle rtth; if ((type is ArrayType && - (TypeLoaderEnvironment.Instance.TryGetArrayTypeForElementType_LookupOnly(typeAsParameterType.ParameterType.RuntimeTypeHandle, type.IsMdArray, type.IsMdArray ? ((ArrayType)type).Rank : -1, out rtth) || + (TypeLoaderEnvironment.TryGetArrayTypeForElementType_LookupOnly(typeAsParameterType.ParameterType.RuntimeTypeHandle, type.IsMdArray, type.IsMdArray ? ((ArrayType)type).Rank : -1, out rtth) || TypeLoaderEnvironment.Instance.TryGetArrayTypeHandleForNonDynamicArrayTypeFromTemplateTable(type as ArrayType, out rtth))) || (type is PointerType && TypeSystemContext.PointerTypesCache.TryGetValue(typeAsParameterType.ParameterType.RuntimeTypeHandle, out rtth)) @@ -232,7 +232,7 @@ internal TypeDesc ComputeTemplate(bool templateRequired = true) return ComputeTemplate(GetOrCreateTypeBuilderState(), templateRequired); } - internal TypeDesc ComputeTemplate(TypeBuilderState state, bool templateRequired = true) + internal static TypeDesc ComputeTemplate(TypeBuilderState state, bool templateRequired = true) { TypeDesc templateType = state.TemplateType; diff --git a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeSystemContext.Runtime.cs b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeSystemContext.Runtime.cs index 6667763770f48..19d6028102ed0 100644 --- a/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeSystemContext.Runtime.cs +++ b/src/coreclr/nativeaot/System.Private.TypeLoader/src/Internal/TypeSystem/TypeSystemContext.Runtime.cs @@ -23,7 +23,7 @@ namespace Internal.TypeSystem { public abstract partial class TypeSystemContext { - internal TemplateLocator TemplateLookup => new TemplateLocator(); + internal static TemplateLocator TemplateLookup => new TemplateLocator(); internal class RuntimeTypeHandleToParameterTypeRuntimeTypeHandleHashtable : LockFreeReaderHashtableOfPointers { @@ -141,7 +141,7 @@ internal TypeDesc GetTypeDescFromQHandle(QTypeDefinition qTypeDefinition) #endif // Helper routine for ResolveRuntimeTypeHandle, used to handle lookups which may result in a metadata based type. - private TypeDesc TryGetMetadataBasedTypeFromRuntimeTypeHandle_Uncached(RuntimeTypeHandle rtth) + private static TypeDesc TryGetMetadataBasedTypeFromRuntimeTypeHandle_Uncached(RuntimeTypeHandle rtth) { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING QTypeDefinition qTypeDefinition; diff --git a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeFormatReaderGen.cs b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeFormatReaderGen.cs index bbc23ec878484..b324c87646180 100644 --- a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeFormatReaderGen.cs +++ b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeFormatReaderGen.cs @@ -7,6 +7,7 @@ #pragma warning disable 169 #pragma warning disable 282 // There is no defined ordering between fields in multiple declarations of partial class or struct #pragma warning disable CA1066 // IEquatable implementations aren't used +#pragma warning disable CA1822 #pragma warning disable IDE0059 using System; diff --git a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeMetadataReader.cs b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeMetadataReader.cs index 5b7921f972f97..8be485c14635a 100644 --- a/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeMetadataReader.cs +++ b/src/coreclr/tools/Common/Internal/Metadata/NativeFormat/NativeMetadataReader.cs @@ -253,7 +253,7 @@ internal partial class MetadataHeader public void Decode(NativeReader reader) { if (reader.ReadUInt32(0) != Signature) - reader.ThrowBadImageFormatException(); + NativeReader.ThrowBadImageFormatException(); reader.Read(4, out ScopeDefinitions); } } diff --git a/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.cs b/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.cs index 845dc7c95a478..61dcffe240304 100644 --- a/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.cs +++ b/src/coreclr/tools/Common/Internal/NativeFormat/NativeFormatReader.cs @@ -254,7 +254,7 @@ public IntPtr OffsetToAddress(uint offset) return new IntPtr(_base + offset); } - public void ThrowBadImageFormatException() + public static void ThrowBadImageFormatException() { Debug.Assert(false); throw new BadImageFormatException(); @@ -395,9 +395,9 @@ public uint Offset } } - public void ThrowBadImageFormatException() + public static void ThrowBadImageFormatException() { - _reader.ThrowBadImageFormatException(); + NativeReader.ThrowBadImageFormatException(); } public byte GetUInt8() @@ -470,12 +470,12 @@ public NativeHashtable(NativeParser parser) int numberOfBucketsShift = (int)(header >> 2); if (numberOfBucketsShift > 31) - _reader.ThrowBadImageFormatException(); + NativeReader.ThrowBadImageFormatException(); _bucketMask = (uint)((1 << numberOfBucketsShift) - 1); byte entryIndexSize = (byte)(header & 3); if (entryIndexSize > 2) - _reader.ThrowBadImageFormatException(); + NativeReader.ThrowBadImageFormatException(); _entryIndexSize = entryIndexSize; } diff --git a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/DebugNameFormatter.cs b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/DebugNameFormatter.cs index ea55c07ad767b..607287e45f6dc 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/DebugNameFormatter.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/DebugNameFormatter.cs @@ -182,7 +182,7 @@ protected override Void AppendNameForNamespaceType(StringBuilder sb, DefType typ return Void.Value; } - private void AssemblyQualify(StringBuilder sb, DefType type, FormatOptions options) + private static void AssemblyQualify(StringBuilder sb, DefType type, FormatOptions options) { if (((options & FormatOptions.AssemblyQualify) != 0) && type is MetadataType mdType @@ -215,7 +215,7 @@ private void AssemblyQualify(StringBuilder sb, DefType type, FormatOptions optio } } - private void NamespaceQualify(StringBuilder sb, DefType type, FormatOptions options) + private static void NamespaceQualify(StringBuilder sb, DefType type, FormatOptions options) { if ((options & FormatOptions.NamespaceQualify) != 0) { diff --git a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtable.cs b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtable.cs index c36e39f224859..0ab073cce5111 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtable.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtable.cs @@ -523,7 +523,7 @@ private bool TryWriteSentinelToLocation(TValue[] hashTableLocal, int tableIndex) /// Attempts to write a value into the table. Should never fail as the sentinel should be the only /// entry that can be in the table at this point /// - private void WriteValueToLocation(TValue value, TValue[] hashTableLocal, int tableIndex) + private static void WriteValueToLocation(TValue value, TValue[] hashTableLocal, int tableIndex) { // Add to hash, use a volatile write to ensure that // the contents of the value are fully published to all @@ -535,7 +535,7 @@ private void WriteValueToLocation(TValue value, TValue[] hashTableLocal, int tab /// Attempts to abort write a value into the table. Should never fail as the sentinel should be the only /// entry that can be in the table at this point /// - private void WriteAbortNullToLocation(TValue[] hashTableLocal, int tableIndex) + private static void WriteAbortNullToLocation(TValue[] hashTableLocal, int tableIndex) { // Add to hash, use a volatile write to ensure that // the contents of the value are fully published to all diff --git a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtableOfPointers.cs b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtableOfPointers.cs index 7c03a26c71bc6..f0b7ea4a45d9a 100644 --- a/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtableOfPointers.cs +++ b/src/coreclr/tools/Common/TypeSystem/Common/Utilities/LockFreeReaderHashtableOfPointers.cs @@ -211,7 +211,7 @@ public bool TryGetValue(TKey key, out TValue value) /// /// /// The value that replaced the sentinel, or null - IntPtr WaitForSentinelInHashtableToDisappear(IntPtr[] hashtable, int tableIndex) + private static IntPtr WaitForSentinelInHashtableToDisappear(IntPtr[] hashtable, int tableIndex) { var sw = new SpinWait(); while (true) @@ -353,7 +353,7 @@ private TValue AddOrGetExistingInner(TValue value, out bool addedValue) return result; } - IntPtr VolatileReadNonSentinelFromHashtable(IntPtr[] hashTable, int tableIndex) + private static IntPtr VolatileReadNonSentinelFromHashtable(IntPtr[] hashTable, int tableIndex) { IntPtr examineEntry = Volatile.Read(ref hashTable[tableIndex]); @@ -458,7 +458,7 @@ private bool TryAddOrGetExisting(TValue value, out bool addedValue, ref TValue v /// Attampts to write the Sentinel into the table. May fail if another value has been added. /// /// True if the value was successfully written - private bool TryWriteSentinelToLocation(IntPtr[] hashTableLocal, int tableIndex) + private static bool TryWriteSentinelToLocation(IntPtr[] hashTableLocal, int tableIndex) { // Add to hash, use a CompareExchange to ensure that // the sentinel is are fully communicated to all threads @@ -473,7 +473,7 @@ private bool TryWriteSentinelToLocation(IntPtr[] hashTableLocal, int tableIndex) /// /// Writes the value into the table. Must only be used to overwrite a sentinel. /// - private void WriteValueToLocation(IntPtr value, IntPtr[] hashTableLocal, int tableIndex) + private static void WriteValueToLocation(IntPtr value, IntPtr[] hashTableLocal, int tableIndex) { // Add to hash, use a volatile write to ensure that // the contents of the value are fully published to all @@ -484,7 +484,7 @@ private void WriteValueToLocation(IntPtr value, IntPtr[] hashTableLocal, int tab /// /// Abandons the sentinel. Must only be used to overwrite a sentinel. /// - private void WriteAbortNullToLocation(IntPtr[] hashTableLocal, int tableIndex) + private static void WriteAbortNullToLocation(IntPtr[] hashTableLocal, int tableIndex) { // Abandon sentinel, use a volatile write to ensure that // the contents of the value are fully published to all diff --git a/src/installer/managed/Microsoft.NET.HostModel/Bundle/Bundler.cs b/src/installer/managed/Microsoft.NET.HostModel/Bundle/Bundler.cs index 6807356ca134f..b822887e658fd 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/Bundle/Bundler.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/Bundle/Bundler.cs @@ -169,7 +169,7 @@ private bool ShouldExclude(FileType type, string relativePath) } } - private bool IsAssembly(string path, out bool isPE) + private static bool IsAssembly(string path, out bool isPE) { isPE = false; diff --git a/src/installer/managed/Microsoft.NET.HostModel/ComHost/TypeLibReader.cs b/src/installer/managed/Microsoft.NET.HostModel/ComHost/TypeLibReader.cs index fd1c45e66dc7a..5cb039b7a53a6 100644 --- a/src/installer/managed/Microsoft.NET.HostModel/ComHost/TypeLibReader.cs +++ b/src/installer/managed/Microsoft.NET.HostModel/ComHost/TypeLibReader.cs @@ -36,7 +36,7 @@ public TypeLibReader(byte[] tlbBytes) private const int NumTablesToSkip = 5; private const int SizeOfTableHeader = sizeof(int) * 4; - private Guid FindGuid(ReadOnlySpan fileContents) + private static Guid FindGuid(ReadOnlySpan fileContents) { checked { diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/SafeDeleteContext.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/SafeDeleteContext.cs index 9a00e7b1ac1d0..8718558557fc6 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/SafeDeleteContext.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/SafeDeleteContext.cs @@ -44,13 +44,5 @@ public override string ToString() { return _handle.ToString(); } - -#if DEBUG - //This method should never be called for this type - public new IntPtr DangerousGetHandle() - { - throw new InvalidOperationException(); - } -#endif } } diff --git a/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs b/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs index 3c5bbe532161e..47de5f4e6b578 100644 --- a/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs +++ b/src/libraries/Common/src/Interop/Windows/SspiCli/SecuritySafeHandles.cs @@ -187,14 +187,6 @@ public override bool IsInvalid public DateTime Expiry => _expiry; -#if DEBUG - public new IntPtr DangerousGetHandle() - { - Debug.Fail("This method should never be called for this type"); - throw NotImplemented.ByDesign; - } -#endif - public static unsafe int AcquireDefaultCredential( string package, Interop.SspiCli.CredentialUse intent, diff --git a/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs b/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs index f010798cda861..d563de42b80d2 100644 --- a/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs +++ b/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs @@ -362,7 +362,7 @@ public CodeTypeReferenceCollection TypeArguments // " [System.Collections.Generic.List[[System.string, mscorlib, Version=2.0.0.0, Culture=neutral, // PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]" // - private string RipOffAssemblyInformationFromTypeName(string typeName) + private static string RipOffAssemblyInformationFromTypeName(string typeName) { int start = 0; int end = typeName.Length - 1; diff --git a/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs b/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs index 61f4cfcb9ce08..2e717798362ca 100644 --- a/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs +++ b/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs @@ -190,7 +190,7 @@ private DataTable ExecuteCommand(DataRow requestedCollectionRow, string?[]? rest return resultTable; } - private DataColumn[] FilterColumns(DataTable sourceTable, string[]? hiddenColumnNames, DataColumnCollection destinationColumns) + private static DataColumn[] FilterColumns(DataTable sourceTable, string[]? hiddenColumnNames, DataColumnCollection destinationColumns) { int columnCount = 0; foreach (DataColumn sourceColumn in sourceTable.Columns) @@ -465,7 +465,7 @@ public virtual DataTable GetSchema(DbConnection connection, string collectionNam return requestedSchema; } - private bool IncludeThisColumn(DataColumn sourceColumn, string[]? hiddenColumnNames) + private static bool IncludeThisColumn(DataColumn sourceColumn, string[]? hiddenColumnNames) { bool result = true; diff --git a/src/libraries/Common/src/System/IO/Compression/ZLibNative.ZStream.cs b/src/libraries/Common/src/System/IO/Compression/ZLibNative.ZStream.cs index bfb8c5145c04a..acc19c936b7bc 100644 --- a/src/libraries/Common/src/System/IO/Compression/ZLibNative.ZStream.cs +++ b/src/libraries/Common/src/System/IO/Compression/ZLibNative.ZStream.cs @@ -16,10 +16,6 @@ internal static partial class ZLibNative [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] internal struct ZStream { - internal void Init() - { - } - internal IntPtr nextIn; //Bytef *next_in; /* next input byte */ internal IntPtr nextOut; //Bytef *next_out; /* next output byte should be put there */ diff --git a/src/libraries/Common/src/System/IO/Compression/ZLibNative.cs b/src/libraries/Common/src/System/IO/Compression/ZLibNative.cs index 843c28a879bba..99330b032ca8c 100644 --- a/src/libraries/Common/src/System/IO/Compression/ZLibNative.cs +++ b/src/libraries/Common/src/System/IO/Compression/ZLibNative.cs @@ -197,8 +197,6 @@ public enum State { NotInitialized, InitializedForDeflate, InitializedForInflate public ZLibStreamHandle() : base(new IntPtr(-1), true) { - _zStream.Init(); - _initializationState = State.NotInitialized; SetHandle(IntPtr.Zero); } diff --git a/src/libraries/Common/src/System/IO/TempFileCollection.cs b/src/libraries/Common/src/System/IO/TempFileCollection.cs index 95ca600bf2fab..7f70363b9ce51 100644 --- a/src/libraries/Common/src/System/IO/TempFileCollection.cs +++ b/src/libraries/Common/src/System/IO/TempFileCollection.cs @@ -158,7 +158,7 @@ public void Delete() SafeDelete(); } - internal void Delete(string fileName) + private static void Delete(string fileName) { try { diff --git a/src/libraries/Common/src/System/Net/CaseInsensitiveAscii.cs b/src/libraries/Common/src/System/Net/CaseInsensitiveAscii.cs index 2b0cb7f207dca..4bfdf23ca7cd8 100644 --- a/src/libraries/Common/src/System/Net/CaseInsensitiveAscii.cs +++ b/src/libraries/Common/src/System/Net/CaseInsensitiveAscii.cs @@ -85,7 +85,7 @@ public int Compare(object? firstObject, object? secondObject) } // ASCII string case insensitive hash function - private int FastGetHashCode(string myString) + private static int FastGetHashCode(string myString) { int myHashCode = myString.Length; if (myHashCode != 0) diff --git a/src/libraries/Common/src/System/Net/ContextAwareResult.Unix.cs b/src/libraries/Common/src/System/Net/ContextAwareResult.Unix.cs index fcf2e5d95ac16..689dea330dcd7 100644 --- a/src/libraries/Common/src/System/Net/ContextAwareResult.Unix.cs +++ b/src/libraries/Common/src/System/Net/ContextAwareResult.Unix.cs @@ -5,14 +5,8 @@ namespace System.Net { internal sealed partial class ContextAwareResult { - private void SafeCaptureIdentity() - { - // WindowsIdentity is not supported on Unix - } + partial void SafeCaptureIdentity(); - private void CleanupInternal() - { - // Nothing to cleanup - } + partial void CleanupInternal(); } } diff --git a/src/libraries/Common/src/System/Net/ContextAwareResult.cs b/src/libraries/Common/src/System/Net/ContextAwareResult.cs index 961fba50067db..87d936afbfd1c 100644 --- a/src/libraries/Common/src/System/Net/ContextAwareResult.cs +++ b/src/libraries/Common/src/System/Net/ContextAwareResult.cs @@ -370,6 +370,6 @@ private void CompleteCallback() base.Complete(IntPtr.Zero); } - internal EndPoint? RemoteEndPoint => null; + internal static EndPoint? RemoteEndPoint => null; } } 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 83e1b7f3a3b9f..9e3d8fe8a219c 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 @@ -710,7 +710,7 @@ private void OnIndexedHeaderName(int index) _state = State.HeaderValueLength; } - private void OnIndexedHeaderNamePostBase(int index) + private static void OnIndexedHeaderNamePostBase(int index) { ThrowDynamicTableNotSupported(); // TODO update with postbase index @@ -718,7 +718,7 @@ private void OnIndexedHeaderNamePostBase(int index) // _state = State.HeaderValueLength; } - private void OnPostBaseIndex(int intResult, IHttpStreamHeadersHandler handler) + private static void OnPostBaseIndex(int intResult, IHttpStreamHeadersHandler handler) { ThrowDynamicTableNotSupported(); // TODO diff --git a/src/libraries/Common/src/System/Net/LazyAsyncResult.cs b/src/libraries/Common/src/System/Net/LazyAsyncResult.cs index 6a4dd5eac8532..501edacb43051 100644 --- a/src/libraries/Common/src/System/Net/LazyAsyncResult.cs +++ b/src/libraries/Common/src/System/Net/LazyAsyncResult.cs @@ -173,6 +173,7 @@ private bool LazilyCreateEvent(out ManualResetEvent waitHandle) } } +#pragma warning disable CA1822 // This allows ContextAwareResult to not let anyone trigger the CompletedSynchronously tripwire while the context is being captured. [Conditional("DEBUG")] protected void DebugProtectState(bool protect) @@ -181,6 +182,7 @@ protected void DebugProtectState(bool protect) _protectState = protect; #endif } +#pragma warning restore CA1822 // Interface property, returning synchronous completion status. public bool CompletedSynchronously diff --git a/src/libraries/Common/src/System/Resources/ResourceWriter.cs b/src/libraries/Common/src/System/Resources/ResourceWriter.cs index 47d30c4bb8da4..999dc16f55abe 100644 --- a/src/libraries/Common/src/System/Resources/ResourceWriter.cs +++ b/src/libraries/Common/src/System/Resources/ResourceWriter.cs @@ -399,7 +399,7 @@ public void Generate() // Finds the ResourceTypeCode for a type, or adds this type to the // types list. - private ResourceTypeCode FindTypeCode(object? value, List types) + private static ResourceTypeCode FindTypeCode(object? value, List types) { if (value == null) return ResourceTypeCode.Null; @@ -472,7 +472,7 @@ private ResourceTypeCode FindTypeCode(object? value, List types) return (ResourceTypeCode)(typeIndex + ResourceTypeCode.StartOfUserTypes); } - private void WriteValue(ResourceTypeCode typeCode, object? value, BinaryWriter writer) + private static void WriteValue(ResourceTypeCode typeCode, object? value, BinaryWriter writer) { Debug.Assert(writer != null); diff --git a/src/libraries/Common/src/System/Security/Cryptography/ECAndroid.cs b/src/libraries/Common/src/System/Security/Cryptography/ECAndroid.cs index 5968fa1c726ce..a90f729c0b31d 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECAndroid.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECAndroid.cs @@ -32,7 +32,7 @@ public ECAndroid(SafeEcKeyHandle key) internal SafeEcKeyHandle Value => _key.Value; - private SafeEcKeyHandle GenerateKeyLazy(AsymmetricAlgorithm owner) => + private static SafeEcKeyHandle GenerateKeyLazy(AsymmetricAlgorithm owner) => GenerateKeyByKeySize(owner.KeySize); public void Dispose() diff --git a/src/libraries/Common/src/System/Security/Cryptography/ECOpenSsl.cs b/src/libraries/Common/src/System/Security/Cryptography/ECOpenSsl.cs index 68faec7a14c5b..5157a2e1246c5 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/ECOpenSsl.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/ECOpenSsl.cs @@ -32,7 +32,7 @@ public ECOpenSsl(SafeEcKeyHandle key) internal SafeEcKeyHandle Value => _key.Value; - private SafeEcKeyHandle GenerateKeyLazy(AsymmetricAlgorithm owner) => + private static SafeEcKeyHandle GenerateKeyLazy(AsymmetricAlgorithm owner) => GenerateKeyByKeySize(owner.KeySize); public void Dispose() diff --git a/src/libraries/Common/src/System/Security/Cryptography/RSACng.EncryptDecrypt.cs b/src/libraries/Common/src/System/Security/Cryptography/RSACng.EncryptDecrypt.cs index 0ff2474f0f7ce..70c757230df07 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/RSACng.EncryptDecrypt.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/RSACng.EncryptDecrypt.cs @@ -253,7 +253,7 @@ private unsafe byte[] EncryptOrDecrypt(SafeNCryptKeyHandle key, ReadOnlySpan input, Span output, AsymmetricPaddingMode paddingMode, void* paddingInfo, bool encrypt, out int bytesWritten) + private static unsafe bool TryEncryptOrDecrypt(SafeNCryptKeyHandle key, ReadOnlySpan input, Span output, AsymmetricPaddingMode paddingMode, void* paddingInfo, bool encrypt, out int bytesWritten) { for (int i = 0; i <= StatusUnsuccessfulRetryCount; i++) { diff --git a/src/libraries/Common/src/System/Threading/Tasks/RendezvousAwaitable.cs b/src/libraries/Common/src/System/Threading/Tasks/RendezvousAwaitable.cs index 743812383d88a..373cb8d8a86dc 100644 --- a/src/libraries/Common/src/System/Threading/Tasks/RendezvousAwaitable.cs +++ b/src/libraries/Common/src/System/Threading/Tasks/RendezvousAwaitable.cs @@ -133,6 +133,7 @@ public void OnCompleted(Action continuation) /// Register the continuation to invoke when the operation completes. public void UnsafeOnCompleted(Action continuation) => OnCompleted(continuation); +#pragma warning disable CA1822 [Conditional("DEBUG")] private void AssertResultConsistency(bool expectedCompleted) { @@ -147,5 +148,6 @@ private void AssertResultConsistency(bool expectedCompleted) } #endif } +#pragma warning restore CA1822 } } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeLibDesc.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeLibDesc.cs index 591d8c59309d6..3ea0065d2612c 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeLibDesc.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/ComTypeLibDesc.cs @@ -35,11 +35,6 @@ private ComTypeLibDesc() public override string ToString() => $""; - public string Documentation - { - get { return string.Empty; } - } - #region IDynamicMetaObjectProvider Members DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/DynamicDebuggerProxy.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/DynamicDebuggerProxy.cs index 8f41e1dca5fcf..cf9b27c8a471c 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/DynamicDebuggerProxy.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/DynamicDebuggerProxy.cs @@ -475,6 +475,7 @@ private DynamicDebugViewEmptyException(SerializationInfo info, StreamingContext { } +#pragma warning disable CA1822 // This property value is used by the debugger EE as the message // displayed when a dynamic object has no members. public string Empty @@ -484,6 +485,7 @@ public string Empty return SR.EmptyDynamicView; } } +#pragma warning restore CA1822 } } } diff --git a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs index a29175fe6c431..faca677a332f7 100644 --- a/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs +++ b/src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs @@ -238,6 +238,7 @@ private void CheckBetterTable() } #endif // DEBUG +#pragma warning disable CA1822 [RequiresUnreferencedCode(Binder.TrimmerWarning)] private BetterType WhichSimpleConversionIsBetter(PredefinedType pt1, PredefinedType pt2) { @@ -248,8 +249,7 @@ private BetterType WhichSimpleConversionIsBetter(PredefinedType pt1, PredefinedT Debug.Assert((int)pt2 < NUM_EXT_TYPES); return (BetterType)s_simpleTypeBetter[(int)pt1][(int)pt2]; } - - +#pragma warning restore CA1822 /*************************************************************************************************** Determined which conversion to a predefined type is better relative to a given type. It is diff --git a/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/CommandLineConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/CommandLineConfigurationProvider.cs index ac17d7009fe06..82209ea80dc0d 100644 --- a/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/CommandLineConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration.CommandLine/src/CommandLineConfigurationProvider.cs @@ -131,7 +131,7 @@ public override void Load() Data = data; } - private Dictionary GetValidatedSwitchMappingsCopy(IDictionary switchMappings) + private static Dictionary GetValidatedSwitchMappingsCopy(IDictionary switchMappings) { // The dictionary passed in might be constructed with a case-sensitive comparer // However, the keys in configuration providers are all case-insensitive diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs index db2701be21ae0..01ee4cc86cbf7 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/CallSiteFactory.cs @@ -305,7 +305,7 @@ private static bool AreCompatible(DynamicallyAccessedMemberTypes serviceDynamica } } - private CallSiteResultCacheLocation GetCommonCacheLocation(CallSiteResultCacheLocation locationA, CallSiteResultCacheLocation locationB) + private static CallSiteResultCacheLocation GetCommonCacheLocation(CallSiteResultCacheLocation locationA, CallSiteResultCacheLocation locationB) { return (CallSiteResultCacheLocation)Math.Max((int)locationA, (int)locationB); } diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/Expressions/ExpressionResolverBuilder.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/Expressions/ExpressionResolverBuilder.cs index 3d7f40834ad3f..7e0b988fa2b9e 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/Expressions/ExpressionResolverBuilder.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/Expressions/ExpressionResolverBuilder.cs @@ -136,7 +136,7 @@ protected override Expression VisitDisposeCache(ServiceCallSite callSite, object VisitCallSiteMain(callSite, context)); } - private Expression TryCaptureDisposable(ServiceCallSite callSite, ParameterExpression scope, Expression service) + private static Expression TryCaptureDisposable(ServiceCallSite callSite, ParameterExpression scope, Expression service) { if (!callSite.CaptureDisposable) { @@ -269,7 +269,7 @@ private Expression BuildScopedExpression(ServiceCallSite callSite) ); } - public Expression GetCaptureDisposable(ParameterExpression scope) + public static Expression GetCaptureDisposable(ParameterExpression scope) { if (scope != ScopeParameter) { diff --git a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitResolverBuilder.cs b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitResolverBuilder.cs index e46e459ce9d50..73a8a86fb14ea 100644 --- a/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitResolverBuilder.cs +++ b/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/ILEmit/ILEmitResolverBuilder.cs @@ -257,7 +257,7 @@ private GeneratedMethod BuildTypeNoCache(ServiceCallSite callSite) return null; } - private void AddConstant(ILEmitResolverBuilderContext argument, object? value) + private static void AddConstant(ILEmitResolverBuilderContext argument, object? value) { if (argument.Constants == null) { @@ -273,7 +273,7 @@ private void AddConstant(ILEmitResolverBuilderContext argument, object? value) argument.Constants.Add(value); } - private void AddCacheKey(ILEmitResolverBuilderContext argument, ServiceCacheKey key) + private static void AddCacheKey(ILEmitResolverBuilderContext argument, ServiceCacheKey key) { Debug.Assert(key.Type != null); diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextWriter.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextWriter.cs index 0fb34c4db048b..eb4c4ab8cd0e9 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextWriter.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextWriter.cs @@ -35,7 +35,7 @@ public void Write(DependencyContext context!!, Stream stream!!) } } - private void WriteRuntimeTargetInfo(DependencyContext context, Utf8JsonWriter jsonWriter) + private static void WriteRuntimeTargetInfo(DependencyContext context, Utf8JsonWriter jsonWriter) { jsonWriter.WriteStartObject(DependencyContextStrings.RuntimeTargetPropertyName); if (context.Target.IsPortable) @@ -53,7 +53,7 @@ private void WriteRuntimeTargetInfo(DependencyContext context, Utf8JsonWriter js jsonWriter.WriteEndObject(); } - private void WriteRuntimeGraph(DependencyContext context, Utf8JsonWriter jsonWriter) + private static void WriteRuntimeGraph(DependencyContext context, Utf8JsonWriter jsonWriter) { jsonWriter.WriteStartObject(DependencyContextStrings.RuntimesPropertyName); foreach (RuntimeFallbacks runtimeFallback in context.RuntimeGraph) @@ -68,7 +68,7 @@ private void WriteRuntimeGraph(DependencyContext context, Utf8JsonWriter jsonWri jsonWriter.WriteEndObject(); } - private void WriteCompilationOptions(CompilationOptions compilationOptions, Utf8JsonWriter jsonWriter) + private static void WriteCompilationOptions(CompilationOptions compilationOptions, Utf8JsonWriter jsonWriter) { jsonWriter.WriteStartObject(DependencyContextStrings.CompilationOptionsPropertName); if (compilationOptions.Defines?.Any() == true) @@ -94,7 +94,7 @@ private void WriteCompilationOptions(CompilationOptions compilationOptions, Utf8 jsonWriter.WriteEndObject(); } - private void AddStringPropertyIfNotNull(string name, string? value, Utf8JsonWriter jsonWriter) + private static void AddStringPropertyIfNotNull(string name, string? value, Utf8JsonWriter jsonWriter) { if (value != null) { @@ -102,7 +102,7 @@ private void AddStringPropertyIfNotNull(string name, string? value, Utf8JsonWrit } } - private void AddBooleanPropertyIfNotNull(string name, bool? value, Utf8JsonWriter jsonWriter) + private static void AddBooleanPropertyIfNotNull(string name, bool? value, Utf8JsonWriter jsonWriter) { if (value.HasValue) { @@ -110,7 +110,7 @@ private void AddBooleanPropertyIfNotNull(string name, bool? value, Utf8JsonWrite } } - private void WriteTargets(DependencyContext context, Utf8JsonWriter jsonWriter) + private static void WriteTargets(DependencyContext context, Utf8JsonWriter jsonWriter) { jsonWriter.WriteStartObject(DependencyContextStrings.TargetsPropertyName); if (context.Target.IsPortable) @@ -126,7 +126,7 @@ private void WriteTargets(DependencyContext context, Utf8JsonWriter jsonWriter) jsonWriter.WriteEndObject(); } - private void WriteTarget(string key, IReadOnlyList libraries, Utf8JsonWriter jsonWriter) + private static void WriteTarget(string key, IReadOnlyList libraries, Utf8JsonWriter jsonWriter) { jsonWriter.WriteStartObject(key); int count = libraries.Count; @@ -138,7 +138,7 @@ private void WriteTarget(string key, IReadOnlyList libraries, Utf8JsonW jsonWriter.WriteEndObject(); } - private void WritePortableTarget(string key, IReadOnlyList runtimeLibraries, IReadOnlyList compilationLibraries, Utf8JsonWriter jsonWriter) + private static void WritePortableTarget(string key, IReadOnlyList runtimeLibraries, IReadOnlyList compilationLibraries, Utf8JsonWriter jsonWriter) { Dictionary runtimeLookup = runtimeLibraries.LibraryCollectionToDictionary(); Dictionary compileLookup = compilationLibraries.LibraryCollectionToDictionary(); @@ -170,7 +170,7 @@ private void WritePortableTarget(string key, IReadOnlyList runti jsonWriter.WriteEndObject(); } - private void AddCompilationAssemblies(IEnumerable compilationAssemblies, Utf8JsonWriter jsonWriter) + private static void AddCompilationAssemblies(IEnumerable compilationAssemblies, Utf8JsonWriter jsonWriter) { if (!compilationAssemblies.Any()) { @@ -180,7 +180,7 @@ private void AddCompilationAssemblies(IEnumerable compilationAssemblies, WriteAssetList(DependencyContextStrings.CompileTimeAssembliesKey, compilationAssemblies, jsonWriter); } - private void AddAssets(string key, RuntimeAssetGroup? group, Utf8JsonWriter jsonWriter) + private static void AddAssets(string key, RuntimeAssetGroup? group, Utf8JsonWriter jsonWriter) { if (group == null || !group.RuntimeFiles.Any()) { @@ -190,7 +190,7 @@ private void AddAssets(string key, RuntimeAssetGroup? group, Utf8JsonWriter json WriteAssetList(key, group.RuntimeFiles, jsonWriter); } - private void AddDependencies(IEnumerable dependencies, Utf8JsonWriter jsonWriter) + private static void AddDependencies(IEnumerable dependencies, Utf8JsonWriter jsonWriter) { if (!dependencies.Any()) { @@ -205,7 +205,7 @@ private void AddDependencies(IEnumerable dependencies, Utf8JsonWrite jsonWriter.WriteEndObject(); } - private void AddResourceAssemblies(IEnumerable resourceAssemblies, Utf8JsonWriter jsonWriter) + private static void AddResourceAssemblies(IEnumerable resourceAssemblies, Utf8JsonWriter jsonWriter) { if (!resourceAssemblies.Any()) { @@ -222,7 +222,7 @@ private void AddResourceAssemblies(IEnumerable resourceAssembl jsonWriter.WriteEndObject(); } - private void WriteTargetLibrary(string key, Library library, Utf8JsonWriter jsonWriter) + private static void WriteTargetLibrary(string key, Library library, Utf8JsonWriter jsonWriter) { if (library is RuntimeLibrary runtimeLibrary) { @@ -250,7 +250,7 @@ private void WriteTargetLibrary(string key, Library library, Utf8JsonWriter json } } - private void WritePortableTargetLibrary(string key, RuntimeLibrary? runtimeLibrary, CompilationLibrary? compilationLibrary, Utf8JsonWriter jsonWriter) + private static void WritePortableTargetLibrary(string key, RuntimeLibrary? runtimeLibrary, CompilationLibrary? compilationLibrary, Utf8JsonWriter jsonWriter) { jsonWriter.WriteStartObject(key); @@ -298,7 +298,7 @@ private void WritePortableTargetLibrary(string key, RuntimeLibrary? runtimeLibra jsonWriter.WriteEndObject(); } - private bool AddRuntimeSpecificAssetGroups(string assetType, IEnumerable assetGroups, bool wroteObjectStart, Utf8JsonWriter jsonWriter) + private static bool AddRuntimeSpecificAssetGroups(string assetType, IEnumerable assetGroups, bool wroteObjectStart, Utf8JsonWriter jsonWriter) { IEnumerable groups = assetGroups.Where(g => !string.IsNullOrEmpty(g.Runtime)); if (!wroteObjectStart && groups.Any()) @@ -330,7 +330,7 @@ private bool AddRuntimeSpecificAssetGroups(string assetType, IEnumerable assets, string? runtime, string? assetType, Utf8JsonWriter jsonWriter) + private static void AddRuntimeSpecificAssets(IEnumerable assets, string? runtime, string? assetType, Utf8JsonWriter jsonWriter) { foreach (RuntimeFile asset in assets) { @@ -353,7 +353,7 @@ private void AddRuntimeSpecificAssets(IEnumerable assets, string? r } } - private void WriteAssetList(string key, IEnumerable assetPaths, Utf8JsonWriter jsonWriter) + private static void WriteAssetList(string key, IEnumerable assetPaths, Utf8JsonWriter jsonWriter) { jsonWriter.WriteStartObject(key); foreach (string assembly in assetPaths) @@ -364,7 +364,7 @@ private void WriteAssetList(string key, IEnumerable assetPaths, Utf8Json jsonWriter.WriteEndObject(); } - private void WriteAssetList(string key, IEnumerable runtimeFiles, Utf8JsonWriter jsonWriter) + private static void WriteAssetList(string key, IEnumerable runtimeFiles, Utf8JsonWriter jsonWriter) { jsonWriter.WriteStartObject(key); @@ -388,7 +388,7 @@ private void WriteAssetList(string key, IEnumerable runtimeFiles, U jsonWriter.WriteEndObject(); } - private void WriteLibraries(DependencyContext context, Utf8JsonWriter jsonWriter) + private static void WriteLibraries(DependencyContext context, Utf8JsonWriter jsonWriter) { IEnumerable> allLibraries = context.RuntimeLibraries.Cast().Concat(context.CompileLibraries) @@ -402,7 +402,7 @@ private void WriteLibraries(DependencyContext context, Utf8JsonWriter jsonWriter jsonWriter.WriteEndObject(); } - private void WriteLibrary(string key, Library library, Utf8JsonWriter jsonWriter) + private static void WriteLibrary(string key, Library library, Utf8JsonWriter jsonWriter) { jsonWriter.WriteStartObject(key); jsonWriter.WriteString(DependencyContextStrings.TypePropertyName, library.Type); diff --git a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/InMemoryDirectoryInfo.cs b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/InMemoryDirectoryInfo.cs index 9f0c95f2d55f3..0997fd33c67f9 100644 --- a/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/InMemoryDirectoryInfo.cs +++ b/src/libraries/Microsoft.Extensions.FileSystemGlobbing/src/InMemoryDirectoryInfo.cs @@ -108,7 +108,7 @@ public override IEnumerable EnumerateFileSystemInfos() } } - private bool IsRootDirectory(string rootDir, string filePath) + private static bool IsRootDirectory(string rootDir, string filePath) { int rootDirLength = rootDir.Length; diff --git a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ApplicationLifetime.cs b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ApplicationLifetime.cs index 2f527097be4a1..f30af85526924 100644 --- a/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ApplicationLifetime.cs +++ b/src/libraries/Microsoft.Extensions.Hosting/src/Internal/ApplicationLifetime.cs @@ -100,7 +100,7 @@ public void NotifyStopped() } } - private void ExecuteHandlers(CancellationTokenSource cancel) + private static void ExecuteHandlers(CancellationTokenSource cancel) { // Noop if this is already cancelled if (cancel.IsCancellationRequested) diff --git a/src/libraries/Microsoft.Extensions.Logging.Configuration/src/LoggerFilterConfigureOptions.cs b/src/libraries/Microsoft.Extensions.Logging.Configuration/src/LoggerFilterConfigureOptions.cs index 87948d69e521c..d814e343c7bea 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Configuration/src/LoggerFilterConfigureOptions.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Configuration/src/LoggerFilterConfigureOptions.cs @@ -57,7 +57,7 @@ private void LoadDefaultConfigValues(LoggerFilterOptions options) bool GetCaptureScopesValue(LoggerFilterOptions options) => _configuration.GetValue(nameof(options.CaptureScopes), options.CaptureScopes); } - private void LoadRules(LoggerFilterOptions options, IConfigurationSection configurationSection, string logger) + private static void LoadRules(LoggerFilterOptions options, IConfigurationSection configurationSection, string logger) { foreach (System.Collections.Generic.KeyValuePair section in configurationSection.AsEnumerable(true)) { diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParsingLogConsole.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParsingLogConsole.cs index 8c22f9d93ca4d..8cab45f3ffc06 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParsingLogConsole.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/AnsiParsingLogConsole.cs @@ -27,13 +27,13 @@ public void Write(string message) _parser.Parse(message); } - private bool SetColor(ConsoleColor? background, ConsoleColor? foreground) + private static bool SetColor(ConsoleColor? background, ConsoleColor? foreground) { var backgroundChanged = SetBackgroundColor(background); return SetForegroundColor(foreground) || backgroundChanged; } - private bool SetBackgroundColor(ConsoleColor? background) + private static bool SetBackgroundColor(ConsoleColor? background) { if (background.HasValue) { @@ -43,7 +43,7 @@ private bool SetBackgroundColor(ConsoleColor? background) return false; } - private bool SetForegroundColor(ConsoleColor? foreground) + private static bool SetForegroundColor(ConsoleColor? foreground) { if (foreground.HasValue) { @@ -53,7 +53,7 @@ private bool SetForegroundColor(ConsoleColor? foreground) return false; } - private void ResetColor() + private static void ResetColor() { System.Console.ResetColor(); } diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerProvider.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerProvider.cs index 9f4c45a6f9589..8c71e96e21f9d 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerProvider.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/ConsoleLoggerProvider.cs @@ -157,7 +157,7 @@ public ILogger CreateLogger(string name) } #pragma warning disable CS0618 - private void UpdateFormatterOptions(ConsoleFormatter formatter, ConsoleLoggerOptions deprecatedFromOptions) + private static void UpdateFormatterOptions(ConsoleFormatter formatter, ConsoleLoggerOptions deprecatedFromOptions) { // kept for deprecated apis: if (formatter is SimpleConsoleFormatter defaultFormatter) diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/JsonConsoleFormatter.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/JsonConsoleFormatter.cs index b92de57e31064..f6bdea56c57bd 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/JsonConsoleFormatter.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/JsonConsoleFormatter.cs @@ -128,7 +128,7 @@ private void WriteScopeInformation(Utf8JsonWriter writer, IExternalScopeProvider } } - private void WriteItem(Utf8JsonWriter writer, KeyValuePair item) + private static void WriteItem(Utf8JsonWriter writer, KeyValuePair item) { var key = item.Key; switch (item.Value) diff --git a/src/libraries/Microsoft.Extensions.Logging.Console/src/SimpleConsoleFormatter.cs b/src/libraries/Microsoft.Extensions.Logging.Console/src/SimpleConsoleFormatter.cs index 73a7514278f0d..0ec05de570060 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Console/src/SimpleConsoleFormatter.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Console/src/SimpleConsoleFormatter.cs @@ -110,7 +110,7 @@ private void CreateDefaultLogMessage(TextWriter textWriter, in LogEntry< } } - private void WriteMessage(TextWriter textWriter, string message, bool singleLine) + private static void WriteMessage(TextWriter textWriter, string message, bool singleLine) { if (!string.IsNullOrEmpty(message)) { diff --git a/src/libraries/Microsoft.Extensions.Logging.Debug/src/DebugLogger.debug.cs b/src/libraries/Microsoft.Extensions.Logging.Debug/src/DebugLogger.debug.cs index 860a2f8ccf3da..c54d85f4c1f84 100644 --- a/src/libraries/Microsoft.Extensions.Logging.Debug/src/DebugLogger.debug.cs +++ b/src/libraries/Microsoft.Extensions.Logging.Debug/src/DebugLogger.debug.cs @@ -10,7 +10,7 @@ namespace Microsoft.Extensions.Logging.Debug { internal sealed partial class DebugLogger { - private void DebugWriteLine(string message, string name) + private static void DebugWriteLine(string message, string name) { System.Diagnostics.Debug.WriteLine(message, category: name); } diff --git a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogLogger.cs b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogLogger.cs index c8eac36b02acb..144cf67c103f9 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogLogger.cs +++ b/src/libraries/Microsoft.Extensions.Logging.EventLog/src/EventLogLogger.cs @@ -179,7 +179,7 @@ private void WriteMessage(string message, EventLogEntryType eventLogEntryType, i } } - private EventLogEntryType GetEventLogEntryType(LogLevel level) + private static EventLogEntryType GetEventLogEntryType(LogLevel level) { switch (level) { diff --git a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLogger.cs b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLogger.cs index 0794064b1a0ae..e69ad6ab3eff2 100644 --- a/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLogger.cs +++ b/src/libraries/Microsoft.Extensions.Logging.EventSource/src/EventSourceLogger.cs @@ -185,7 +185,7 @@ public void Dispose() /// The exception to get information for. /// ExceptionInfo object represending a .NET Exception /// ETW does not support a concept of a null value. So we use an un-initialized object if there is no exception in the event data. - private ExceptionInfo GetExceptionInfo(Exception? exception) + private static ExceptionInfo GetExceptionInfo(Exception? exception) { return exception != null ? new ExceptionInfo(exception) : ExceptionInfo.Empty; } @@ -193,7 +193,7 @@ private ExceptionInfo GetExceptionInfo(Exception? exception) /// /// Converts an ILogger state object into a set of key-value pairs (That can be send to a EventSource) /// - private IReadOnlyList> GetProperties(object? state) + private static IReadOnlyList> GetProperties(object? state) { if (state is IReadOnlyList> keyValuePairs) { @@ -209,7 +209,7 @@ private ExceptionInfo GetExceptionInfo(Exception? exception) return Array.Empty>(); } - private string ToJson(IReadOnlyList> keyValues) + private static string ToJson(IReadOnlyList> keyValues) { using var stream = new MemoryStream(); using var writer = new Utf8JsonWriter(stream); diff --git a/src/libraries/Microsoft.NETCore.Platforms/src/GenerateRuntimeGraph.cs b/src/libraries/Microsoft.NETCore.Platforms/src/GenerateRuntimeGraph.cs index f60a4f26ff83c..263b437bd8e1f 100644 --- a/src/libraries/Microsoft.NETCore.Platforms/src/GenerateRuntimeGraph.cs +++ b/src/libraries/Microsoft.NETCore.Platforms/src/GenerateRuntimeGraph.cs @@ -240,7 +240,7 @@ public override bool Execute() return !Log.HasLoggedErrors; } - private void EnsureWritable(string file) + private static void EnsureWritable(string file) { if (File.Exists(file)) { diff --git a/src/libraries/Microsoft.NETCore.Platforms/src/RuntimeGroup.cs b/src/libraries/Microsoft.NETCore.Platforms/src/RuntimeGroup.cs index 76fde331a1a3a..83f324595954a 100644 --- a/src/libraries/Microsoft.NETCore.Platforms/src/RuntimeGroup.cs +++ b/src/libraries/Microsoft.NETCore.Platforms/src/RuntimeGroup.cs @@ -264,7 +264,7 @@ internal IEnumerable GetRIDMappings() } } - private bool IsNullOrRoot(string rid) + private static bool IsNullOrRoot(string rid) { return rid == null || rid == rootRID; } diff --git a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft.VisualBasic.Core.vbproj b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft.VisualBasic.Core.vbproj index 060ab1a99b1a7..7dd0b0b698e07 100644 --- a/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft.VisualBasic.Core.vbproj +++ b/src/libraries/Microsoft.VisualBasic.Core/src/Microsoft.VisualBasic.Core.vbproj @@ -9,7 +9,7 @@ Binary 42025 $(DefineConstants),LATEBINDING=True - $(NoWarn),CA1052,CA1810,CA2200 + $(NoWarn),CA1052,CA1810,CA1822,CA2200 Microsoft.VisualBasic.Core false 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 index 78a945e3e25a0..3d4274c68150f 100644 --- a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.FileSystem.cs +++ b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.FileSystem.cs @@ -8,32 +8,32 @@ namespace Microsoft.Win32 { public sealed partial class RegistryKey : MarshalByRefObject, IDisposable { - private void ClosePerfDataKey() + private static void ClosePerfDataKey() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } - private void FlushCore() + private static void FlushCore() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } - private RegistryKey CreateSubKeyInternalCore(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions) + private static RegistryKey CreateSubKeyInternalCore(string subkey, RegistryKeyPermissionCheck permissionCheck, RegistryOptions registryOptions) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } - private void DeleteSubKeyCore(string subkey, bool throwOnMissingSubKey) + private static void DeleteSubKeyCore(string subkey, bool throwOnMissingSubKey) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } - private void DeleteSubKeyTreeCore(string subkey) + private static void DeleteSubKeyTreeCore(string subkey) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } - private void DeleteValueCore(string name, bool throwOnMissingValue) + private static void DeleteValueCore(string name, bool throwOnMissingValue) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } @@ -48,22 +48,22 @@ private static RegistryKey OpenRemoteBaseKeyCore(RegistryHive hKey, string machi throw new PlatformNotSupportedException(SR.Security_RegistryPermission); // remote stores not supported on Unix } - private RegistryKey InternalOpenSubKeyCore(string name, RegistryKeyPermissionCheck permissionCheck, int rights) + private static RegistryKey InternalOpenSubKeyCore(string name, RegistryKeyPermissionCheck permissionCheck, int rights) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } - private RegistryKey InternalOpenSubKeyCore(string name, bool writable) + private static RegistryKey InternalOpenSubKeyCore(string name, bool writable) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } - internal RegistryKey InternalOpenSubKeyWithoutSecurityChecksCore(string name, bool writable) + internal static RegistryKey InternalOpenSubKeyWithoutSecurityChecksCore(string name, bool writable) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } - private SafeRegistryHandle SystemKeyHandle + private static SafeRegistryHandle SystemKeyHandle { get { @@ -71,37 +71,37 @@ private SafeRegistryHandle SystemKeyHandle } } - private int InternalSubKeyCountCore() + private static int InternalSubKeyCountCore() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } - private string[] InternalGetSubKeyNamesCore(int subkeys) + private static string[] InternalGetSubKeyNamesCore(int subkeys) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } - private int InternalValueCountCore() + private static int InternalValueCountCore() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } - private string[] GetValueNamesCore(int values) + private static string[] GetValueNamesCore(int values) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } - private object InternalGetValueCore(string? name, object? defaultValue, bool doNotExpand) + private static object InternalGetValueCore(string? name, object? defaultValue, bool doNotExpand) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } - private RegistryValueKind GetValueKindCore(string? name) + private static RegistryValueKind GetValueKindCore(string? name) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } - private void SetValueCore(string? name, object value, RegistryValueKind valueKind) + private static void SetValueCore(string? name, object value, RegistryValueKind valueKind) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry); } diff --git a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs index 20dcbb887140b..f68e00f442db1 100644 --- a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs +++ b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.Windows.cs @@ -57,7 +57,7 @@ namespace Microsoft.Win32 { public sealed partial class RegistryKey : MarshalByRefObject, IDisposable { - private void ClosePerfDataKey() + private static void ClosePerfDataKey() { // System keys should never be closed. However, we want to call RegCloseKey // on HKEY_PERFORMANCE_DATA when called from PerformanceCounter.CloseSharedResources 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 49d2c2f3a7d97..4dd90defa662b 100644 --- a/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs +++ b/src/libraries/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKey.cs @@ -573,7 +573,7 @@ public void SetValue(string? name, object value!!, RegistryValueKind valueKind) SetValueCore(name, value, valueKind); } - private RegistryValueKind CalculateValueKind(object value) + private static RegistryValueKind CalculateValueKind(object value) { // This logic matches what used to be in SetValue(string name, object value) in the v1.0 and v1.1 days. // Even though we could add detection for an int64 in here, we want to maintain compatibility with the diff --git a/src/libraries/Microsoft.Win32.SystemEvents/src/Microsoft/Win32/SystemEvents.cs b/src/libraries/Microsoft.Win32.SystemEvents/src/Microsoft/Win32/SystemEvents.cs index c3f9bd89c5a3f..da1131ca12dc4 100644 --- a/src/libraries/Microsoft.Win32.SystemEvents/src/Microsoft/Win32/SystemEvents.cs +++ b/src/libraries/Microsoft.Win32.SystemEvents/src/Microsoft/Win32/SystemEvents.cs @@ -370,7 +370,7 @@ private bool ConsoleHandlerProc(int signalType) return false; } - private IntPtr DefWndProc + private static IntPtr DefWndProc { get { @@ -517,7 +517,7 @@ private static void EnsureRegisteredSessionNotification() } } - private UserPreferenceCategory GetUserPreferenceCategory(int msg, IntPtr wParam, IntPtr lParam) + private static UserPreferenceCategory GetUserPreferenceCategory(int msg, IntPtr wParam, IntPtr lParam) { UserPreferenceCategory pref = UserPreferenceCategory.General; @@ -703,7 +703,7 @@ private unsafe void Initialize() /// This empties this control's callback queue, propagating any exceptions /// back as needed. /// - private void InvokeMarshaledCallbacks() + private static void InvokeMarshaledCallbacks() { Debug.Assert(s_threadCallbackList != null, "Invoking marshaled callbacks before there are any"); diff --git a/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs b/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs index 1dc2afa7ab821..f9308292e79c2 100644 --- a/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs +++ b/src/libraries/Microsoft.XmlSerializer.Generator/src/Sgen.cs @@ -220,7 +220,7 @@ private int Run(string[] args) return 0; } - private void GenerateFile(List typeNames, string defaultNamespace, string assemblyName, bool proxyOnly, bool silent, bool verbose, bool force, string outputDirectory, bool parsableerrors) + 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); Type[] types; @@ -420,7 +420,7 @@ private void GenerateFile(List typeNames, string defaultNamespace, strin } - private bool ArgumentMatch(string arg, string formal) + private static bool ArgumentMatch(string arg, string formal) { // Full name format, eg: --assembly if (arg.Length < 3 || arg[0] != '-' || arg[1] != '-') @@ -431,7 +431,7 @@ private bool ArgumentMatch(string arg, string formal) return arg.Equals(formal, StringComparison.InvariantCultureIgnoreCase); } - private bool ShortNameArgumentMatch(string arg, string shortName) + private static bool ShortNameArgumentMatch(string arg, string shortName) { // Short name format, eg: -a if (arg.Length < 2 || arg[0] != '-') @@ -442,7 +442,7 @@ private bool ShortNameArgumentMatch(string arg, string shortName) return arg.Equals(shortName, StringComparison.InvariantCultureIgnoreCase); } - private void ImportType(Type type, string defaultNamespace, List mappings, List importedTypes, bool verbose, XmlReflectionImporter importer, bool parsableerrors) + private static void ImportType(Type type, string defaultNamespace, List mappings, List importedTypes, bool verbose, XmlReflectionImporter importer, bool parsableerrors) { XmlTypeMapping xmlTypeMapping; var localImporter = new XmlReflectionImporter(defaultNamespace); @@ -486,7 +486,7 @@ private static Assembly LoadAssembly(string assemblyName, bool throwOnFail) return assembly; } - private void WriteHeader() + private static void WriteHeader() { // do not localize Copyright header Console.WriteLine($".NET Xml Serialization Generation Utility, Version {ThisAssembly.InformationalVersion}]"); @@ -662,7 +662,7 @@ private static Assembly SgenAssemblyResolver(object source, ResolveEventArgs e) return null; } - private string[] ParseResponseFile(string[] args) + private static string[] ParseResponseFile(string[] args) { var parsedArgs = new List(); foreach (string arg in args) diff --git a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.PlatformNotSupported.cs b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.PlatformNotSupported.cs index ba4806e5a07cc..376aabc16b49c 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.PlatformNotSupported.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.PlatformNotSupported.cs @@ -8,7 +8,7 @@ namespace Microsoft.CSharp { internal sealed partial class CSharpCodeGenerator { - private CompilerResults FromFileBatch(CompilerParameters options, string[] fileNames) + private static CompilerResults FromFileBatch(CompilerParameters options, string[] fileNames) { throw new PlatformNotSupportedException(); } diff --git a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs index cf872800a7bd9..2dfbca9def9ba 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs @@ -62,9 +62,9 @@ internal CSharpCodeGenerator(IDictionary providerOptions) private bool _generatingForLoop; - private string FileExtension => ".cs"; + private static string FileExtension => ".cs"; - private string CompilerName => "csc.exe"; + private static string CompilerName => "csc.exe"; private string CurrentTypeName => _currentClass != null ? _currentClass.Name : "<% unknown %>"; @@ -84,7 +84,7 @@ private int Indent private bool IsCurrentDelegate => _currentClass != null && _currentClass is CodeTypeDelegate; - private string NullToken => "null"; + private static string NullToken => "null"; private TextWriter Output => _output; @@ -157,7 +157,7 @@ private string QuoteSnippetStringCStyle(string value) return b.ToString(); } - private string QuoteSnippetStringVerbatimStyle(string value) + private static string QuoteSnippetStringVerbatimStyle(string value) { var b = new StringBuilder(value.Length + 5); @@ -490,7 +490,7 @@ private void GenerateMethodReferenceExpression(CodeMethodReferenceExpression e) } } - private bool GetUserData(CodeObject e, string property, bool defaultValue) + private static bool GetUserData(CodeObject e, string property, bool defaultValue) { object o = e.UserData[property]; if (o != null && o is bool) @@ -2957,7 +2957,7 @@ private CompilerResults FromDom(CompilerParameters options!!, CodeCompileUnit e) } - private CompilerResults FromFile(CompilerParameters options!!, string fileName!!) + private static CompilerResults FromFile(CompilerParameters options!!, string fileName!!) { // Try opening the file to make sure it exists. This will throw an exception // if it doesn't @@ -2966,7 +2966,7 @@ private CompilerResults FromFile(CompilerParameters options!!, string fileName!! return FromFileBatch(options, new string[1] { fileName }); } - private CompilerResults FromSource(CompilerParameters options!!, string source) + private static CompilerResults FromSource(CompilerParameters options!!, string source) { return FromSourceBatch(options, new string[1] { source }); } @@ -2995,7 +2995,7 @@ private CompilerResults FromDomBatch(CompilerParameters options!!, CodeCompileUn return FromFileBatch(options, filenames); } - private void ResolveReferencedAssemblies(CompilerParameters options, CodeCompileUnit e) + private static void ResolveReferencedAssemblies(CompilerParameters options, CodeCompileUnit e) { if (e.ReferencedAssemblies.Count > 0) { @@ -3009,7 +3009,7 @@ private void ResolveReferencedAssemblies(CompilerParameters options, CodeCompile } } - private CompilerResults FromSourceBatch(CompilerParameters options!!, string[] sources!!) + private static CompilerResults FromSourceBatch(CompilerParameters options!!, string[] sources!!) { string[] filenames = new string[sources.Length]; diff --git a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeGenerator.cs b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeGenerator.cs index 68b7ba79b4bd6..b28c58a622666 100644 --- a/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeGenerator.cs +++ b/src/libraries/System.CodeDom/src/Microsoft/VisualBasic/VBCodeGenerator.cs @@ -260,7 +260,7 @@ internal VBCodeGenerator(IDictionary providerOptions) protected override string NullToken => "Nothing"; - private void EnsureInDoubleQuotes(ref bool fInDoubleQuotes, StringBuilder b) + private static void EnsureInDoubleQuotes(ref bool fInDoubleQuotes, StringBuilder b) { if (fInDoubleQuotes) { @@ -271,7 +271,7 @@ private void EnsureInDoubleQuotes(ref bool fInDoubleQuotes, StringBuilder b) fInDoubleQuotes = true; } - private void EnsureNotInDoubleQuotes(ref bool fInDoubleQuotes, StringBuilder b) + private static void EnsureNotInDoubleQuotes(ref bool fInDoubleQuotes, StringBuilder b) { if (!fInDoubleQuotes) { @@ -1192,7 +1192,7 @@ protected override void GenerateExpressionStatement(CodeExpressionStatement e) Output.WriteLine(); } - private bool IsDocComment(CodeCommentStatement comment) + private static bool IsDocComment(CodeCommentStatement comment) { return ((comment != null) && (comment.Comment != null) && comment.Comment.DocComment); } @@ -1539,7 +1539,7 @@ protected override void GenerateField(CodeMemberField e) } } - private bool MethodIsOverloaded(CodeMemberMethod e, CodeTypeDeclaration c) + private static bool MethodIsOverloaded(CodeMemberMethod e, CodeTypeDeclaration c) { if ((e.Attributes & MemberAttributes.Overloaded) != 0) { @@ -1701,7 +1701,7 @@ protected override void GenerateEntryPointMethod(CodeEntryPointMethod e, CodeTyp Output.WriteLine("End Sub"); } - private bool PropertyIsOverloaded(CodeMemberProperty e, CodeTypeDeclaration c) + private static bool PropertyIsOverloaded(CodeMemberProperty e, CodeTypeDeclaration c) { if ((e.Attributes & MemberAttributes.Overloaded) != 0) { @@ -2159,7 +2159,7 @@ protected override void GenerateNamespace(CodeNamespace e) GenerateNamespaceEnd(e); } - private bool AllowLateBound(CodeCompileUnit e) + private static bool AllowLateBound(CodeCompileUnit e) { object o = e.UserData["AllowLateBound"]; if (o != null && o is bool) @@ -2171,7 +2171,7 @@ private bool AllowLateBound(CodeCompileUnit e) return true; } - private bool RequireVariableDeclaration(CodeCompileUnit e) + private static bool RequireVariableDeclaration(CodeCompileUnit e) { object o = e.UserData["RequireVariableDeclaration"]; if (o != null && o is bool) @@ -2181,7 +2181,7 @@ private bool RequireVariableDeclaration(CodeCompileUnit e) return true; } - private bool GetUserData(CodeObject e, string property, bool defaultValue) + private static bool GetUserData(CodeObject e, string property, bool defaultValue) { object o = e.UserData[property]; if (o != null && o is bool) diff --git a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs index 25ee9eefcb1b2..e2da041b18e0a 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeCompiler.cs @@ -133,7 +133,7 @@ protected virtual CompilerResults FromDomBatch(CompilerParameters options!!, Cod return FromFileBatch(options, filenames); } - private void ResolveReferencedAssemblies(CompilerParameters options, CodeCompileUnit e) + private static void ResolveReferencedAssemblies(CompilerParameters options, CodeCompileUnit e) { if (e.ReferencedAssemblies.Count > 0) { 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 f2c970d1afd04..e68b6c4a20eca 100644 --- a/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs +++ b/src/libraries/System.CodeDom/src/System/CodeDom/Compiler/CodeValidator.cs @@ -23,7 +23,7 @@ internal void ValidateIdentifiers(CodeObject e) } else if (e is CodeComment) { - ValidateComment((CodeComment)e); + // do nothing } else if (e is CodeExpression) { @@ -68,7 +68,6 @@ private void ValidateTypeMember(CodeTypeMember e) ValidateCommentStatements(e.Comments); ValidateCodeDirectives(e.StartDirectives); ValidateCodeDirectives(e.EndDirectives); - if (e.LinePragma != null) ValidateLinePragmaStart(e.LinePragma); if (e is CodeMemberEvent) { @@ -88,7 +87,7 @@ private void ValidateTypeMember(CodeTypeMember e) } else if (e is CodeSnippetTypeMember) { - ValidateSnippetMember((CodeSnippetTypeMember)e); + // do nothing } else if (e is CodeTypeDeclaration) { @@ -106,21 +105,15 @@ private void ValidateCodeCompileUnit(CodeCompileUnit e) ValidateCodeDirectives(e.EndDirectives); if (e is CodeSnippetCompileUnit) { - ValidateSnippetCompileUnit((CodeSnippetCompileUnit)e); + // do nothing } else { ValidateCompileUnitStart(e); ValidateNamespaces(e); - ValidateCompileUnitEnd(e); } } - private void ValidateSnippetCompileUnit(CodeSnippetCompileUnit e) - { - if (e.LinePragma != null) ValidateLinePragmaStart(e.LinePragma); - } - private void ValidateCompileUnitStart(CodeCompileUnit e) { if (e.AssemblyCustomAttributes.Count > 0) @@ -129,10 +122,6 @@ private void ValidateCompileUnitStart(CodeCompileUnit e) } } - private void ValidateCompileUnitEnd(CodeCompileUnit e) - { - } - private void ValidateNamespaces(CodeCompileUnit e) { foreach (CodeNamespace n in e.Namespaces) @@ -158,15 +147,10 @@ private static void ValidateNamespaceStart(CodeNamespace e) } } - private void ValidateNamespaceImports(CodeNamespace e) + private static void ValidateNamespaceImports(CodeNamespace e) { foreach (CodeNamespaceImport imp in e.Imports) { - if (imp.LinePragma != null) - { - ValidateLinePragmaStart(imp.LinePragma); - } - ValidateNamespaceImport(imp); } } @@ -334,7 +318,6 @@ private void ValidateProperty(CodeMemberProperty e) private void ValidateMemberMethod(CodeMemberMethod e) { ValidateCommentStatements(e.Comments); - if (e.LinePragma != null) ValidateLinePragmaStart(e.LinePragma); ValidateTypeParameters(e.TypeParameters); ValidateTypeReferences(e.ImplementationTypes); @@ -389,10 +372,6 @@ private void ValidateMethod(CodeMemberMethod e) } } - private void ValidateSnippetMember(CodeSnippetTypeMember e) - { - } - private void ValidateTypeStart(CodeTypeDeclaration e) { ValidateCommentStatements(e.Comments); @@ -416,7 +395,7 @@ private void ValidateTypeStart(CodeTypeDeclaration e) } } - private void ValidateCommentStatements(CodeCommentStatementCollection e) + private static void ValidateCommentStatements(CodeCommentStatementCollection e) { foreach (CodeCommentStatement comment in e) { @@ -424,12 +403,7 @@ private void ValidateCommentStatements(CodeCommentStatementCollection e) } } - private void ValidateCommentStatement(CodeCommentStatement e) - { - ValidateComment(e.Comment); - } - - private void ValidateComment(CodeComment e) + private static void ValidateCommentStatement(CodeCommentStatement e) { } @@ -472,7 +446,7 @@ private void ValidateStatement(CodeStatement e!!) } else if (e is CodeSnippetStatement) { - ValidateSnippetStatement((CodeSnippetStatement)e); + // do nothing } else if (e is CodeVariableDeclarationStatement) { @@ -612,10 +586,6 @@ private void ValidateVariableDeclarationStatement(CodeVariableDeclarationStateme } } - private void ValidateLinePragmaStart(CodeLinePragma e) - { - } - private void ValidateEvent(CodeMemberEvent e) { if (e.CustomAttributes.Count > 0) @@ -639,10 +609,6 @@ private void ValidateParameters(CodeParameterDeclarationExpressionCollection par } } - private void ValidateSnippetStatement(CodeSnippetStatement e) - { - } - private void ValidateExpressionList(CodeExpressionCollection expressions) { foreach (CodeExpression current in expressions) @@ -720,7 +686,7 @@ private void ValidateExpression(CodeExpression e) } else if (e is CodeBaseReferenceExpression) { - ValidateBaseReferenceExpression((CodeBaseReferenceExpression)e); + // Nothing to validate } else if (e is CodeBinaryOperatorExpression) { @@ -760,7 +726,7 @@ private void ValidateExpression(CodeExpression e) } else if (e is CodeSnippetExpression) { - ValidateSnippetExpression((CodeSnippetExpression)e); + // do nothing } else if (e is CodeMethodInvokeExpression) { @@ -792,7 +758,7 @@ private void ValidateExpression(CodeExpression e) } else if (e is CodePrimitiveExpression) { - ValidatePrimitiveExpression((CodePrimitiveExpression)e); + // do nothing } else if (e is CodePropertyReferenceExpression) { @@ -800,11 +766,11 @@ private void ValidateExpression(CodeExpression e) } else if (e is CodePropertySetValueReferenceExpression) { - ValidatePropertySetValueReferenceExpression((CodePropertySetValueReferenceExpression)e); + // Do nothing } else if (e is CodeThisReferenceExpression) { - ValidateThisReferenceExpression((CodeThisReferenceExpression)e); + // Do nothing } else if (e is CodeTypeReferenceExpression) { @@ -844,10 +810,6 @@ private void ValidateArrayCreateExpression(CodeArrayCreateExpression e) } } - private void ValidateBaseReferenceExpression(CodeBaseReferenceExpression e) - { // Nothing to validate - } - private void ValidateBinaryOperatorExpression(CodeBinaryOperatorExpression e) { ValidateExpression(e.Left); @@ -909,10 +871,6 @@ private void ValidateArrayIndexerExpression(CodeArrayIndexerExpression e) } } - private void ValidateSnippetExpression(CodeSnippetExpression e) - { - } - private void ValidateMethodInvokeExpression(CodeMethodInvokeExpression e) { ValidateMethodReferenceExpression(e.Method); @@ -969,10 +927,6 @@ private void ValidateDirectionExpression(CodeDirectionExpression e) ValidateExpression(e.Expression); } - private void ValidatePrimitiveExpression(CodePrimitiveExpression e) - { - } - private void ValidatePropertyReferenceExpression(CodePropertyReferenceExpression e) { if (e.TargetObject != null) @@ -982,14 +936,6 @@ private void ValidatePropertyReferenceExpression(CodePropertyReferenceExpression ValidateIdentifier(e, nameof(e.PropertyName), e.PropertyName); } - private void ValidatePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e) - { // Do nothing - } - - private void ValidateThisReferenceExpression(CodeThisReferenceExpression e) - { // Do nothing - } - private static void ValidateTypeOfExpression(CodeTypeOfExpression e) { ValidateTypeReference(e.Type); diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentBag.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentBag.cs index 25f7d4451584c..5a49c44c71015 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentBag.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentBag.cs @@ -238,7 +238,7 @@ private bool TrySteal([MaybeNullWhen(false)] out T result, bool take) /// /// Attempts to steal from each queue starting from to . /// - private bool TryStealFromTo(WorkStealingQueue? startInclusive, WorkStealingQueue? endExclusive, [MaybeNullWhen(false)] out T result, bool take) + private static bool TryStealFromTo(WorkStealingQueue? startInclusive, WorkStealingQueue? endExclusive, [MaybeNullWhen(false)] out T result, bool take) { for (WorkStealingQueue? queue = startInclusive; queue != endExclusive; queue = queue._nextQueue) { diff --git a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentStack.cs b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentStack.cs index 7416c2c9c17c0..d3921f989d0a1 100644 --- a/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentStack.cs +++ b/src/libraries/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentStack.cs @@ -689,7 +689,7 @@ private List ToList() /// Returns an array containing a snapshot of the list's contents starting at the specified node. /// /// A list of the stack's contents starting at the specified node. - private List ToList(Node? curr) + private static List ToList(Node? curr) { List list = new List(); @@ -725,7 +725,7 @@ public IEnumerator GetEnumerator() return GetEnumerator(_head); } - private IEnumerator GetEnumerator(Node? head) + private static IEnumerator GetEnumerator(Node? head) { Node? current = head; while (current != null) diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Enumerator.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Enumerator.cs index a4f0c6516f719..1e5d2af76bf94 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Enumerator.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableList_1.Enumerator.cs @@ -25,15 +25,6 @@ public sealed partial class ImmutableList [EditorBrowsable(EditorBrowsableState.Advanced)] public struct Enumerator : IEnumerator, ISecurePooledObjectUser, IStrongEnumerator { - /// - /// The resource pool of reusable mutable stacks for purposes of enumeration. - /// - /// - /// We utilize this resource pool to make "allocation free" enumeration achievable. - /// - private static readonly SecureObjectPool>, Enumerator> s_EnumeratingStacks = - new SecureObjectPool>, Enumerator>(); - /// /// The builder being enumerated, if applicable. /// @@ -113,9 +104,9 @@ internal Enumerator(Node root, Builder? builder = null, int startIndex = -1, int _stack = null; if (_count > 0) { - if (!s_EnumeratingStacks.TryTake(this, out _stack)) + if (!SecureObjectPool>, Enumerator>.TryTake(this, out _stack)) { - _stack = s_EnumeratingStacks.PrepNew(this, new Stack>(root.Height)); + _stack = SecureObjectPool>, Enumerator>.PrepNew(this, new Stack>(root.Height)); } this.ResetStack(); @@ -157,7 +148,7 @@ public void Dispose() if (_stack != null && _stack.TryUse(ref this, out Stack>? stack)) { stack.ClearFastWhenEmpty(); - s_EnumeratingStacks.TryAdd(this, _stack!); + SecureObjectPool>, Enumerator>.TryAdd(this, _stack!); } _stack = null; diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Enumerator.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Enumerator.cs index 9d68df2f94585..0b4c6dd97b772 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Enumerator.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedDictionary_2.Enumerator.cs @@ -25,15 +25,6 @@ public sealed partial class ImmutableSortedDictionary [EditorBrowsable(EditorBrowsableState.Advanced)] public struct Enumerator : IEnumerator>, ISecurePooledObjectUser { - /// - /// The resource pool of reusable mutable stacks for purposes of enumeration. - /// - /// - /// We utilize this resource pool to make "allocation free" enumeration achievable. - /// - private static readonly SecureObjectPool>, Enumerator> s_enumeratingStacks = - new SecureObjectPool>, Enumerator>(); - /// /// The builder being enumerated, if applicable. /// @@ -82,9 +73,9 @@ internal Enumerator(Node root, Builder? builder = null) _stack = null; if (!_root.IsEmpty) { - if (!s_enumeratingStacks.TryTake(this, out _stack)) + if (!SecureObjectPool>, Enumerator>.TryTake(this, out _stack)) { - _stack = s_enumeratingStacks.PrepNew(this, new Stack>(root.Height)); + _stack = SecureObjectPool>, Enumerator>.PrepNew(this, new Stack>(root.Height)); } this.PushLeft(_root); @@ -132,7 +123,7 @@ public void Dispose() if (_stack != null && _stack.TryUse(ref this, out Stack>? stack)) { stack.ClearFastWhenEmpty(); - s_enumeratingStacks.TryAdd(this, _stack!); + SecureObjectPool>, Enumerator>.TryAdd(this, _stack!); } _stack = null; diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Enumerator.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Enumerator.cs index 029815936870c..3def98eca30ec 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Enumerator.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Enumerator.cs @@ -24,15 +24,6 @@ public sealed partial class ImmutableSortedSet [EditorBrowsable(EditorBrowsableState.Advanced)] public struct Enumerator : IEnumerator, ISecurePooledObjectUser, IStrongEnumerator { - /// - /// The resource pool of reusable mutable stacks for purposes of enumeration. - /// - /// - /// We utilize this resource pool to make "allocation free" enumeration achievable. - /// - private static readonly SecureObjectPool>, Enumerator> s_enumeratingStacks = - new SecureObjectPool>, Enumerator>(); - /// /// The builder being enumerated, if applicable. /// @@ -94,9 +85,9 @@ internal Enumerator(Node root, Builder? builder = null, bool reverse = false) _enumeratingBuilderVersion = builder != null ? builder.Version : -1; _poolUserId = SecureObjectPool.NewId(); _stack = null; - if (!s_enumeratingStacks.TryTake(this, out _stack)) + if (!SecureObjectPool>, Enumerator>.TryTake(this, out _stack)) { - _stack = s_enumeratingStacks.PrepNew(this, new Stack>(root.Height)); + _stack = SecureObjectPool>, Enumerator>.PrepNew(this, new Stack>(root.Height)); } this.PushNext(_root); @@ -143,7 +134,7 @@ public void Dispose() if (_stack != null && _stack.TryUse(ref this, out Stack>? stack)) { stack.ClearFastWhenEmpty(); - s_enumeratingStacks.TryAdd(this, _stack!); + SecureObjectPool>, Enumerator>.TryAdd(this, _stack!); _stack = null; } } diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SecureObjectPool.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SecureObjectPool.cs index 363d69e0199c7..1e6fd54f55ab2 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SecureObjectPool.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SecureObjectPool.cs @@ -38,10 +38,10 @@ internal static int NewId() } } - internal sealed class SecureObjectPool + internal static class SecureObjectPool where TCaller : ISecurePooledObjectUser { - public void TryAdd(TCaller caller, SecurePooledObject item) + public static void TryAdd(TCaller caller, SecurePooledObject item) { // Only allow the caller to recycle this object if it is the current owner. if (caller.PoolUserId == item.Owner) @@ -51,7 +51,7 @@ public void TryAdd(TCaller caller, SecurePooledObject item) } } - public bool TryTake(TCaller caller, out SecurePooledObject? item) + public static bool TryTake(TCaller caller, out SecurePooledObject? item) { if (caller.PoolUserId != SecureObjectPool.UnassignedId && AllocFreeConcurrentStack>.TryTake(out item)) { @@ -65,7 +65,7 @@ public bool TryTake(TCaller caller, out SecurePooledObject? item) } } - public SecurePooledObject PrepNew(TCaller caller, T newValue) + public static SecurePooledObject PrepNew(TCaller caller, T newValue) { Requires.NotNullAllowStructs(newValue, nameof(newValue)); var pooledObject = new SecurePooledObject(newValue); diff --git a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SortedInt32KeyNode.Enumerator.cs b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SortedInt32KeyNode.Enumerator.cs index bbbc680b8aa85..caed1cef1b231 100644 --- a/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SortedInt32KeyNode.Enumerator.cs +++ b/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/SortedInt32KeyNode.Enumerator.cs @@ -24,15 +24,6 @@ internal sealed partial class SortedInt32KeyNode [EditorBrowsable(EditorBrowsableState.Advanced)] public struct Enumerator : IEnumerator>, ISecurePooledObjectUser { - /// - /// The resource pool of reusable mutable stacks for purposes of enumeration. - /// - /// - /// We utilize this resource pool to make "allocation free" enumeration achievable. - /// - private static readonly SecureObjectPool>>, Enumerator> s_enumeratingStacks = - new SecureObjectPool>>, Enumerator>(); - /// /// A unique ID for this instance of this enumerator. /// Used to protect pooled objects from use after they are recycled. @@ -68,9 +59,9 @@ internal Enumerator(SortedInt32KeyNode root) _stack = null; if (!_root.IsEmpty) { - if (!s_enumeratingStacks.TryTake(this, out _stack)) + if (!SecureObjectPool>>, Enumerator>.TryTake(this, out _stack)) { - _stack = s_enumeratingStacks.PrepNew(this, new Stack>>(root.Height)); + _stack = SecureObjectPool>>, Enumerator>.PrepNew(this, new Stack>>(root.Height)); } this.PushLeft(_root); @@ -118,7 +109,7 @@ public void Dispose() if (_stack != null && _stack.TryUse(ref this, out Stack>>? stack)) { stack.ClearFastWhenEmpty(); - s_enumeratingStacks.TryAdd(this, _stack!); + SecureObjectPool>>, Enumerator>.TryAdd(this, _stack!); } _stack = null; diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs b/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs index acb0f425c76a3..e3cee881d67ca 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/LinkedList.cs @@ -413,7 +413,7 @@ internal void InternalRemoveNode(LinkedListNode node) version++; } - internal void ValidateNewNode(LinkedListNode node!!) + internal static void ValidateNewNode(LinkedListNode node!!) { if (node.list != null) { diff --git a/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs b/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs index b2937c17c3901..7eac1a0b54509 100644 --- a/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs +++ b/src/libraries/System.Collections/src/System/Collections/Generic/PriorityQueue.cs @@ -563,12 +563,12 @@ private void RemoveRootNode() /// /// Gets the index of an element's parent. /// - private int GetParentIndex(int index) => (index - 1) >> Log2Arity; + private static int GetParentIndex(int index) => (index - 1) >> Log2Arity; /// /// Gets the index of the first child of an element. /// - private int GetFirstChildIndex(int index) => (index << Log2Arity) + 1; + private static int GetFirstChildIndex(int index) => (index << Log2Arity) + 1; /// /// Converts an unordered list into a heap. diff --git a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs index a086b9cfd1e57..629c339255bd7 100644 --- a/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs +++ b/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs @@ -235,7 +235,7 @@ private Dictionary CreatePropertyStoreItems() /// The property descriptor whose attributes are needed. /// A new stripped of any attributes from the property's type. [RequiresUnreferencedCode("The Type of propertyDescriptor.PropertyType cannot be statically discovered.")] - private AttributeCollection GetExplicitAttributes(PropertyDescriptor propertyDescriptor) + private static AttributeCollection GetExplicitAttributes(PropertyDescriptor propertyDescriptor) { AttributeCollection propertyDescriptorAttributes = propertyDescriptor.Attributes; List attributes = new List(propertyDescriptorAttributes.Count); diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs index 34d611c7e2121..7cb235e267b4e 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/AttributedModel/AttributedPartCreationInfo.cs @@ -318,7 +318,7 @@ private AttributedExportDefinition CreateExportDefinition(MemberInfo member, Exp return new AttributedExportDefinition(this, member, exportAttribute, typeIdentityType, contractName); } - private IEnumerable GetExportMembers(Type type) + private static IEnumerable GetExportMembers(Type type) { BindingFlags flags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; @@ -361,7 +361,7 @@ private IEnumerable GetExportMembers(Type type) } } - private IEnumerable GetInheritedExports(Type type) + private static IEnumerable GetInheritedExports(Type type) { // If the type is abstract we aren't interested in type level exports if (type.IsAbstract) @@ -437,7 +437,7 @@ private IEnumerable GetImportDefinitions() return imports; } - private IEnumerable GetImportMembers(Type type) + private static IEnumerable GetImportMembers(Type type) { if (type.IsAbstract) { @@ -468,7 +468,7 @@ private IEnumerable GetImportMembers(Type type) } } - private IEnumerable GetDeclaredOnlyImportMembers(Type type) + private static IEnumerable GetDeclaredOnlyImportMembers(Type type) { BindingFlags flags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.LifetimeContext.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.LifetimeContext.cs index 669977a0c1ea1..9321e722f5943 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.LifetimeContext.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.LifetimeContext.cs @@ -11,7 +11,7 @@ internal sealed partial class ExportFactoryCreator { private sealed class LifetimeContext { - public Tuple GetExportLifetimeContextFromExport(Export export) + public static Tuple GetExportLifetimeContextFromExport(Export export) { T exportedValue; Action disposeAction; diff --git a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.cs b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.cs index 983c96c1ab72e..85e2fd52b5988 100644 --- a/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.cs +++ b/src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ExportfactoryCreator.cs @@ -44,9 +44,7 @@ private object CreateStronglyTypedExportFactoryOfT(Export export) Type[] typeArgs = { typeof(T) }; Type constructed = _exportFactoryType.MakeGenericType(typeArgs); - var lifetimeContext = new LifetimeContext(); - - Func> exportLifetimeContextCreator = () => lifetimeContext.GetExportLifetimeContextFromExport(export); + Func> exportLifetimeContextCreator = () => LifetimeContext.GetExportLifetimeContextFromExport(export); object[] args = { exportLifetimeContextCreator }; var instance = Activator.CreateInstance(constructed, args); @@ -59,9 +57,7 @@ private object CreateStronglyTypedExportFactoryOfTM(Export export) Type[] typeArgs = { typeof(T), typeof(M) }; Type constructed = _exportFactoryType.MakeGenericType(typeArgs); - var lifetimeContext = new LifetimeContext(); - - Func> exportLifetimeContextCreator = () => lifetimeContext.GetExportLifetimeContextFromExport(export); + Func> exportLifetimeContextCreator = () => LifetimeContext.GetExportLifetimeContextFromExport(export); var metadataView = AttributedModelServices.GetMetadataView(export.Metadata); object?[] args = { exportLifetimeContextCreator, metadataView }; diff --git a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ImportConventionBuilder.cs b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ImportConventionBuilder.cs index fef34353fb59b..6be7f59b7ae8b 100644 --- a/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ImportConventionBuilder.cs +++ b/src/libraries/System.Composition.Convention/src/System/Composition/Convention/ImportConventionBuilder.cs @@ -169,7 +169,7 @@ internal void BuildAttributes(Type type, ref List attributes) return; } - private bool IsSupportedImportManyType(TypeInfo typeInfo) + private static bool IsSupportedImportManyType(TypeInfo typeInfo) { return typeInfo.IsArray || (typeInfo.IsGenericTypeDefinition && s_supportedImportManyTypes.Contains(typeInfo.AsType())) || diff --git a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/ExportDescriptorRegistryUpdate.cs b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/ExportDescriptorRegistryUpdate.cs index 2c01ff65bd108..48967a0259f20 100644 --- a/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/ExportDescriptorRegistryUpdate.cs +++ b/src/libraries/System.Composition.Hosting/src/System/Composition/Hosting/Core/ExportDescriptorRegistryUpdate.cs @@ -111,7 +111,7 @@ private void CheckDependency(CompositionDependency dependency, HashSet dependencies) + private static StringBuilder DescribeCompositionStack(CompositionDependency import, IEnumerable dependencies) { var result = new StringBuilder(); if (dependencies.FirstOrDefault() == null) diff --git a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/TypeInspector.cs b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/TypeInspector.cs index d6d63828d1f2f..4175cd37dfc8c 100644 --- a/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/TypeInspector.cs +++ b/src/libraries/System.Composition.TypedParts/src/System/Composition/TypedParts/Discovery/TypeInspector.cs @@ -99,7 +99,7 @@ private IEnumerable DiscoverPropertyExports(TypeInfo partType) } } - private void ReadLooseMetadata(object[] appliedAttributes, IDictionary metadata) + private static void ReadLooseMetadata(object[] appliedAttributes, IDictionary metadata) { foreach (var attribute in appliedAttributes) { @@ -119,7 +119,7 @@ private void ReadLooseMetadata(object[] appliedAttributes, IDictionary metadata, string name, Type valueType, object value) + private static void AddMetadata(IDictionary metadata, string name, Type valueType, object value) { object existingValue; if (!metadata.TryGetValue(name, out existingValue)) @@ -145,7 +145,7 @@ private void AddMetadata(IDictionary metadata, string name, Type } } - private void ReadMetadataAttribute(Attribute attribute, IDictionary metadata) + private static void ReadMetadataAttribute(Attribute attribute, IDictionary metadata) { var attrType = attribute.GetType(); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs index a2657c00f2b16..d8ef20ae59467 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/AppSettingsReader.cs @@ -71,7 +71,7 @@ public object GetValue(string key!!, Type type!!) } } - private int GetNoneNesting(string val) + private static int GetNoneNesting(string val) { int count = 0; int len = val.Length; 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 b0f6db13c9cf2..70606687d40dc 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ApplicationSettingsBase.cs @@ -25,7 +25,6 @@ public abstract class ApplicationSettingsBase : SettingsBase, INotifyPropertyCha private SettingsLoadedEventHandler _onSettingsLoaded; private SettingsSavingEventHandler _onSettingsSaving; private string _settingsKey = string.Empty; - private bool _firstLoad = true; private bool _initialized; /// @@ -708,18 +707,6 @@ private object GetPropertyValue(string propertyName) { if (PropertyValues[propertyName] == null) { - - // If this is our first load and we are part of a Clickonce app, call Upgrade. - if (_firstLoad) - { - _firstLoad = false; - - if (IsFirstRunOfClickOnceApp()) - { - Upgrade(); - } - } - // we query the value first so that we initialize all values from value providers and so that we don't end up // on an infinite recursion when calling Properties[propertyName] as that calls this. _ = base[propertyName]; @@ -741,16 +728,6 @@ private object GetPropertyValue(string propertyName) } } - /// - /// Returns true if this is a clickonce deployed app and this is the first run of the app - /// since deployment or last upgrade. - /// - private bool IsFirstRunOfClickOnceApp() - { - // Always false for .NET Core - return false; - } - /// /// Returns true if this is a clickonce deployed app. /// @@ -764,7 +741,7 @@ internal static bool IsClickOnceDeployed(AppDomain appDomain) /// Only those settings class properties that have a SettingAttribute on them are /// treated as settings. This routine filters out other properties. /// - private PropertyInfo[] SettingsFilter(PropertyInfo[] allProps) + private static PropertyInfo[] SettingsFilter(PropertyInfo[] allProps) { var settingProps = new List(); object[] attributes; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigurationHost.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigurationHost.cs index 190ec71abaf03..796d8a983a2b2 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigurationHost.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigurationHost.cs @@ -122,7 +122,7 @@ public override void RefreshConfigPaths() } // Return true if the config path is for a user.config file, false otherwise. - private bool IsUserConfig(string configPath) + private static bool IsUserConfig(string configPath) { return StringUtil.EqualsIgnoreCase(configPath, RoamingUserConfigPath) || StringUtil.EqualsIgnoreCase(configPath, LocalUserConfigPath); @@ -396,7 +396,7 @@ public override object return new ExeContext(GetUserLevel(configPath), ConfigPaths.ApplicationUri); } - private ConfigurationUserLevel GetUserLevel(string configPath) + private static ConfigurationUserLevel GetUserLevel(string configPath) { ConfigurationUserLevel level; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientSettingsStore.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientSettingsStore.cs index d342d6eb607cd..13e44567a36b9 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientSettingsStore.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ClientSettingsStore.cs @@ -24,7 +24,7 @@ internal sealed class ClientSettingsStore private const string ApplicationSettingsGroupPrefix = ApplicationSettingsGroupName + "/"; private const string UserSettingsGroupPrefix = UserSettingsGroupName + "/"; - private Configuration GetUserConfig(bool isRoaming) + private static Configuration GetUserConfig(bool isRoaming) { ConfigurationUserLevel userLevel = isRoaming ? ConfigurationUserLevel.PerUserRoaming : ConfigurationUserLevel.PerUserRoamingAndLocal; @@ -32,7 +32,7 @@ private Configuration GetUserConfig(bool isRoaming) return ClientSettingsConfigurationHost.OpenExeConfiguration(userLevel); } - private ClientSettingsSection GetConfigSection(Configuration config, string sectionName, bool declare) + private static ClientSettingsSection GetConfigSection(Configuration config, string sectionName, bool declare) { string fullSectionName = UserSettingsGroupPrefix + sectionName; ClientSettingsSection section = null; @@ -54,7 +54,7 @@ private ClientSettingsSection GetConfigSection(Configuration config, string sect // Declares the section handler of a given section in its section group, if a declaration isn't already // present. - private void DeclareSection(Configuration config, string sectionName) + private static void DeclareSection(Configuration config, string sectionName) { ConfigurationSectionGroup settingsGroup = config.GetSectionGroup(UserSettingsGroupName); @@ -82,7 +82,7 @@ private void DeclareSection(Configuration config, string sectionName) } } - internal IDictionary ReadSettings(string sectionName, bool isUserScoped) + internal static IDictionary ReadSettings(string sectionName, bool isUserScoped) { IDictionary settings = new Hashtable(); @@ -146,12 +146,12 @@ internal static IDictionary ReadSettingsFromFile(string configFileName, string s return settings; } - internal ConnectionStringSettingsCollection ReadConnectionStrings() + internal static ConnectionStringSettingsCollection ReadConnectionStrings() { return PrivilegedConfigurationManager.ConnectionStrings; } - internal void RevertToParent(string sectionName, bool isRoaming) + internal static void RevertToParent(string sectionName, bool isRoaming) { if (!ConfigurationManagerInternalFactory.Instance.SupportsUserConfig) { @@ -169,7 +169,7 @@ internal void RevertToParent(string sectionName, bool isRoaming) } } - internal void WriteSettings(string sectionName, bool isRoaming, IDictionary newSettings) + internal static void WriteSettings(string sectionName, bool isRoaming, IDictionary newSettings) { if (!ConfigurationManagerInternalFactory.Instance.SupportsUserConfig) { @@ -277,7 +277,7 @@ public override void InitForConfiguration(ref string locationSubPath, out string Host.InitForConfiguration(ref locationSubPath, out configPath, out locationConfigPath, configRoot, null, null, desiredConfigPath); } - private bool IsKnownConfigFile(string filename) + private static bool IsKnownConfigFile(string filename) { return string.Equals(filename, ConfigurationManagerInternalFactory.Instance.MachineConfigPath, StringComparison.OrdinalIgnoreCase) || diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationConverterBase.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationConverterBase.cs index 23cec43d17d62..d48fe45f0762e 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationConverterBase.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationConverterBase.cs @@ -17,7 +17,7 @@ public override bool CanConvertFrom(ITypeDescriptorContext ctx, Type type) return type == typeof(string); } - internal void ValidateType(object value, Type expected) + internal static void ValidateType(object value, Type expected) { if ((value != null) && (value.GetType() != expected)) throw new ArgumentException(SR.Format(SR.Converter_unsupported_value_type, expected.Name)); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs index 0cc7649687c80..c64e560b8e5a5 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs @@ -230,7 +230,7 @@ protected ContextInformation EvaluationContext public Configuration CurrentConfiguration => _configRecord?.CurrentConfiguration; - internal ConfigurationElement CreateElement(Type type) + internal static ConfigurationElement CreateElement(Type type) { ConfigurationElement element = (ConfigurationElement)TypeUtil.CreateInstance(type); element.CallInit(); @@ -1192,7 +1192,7 @@ protected internal virtual bool SerializeElement(XmlWriter writer, bool serializ return dataToWrite; } - private bool SerializeLockList(ConfigurationLockCollection list, string elementKey, XmlWriter writer) + private static bool SerializeLockList(ConfigurationLockCollection list, string elementKey, XmlWriter writer) { StringBuilder sb = new StringBuilder(); @@ -1727,7 +1727,7 @@ string key in PostDeserialize(); } - private object DeserializePropertyValue(ConfigurationProperty prop, XmlReader reader) + private static object DeserializePropertyValue(ConfigurationProperty prop, XmlReader reader) { Debug.Assert(prop != null, "prop != null"); Debug.Assert(reader != null, "reader != null"); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationProperty.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationProperty.cs index 7f4299b69f76c..472b2a8c76b84 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationProperty.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationProperty.cs @@ -260,7 +260,7 @@ private void ConstructorInit( } } - private void ValidatePropertyName(string name) + private static void ValidatePropertyName(string name) { if (string.IsNullOrEmpty(name)) throw new ArgumentException(SR.String_null_or_empty, nameof(name)); diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Internal/WriteFileContext.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Internal/WriteFileContext.cs index ae47e20cc90ca..30d9cadd1f9c9 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Internal/WriteFileContext.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/Internal/WriteFileContext.cs @@ -93,7 +93,7 @@ internal void Complete(string filename, bool success) // Copy all the files attributes that we care about from the source // file to the destination file - private void DuplicateFileAttributes(string source, string destination) + private static void DuplicateFileAttributes(string source, string destination) { DateTime creationTime; @@ -111,7 +111,7 @@ private void DuplicateFileAttributes(string source, string destination) // Copy over all the attributes you would want copied from a template file. // As of right now this is just acl's - private void DuplicateTemplateAttributes(string source, string destination) + private static void DuplicateTemplateAttributes(string source, string destination) { FileAttributes fileAttributes = File.GetAttributes(source); File.SetAttributes(destination, fileAttributes); @@ -128,7 +128,7 @@ private void DuplicateTemplateAttributes(string source, string destination) // 2) We are depending on the current behavior that if the file is locked // and we can not open it, that we will get an UnauthorizedAccessException // and not the IOException. - private void ValidateWriteAccess(string filename) + private static void ValidateWriteAccess(string filename) { FileStream fs = null; @@ -154,7 +154,7 @@ private void ValidateWriteAccess(string filename) /// /// Replace one file with another, retrying if locked. /// - private void ReplaceFile(string source, string target) + private static void ReplaceFile(string source, string target) { bool writeSucceeded; int duration = 0; @@ -181,7 +181,7 @@ private void ReplaceFile(string source, string target) } // Attempt to move a file from one location to another, overwriting if needed - private bool AttemptMove(string source, string target) + private static bool AttemptMove(string source, string target) { try { diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs index 65ca82cb5c3e2..09081d915eace 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/LocalFileSettingsProvider.cs @@ -87,9 +87,9 @@ public override SettingsPropertyValueCollection GetPropertyValues(SettingsContex string sectionName = GetSectionName(context); // Look for this section in both applicationSettingsGroup and userSettingsGroup - IDictionary appSettings = Store.ReadSettings(sectionName, false); - IDictionary userSettings = Store.ReadSettings(sectionName, true); - ConnectionStringSettingsCollection connStrings = Store.ReadConnectionStrings(); + IDictionary appSettings = ClientSettingsStore.ReadSettings(sectionName, false); + IDictionary userSettings = ClientSettingsStore.ReadSettings(sectionName, true); + ConnectionStringSettingsCollection connStrings = ClientSettingsStore.ReadConnectionStrings(); // Now map each SettingProperty to the right StoredSetting and deserialize the value if found. foreach (SettingsProperty setting in properties) @@ -209,12 +209,12 @@ public override void SetPropertyValues(SettingsContext context, SettingsProperty // declaration is necessary, it goes in the roaming config file in preference to the local config file. if (roamingUserSettings.Count > 0) { - Store.WriteSettings(sectionName, true, roamingUserSettings); + ClientSettingsStore.WriteSettings(sectionName, true, roamingUserSettings); } if (localUserSettings.Count > 0) { - Store.WriteSettings(sectionName, false, localUserSettings); + ClientSettingsStore.WriteSettings(sectionName, false, localUserSettings); } } @@ -227,8 +227,8 @@ public void Reset(SettingsContext context) string sectionName = GetSectionName(context); // First revert roaming, then local - Store.RevertToParent(sectionName, true); - Store.RevertToParent(sectionName, false); + ClientSettingsStore.RevertToParent(sectionName, true); + ClientSettingsStore.RevertToParent(sectionName, false); } /// @@ -372,7 +372,7 @@ private string GetPreviousConfigFileName(bool isRoaming) /// /// Gleans information from the SettingsContext and determines the name of the config section. /// - private string GetSectionName(SettingsContext context) + private static string GetSectionName(SettingsContext context) { string groupName = (string)context["GroupName"]; string key = (string)context["SettingsKey"]; @@ -438,7 +438,7 @@ private static bool IsRoamingSetting(SettingsProperty setting) /// ApplicationScopedSettingAttribute. This method determines whether this setting is user-scoped /// or not. It will throw if none or both of the attributes are present. /// - private bool IsUserSetting(SettingsProperty setting) + private static bool IsUserSetting(SettingsProperty setting) { bool isUser = setting.Attributes[typeof(UserScopedSettingAttribute)] is UserScopedSettingAttribute; bool isApp = setting.Attributes[typeof(ApplicationScopedSettingAttribute)] is ApplicationScopedSettingAttribute; 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 85031c95e5fc1..f9115aab76b4f 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs @@ -589,7 +589,7 @@ internal void ChangeConfigSource( // and contains no more or less than a single element. // // Throws a ConfigurationErrorsException if there is an error. - private void ValidateSectionXml(string xmlElement, string configKey) + private static void ValidateSectionXml(string xmlElement, string configKey) { if (string.IsNullOrEmpty(xmlElement)) return; @@ -1253,7 +1253,7 @@ private string GetUpdatedSectionDeclarationXml(FactoryRecord factoryRecord, Conf // // Take an ExeDefinition and translate it to a string // - private string ExeDefinitionToString(ConfigurationAllowExeDefinition allowDefinition) => + private static string ExeDefinitionToString(ConfigurationAllowExeDefinition allowDefinition) => allowDefinition switch { ConfigurationAllowExeDefinition.MachineOnly => AllowDefinitionMachineOnly, @@ -1463,7 +1463,7 @@ private SectionUpdates GetConfigDeclarationUpdates(ConfigurationSaveMode saveMod else return null; } - private bool AreLocationAttributesModified(SectionRecord sectionRecord, ConfigurationSection configSection) + private static bool AreLocationAttributesModified(SectionRecord sectionRecord, ConfigurationSection configSection) { OverrideModeSetting overrideMode = OverrideModeSetting.s_locationDefault; bool inheritInChildApplications = true; @@ -1485,7 +1485,7 @@ private bool AreLocationAttributesModified(SectionRecord sectionRecord, Configur || (inheritInChildApplications != configSection.SectionInformation.InheritInChildApplications); } - private bool AreSectionAttributesModified(SectionRecord sectionRecord, ConfigurationSection configSection) + private static bool AreSectionAttributesModified(SectionRecord sectionRecord, ConfigurationSection configSection) { string configSource; string protectionProviderName; @@ -1510,7 +1510,7 @@ private bool AreSectionAttributesModified(SectionRecord sectionRecord, Configura || AreLocationAttributesModified(sectionRecord, configSection); } - private bool IsConfigSectionMoved(SectionRecord sectionRecord, ConfigurationSection configSection) + private static bool IsConfigSectionMoved(SectionRecord sectionRecord, ConfigurationSection configSection) { if (!sectionRecord.HasFileInput) return true; @@ -1735,7 +1735,7 @@ private void GetConfigDefinitionUpdates( // Take an element name, and create an xml string that contains // that element in an empty state - private string WriteEmptyElement(string elementName) + private static string WriteEmptyElement(string elementName) { StringBuilder sb = new StringBuilder(); @@ -1836,7 +1836,6 @@ private void UpdateRecords() { SectionXmlInfo sectionXmlInfo = sectionRecord.FileInput.SectionXmlInfo; sectionXmlInfo.StreamVersion = ConfigStreamInfo.StreamVersion; - sectionXmlInfo.ConfigSourceStreamVersion = configSourceStreamVersion; } } else @@ -1874,7 +1873,6 @@ private void UpdateRecords() sectionXmlInfo.RawXml = null; sectionXmlInfo.ConfigSource = configSource; sectionXmlInfo.ConfigSourceStreamName = configSourceStreamName; - sectionXmlInfo.ConfigSourceStreamVersion = configSourceStreamVersion; sectionXmlInfo.ProtectionProviderName = configSection.SectionInformation.ProtectionProviderName; sectionXmlInfo.OverrideModeSetting = @@ -2157,7 +2155,7 @@ private bool WriteNewConfigDefinitionsRecursive(XmlUtilWriter utilWriter, Sectio return wroteASection; } - private void CheckPreamble(byte[] preamble, XmlUtilWriter utilWriter, byte[] buffer) + private static void CheckPreamble(byte[] preamble, XmlUtilWriter utilWriter, byte[] buffer) { bool hasByteOrderMark = false; using (Stream preambleStream = new MemoryStream(buffer)) @@ -2188,7 +2186,7 @@ private void CheckPreamble(byte[] preamble, XmlUtilWriter utilWriter, byte[] buf // // Calculate a new indent based on the position of the parent element and the current node. // - private int UpdateIndent(int oldIndent, XmlUtil xmlUtil, XmlUtilWriter utilWriter, int parentLinePosition) + private static int UpdateIndent(int oldIndent, XmlUtil xmlUtil, XmlUtilWriter utilWriter, int parentLinePosition) { int indent = oldIndent; if ((xmlUtil.Reader.NodeType == XmlNodeType.Element) && utilWriter.IsLastLineBlank) @@ -2962,7 +2960,7 @@ private bool CopyConfigDefinitionsRecursive( return wroteASection; } - private void WriteSectionUpdate(XmlUtilWriter utilWriter, DefinitionUpdate update, int linePosition, int indent, + private static void WriteSectionUpdate(XmlUtilWriter utilWriter, DefinitionUpdate update, int linePosition, int indent, bool skipFirstIndent) { ConfigurationSection configSection = (ConfigurationSection)update.SectionRecord.Result; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertySourceInfo.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertySourceInfo.cs index 7558081e4cf12..8f67051b4c572 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertySourceInfo.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/PropertySourceInfo.cs @@ -18,14 +18,14 @@ internal PropertySourceInfo(XmlReader reader) internal int LineNumber { get; } - private string GetFilename(XmlReader reader) + private static string GetFilename(XmlReader reader) { IConfigErrorInfo err = reader as IConfigErrorInfo; return err != null ? err.Filename : ""; } - private int GetLineNumber(XmlReader reader) + private static int GetLineNumber(XmlReader reader) { IConfigErrorInfo err = reader as IConfigErrorInfo; diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationSection.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationSection.cs index 9f70aa4162098..e3bd00fe8636b 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationSection.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/ProtectedConfigurationSection.cs @@ -61,7 +61,7 @@ internal ProtectedConfigurationProviderCollection GetAllProviders() return coll; } - private ProtectedConfigurationProvider CreateAndInitializeProviderWithAssert(Type t, ProviderSettings pn) + private static ProtectedConfigurationProvider CreateAndInitializeProviderWithAssert(Type t, ProviderSettings pn) { ProtectedConfigurationProvider provider = (ProtectedConfigurationProvider)TypeUtil.CreateInstance(t); @@ -74,7 +74,7 @@ private ProtectedConfigurationProvider CreateAndInitializeProviderWithAssert(Typ return provider; } - private ProtectedConfigurationProvider InstantiateProvider(ProviderSettings pn) + private static ProtectedConfigurationProvider InstantiateProvider(ProviderSettings pn) { Type t = TypeUtil.GetType(pn.Type, true); if (!typeof(ProtectedConfigurationProvider).IsAssignableFrom(t)) 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 6ffafeba5a0f7..a21c498d5d151 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionXmlInfo.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SectionXmlInfo.cs @@ -37,11 +37,6 @@ internal SectionXmlInfo( internal string ConfigSourceStreamName { get; set; } - internal object ConfigSourceStreamVersion - { - set { } - } - internal string ConfigKey { get; } internal string DefinitionConfigPath { get; } diff --git a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValue.cs b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValue.cs index 769c736f72c78..04804d5296cad 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValue.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/src/System/Configuration/SettingsPropertyValue.cs @@ -75,7 +75,7 @@ public object SerializedValue } } - private bool IsHostedInAspnet() + private static bool IsHostedInAspnet() { // See System.Web.Hosting.ApplicationManager::PopulateDomainBindings return AppDomain.CurrentDomain.GetData(".appDomain") != null; diff --git a/src/libraries/System.Console/src/System/ConsolePal.Unix.cs b/src/libraries/System.Console/src/System/ConsolePal.Unix.cs index 4619429733669..59f6b292ce81a 100644 --- a/src/libraries/System.Console/src/System/ConsolePal.Unix.cs +++ b/src/libraries/System.Console/src/System/ConsolePal.Unix.cs @@ -506,9 +506,9 @@ internal static bool TryGetCursorPosition(out int left, out int top, bool reinit StdInReader r = StdInReader.Inner; int escPos, bracketPos, semiPos, rPos; if (!AppendToStdInReaderUntil(Esc, r, readBytes, ref readBytesPos, out escPos) || - !BufferUntil((byte)'[', r, ref readBytes, ref readBytesPos, out bracketPos) || - !BufferUntil((byte)';', r, ref readBytes, ref readBytesPos, out semiPos) || - !BufferUntil((byte)'R', r, ref readBytes, ref readBytesPos, out rPos)) + !BufferUntil((byte)'[', ref readBytes, ref readBytesPos, out bracketPos) || + !BufferUntil((byte)';', ref readBytes, ref readBytesPos, out semiPos) || + !BufferUntil((byte)'R', ref readBytes, ref readBytesPos, out rPos)) { // We were unable to read everything from stdin, e.g. a timeout occurred. // Since we couldn't get the complete CPR, transfer any bytes we did read @@ -562,14 +562,14 @@ internal static bool TryGetCursorPosition(out int left, out int top, bool reinit s_firstCursorPositionRequest = false; } - static unsafe bool BufferUntil(byte toFind, StdInReader src, ref Span dst, ref int dstPos, out int foundPos) + static unsafe bool BufferUntil(byte toFind, ref Span dst, ref int dstPos, out int foundPos) { // Loop until we find the target byte. while (true) { // Read the next byte from stdin. byte b; - if (src.ReadStdin(&b, 1) != 1) + if (System.IO.StdInReader.ReadStdin(&b, 1) != 1) { foundPos = -1; return false; @@ -602,7 +602,7 @@ static unsafe bool AppendToStdInReaderUntil(byte toFind, StdInReader reader, Spa { // Read the next byte from stdin. byte b; - if (reader.ReadStdin(&b, 1) != 1) + if (System.IO.StdInReader.ReadStdin(&b, 1) != 1) { foundPos = -1; return false; diff --git a/src/libraries/System.Console/src/System/IO/StdInReader.cs b/src/libraries/System.Console/src/System/IO/StdInReader.cs index c5ba73ff740b3..3929dda532c32 100644 --- a/src/libraries/System.Console/src/System/IO/StdInReader.cs +++ b/src/libraries/System.Console/src/System/IO/StdInReader.cs @@ -74,7 +74,7 @@ internal void AppendExtraBuffer(ReadOnlySpan buffer) _endIndex += charLen; } - internal unsafe int ReadStdin(byte* buffer, int bufferSize) + internal static unsafe int ReadStdin(byte* buffer, int bufferSize) { int result = Interop.CheckIo(Interop.Sys.ReadStdin(buffer, bufferSize)); Debug.Assert(result >= 0 && result <= bufferSize); // may be 0 if hits EOL @@ -300,7 +300,7 @@ private static bool IsEol(char c) (c == ConsolePal.s_veolCharacter || c == ConsolePal.s_veol2Character || c == ConsolePal.s_veofCharacter); } - internal ConsoleKey GetKeyFromCharValue(char x, out bool isShift, out bool isCtrl) + internal static ConsoleKey GetKeyFromCharValue(char x, out bool isShift, out bool isCtrl) { isShift = false; isCtrl = false; @@ -492,6 +492,6 @@ private unsafe ConsoleKeyInfo ReadKey() } /// Gets whether there's input waiting on stdin. - internal bool StdinReady { get { return Interop.Sys.StdinReady(); } } + internal static bool StdinReady => Interop.Sys.StdinReady(); } } diff --git a/src/libraries/System.Console/src/System/IO/SyncTextReader.Unix.cs b/src/libraries/System.Console/src/System/IO/SyncTextReader.Unix.cs index b2e5d36d7a23a..ce6e55461e144 100644 --- a/src/libraries/System.Console/src/System/IO/SyncTextReader.Unix.cs +++ b/src/libraries/System.Console/src/System/IO/SyncTextReader.Unix.cs @@ -35,7 +35,7 @@ public bool KeyAvailable lock (this) { StdInReader r = Inner; - return !r.IsUnprocessedBufferEmpty() || r.StdinReady; + return !r.IsUnprocessedBufferEmpty() || StdInReader.StdinReady; } } } diff --git a/src/libraries/System.Data.Common/src/System/Data/BaseCollection.cs b/src/libraries/System.Data.Common/src/System/Data/BaseCollection.cs index 942a2ac579112..1b02adb894baf 100644 --- a/src/libraries/System.Data.Common/src/System/Data/BaseCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/BaseCollection.cs @@ -34,7 +34,7 @@ public class InternalDataCollectionBase : ICollection // > 0 (1) : CaseSensitve equal // < 0 (-1) : Case-Insensitive Equal // = 0 : Not Equal - internal int NamesEqual(string? s1, string? s2, bool fCaseSensitive, CultureInfo locale) + internal static int NamesEqual(string? s1, string? s2, bool fCaseSensitive, CultureInfo locale) { if (fCaseSensitive) { 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 827f442ab2c1e..756ca270b413f 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 @@ -1366,7 +1366,7 @@ internal DbCommand GetDeleteCommand(DataRow? dataRow, bool useColumnsForParamete } [return: NotNullIfNotNull("column")] - private object? GetColumnValue(DataRow row, DataColumn? column, DataRowVersion version) + private static object? GetColumnValue(DataRow row, DataColumn? column, DataRowVersion version) { object? value = null; if (null != column) @@ -1404,13 +1404,13 @@ private static DbParameter GetNextParameter(DbCommand command, int pcount) return p; } - private bool IncludeInInsertValues(DbSchemaRow row) + private static bool IncludeInInsertValues(DbSchemaRow row) { // NOTE: Include ignore condition - i.e. ignore if 'row' is IsReadOnly else include return (!row.IsAutoIncrement && !row.IsHidden && !row.IsExpression && !row.IsRowVersion && !row.IsReadOnly); } - private bool IncludeInUpdateSet(DbSchemaRow row) + private static bool IncludeInUpdateSet(DbSchemaRow row) { // NOTE: Include ignore condition - i.e. ignore if 'row' is IsReadOnly else include return (!row.IsAutoIncrement && !row.IsRowVersion && !row.IsHidden && !row.IsReadOnly); diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataAdapter.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataAdapter.cs index a4e5e4956da3b..3e310f72e9ae4 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataAdapter.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataAdapter.cs @@ -31,7 +31,7 @@ public class DataAdapter : Component, IDataAdapter internal readonly int _objectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount); [Conditional("DEBUG")] - private void AssertReaderHandleFieldCount(DataReaderContainer readerHandler) + private static void AssertReaderHandleFieldCount(DataReaderContainer readerHandler) { #if DEBUG Debug.Assert(readerHandler.FieldCount > 0, "Scenario expects non-empty results but no fields reported by reader"); diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMappingCollection.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMappingCollection.cs index a929eb679faf6..77d621c7cff1e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMappingCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataColumnMappingCollection.cs @@ -81,7 +81,7 @@ public int Count } } - private Type ItemType + private static Type ItemType { get { return typeof(DataColumnMapping); } } @@ -385,7 +385,7 @@ private void Replace(int index, DataColumnMapping newValue) _items[index] = newValue; } - private void ValidateType([NotNull] object? value) + private static void ValidateType([NotNull] object? value) { if (null == value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMappingCollection.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMappingCollection.cs index 46e2fbbc51880..51aa38f260b8e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMappingCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DataTableMappingCollection.cs @@ -54,7 +54,7 @@ ITableMapping ITableMappingCollection.GetByDataSetTable(string dataSetTableName) [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int Count => (null != _items) ? _items.Count : 0; - private Type ItemType => typeof(DataTableMapping); + private static Type ItemType => typeof(DataTableMapping); [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] @@ -321,7 +321,7 @@ private void Replace(int index, DataTableMapping newValue) _items[index] = newValue; } - private void ValidateType([NotNull] object? value) + private static void ValidateType([NotNull] object? value) { if (null == value) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs index c25c75a80c877..8e04dc150ca14 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbConnectionStringBuilder.cs @@ -336,7 +336,7 @@ IDictionaryEnumerator IDictionary.GetEnumerator() return Dictionary.GetEnumerator(); } - private string ObjectToString(object keyword) + private static string ObjectToString(object keyword) { try { @@ -384,7 +384,7 @@ public virtual bool TryGetValue(string keyword, [NotNullWhen(true)] out object? return CurrentValues.TryGetValue(keyword, out value); } - internal Attribute[] GetAttributesFromCollection(AttributeCollection collection) + internal static Attribute[] GetAttributesFromCollection(AttributeCollection collection) { Attribute[] attributes = new Attribute[collection.Count]; collection.CopyTo(attributes, 0); 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 1c202420c6fa0..72163f26113a6 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 @@ -249,7 +249,7 @@ private void CloneFrom(DbDataAdapter from) _IDbDataAdapter.DeleteCommand = CloneCommand(pfrom.DeleteCommand); } - private IDbCommand? CloneCommand(IDbCommand? command) + private static IDbCommand? CloneCommand(IDbCommand? command) { return (IDbCommand?)((command is ICloneable) ? ((ICloneable)command).Clone() : null); } @@ -783,7 +783,7 @@ private void ParameterInput(IDataParameterCollection parameters, StatementType t } } - private void ParameterOutput(IDataParameter parameter, DataRow row, DataTableMapping mappings, MissingMappingAction missingMapping, MissingSchemaAction missingSchema) + private static void ParameterOutput(IDataParameter parameter, DataRow row, DataTableMapping mappings, MissingMappingAction missingMapping, MissingSchemaAction missingSchema) { if (0 != (ParameterDirection.Output & parameter.Direction)) { @@ -1460,7 +1460,7 @@ private void UpdateBatchExecute(BatchCommandInfo[] batchCommands, int commandCou } } - private ConnectionState UpdateConnectionOpen(IDbConnection connection, StatementType statementType, IDbConnection?[] connections, ConnectionState[] connectionStates, bool useSelectConnectionState) + private static ConnectionState UpdateConnectionOpen(IDbConnection connection, StatementType statementType, IDbConnection?[] connections, ConnectionState[] connectionStates, bool useSelectConnectionState) { Debug.Assert(null != connection, "unexpected null connection"); int index = (int)statementType; @@ -1704,7 +1704,7 @@ private int UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCom return affected; // return the count of successful rows within the batch failure } - private int UpdatedRowStatusSkip(BatchCommandInfo[] batchCommands, int commandCount) + private static int UpdatedRowStatusSkip(BatchCommandInfo[] batchCommands, int commandCount) { Debug.Assert(null != batchCommands, "null batchCommands?"); diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs index 0aa98075f3764..3e8d0b3aa9dcc 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs @@ -183,7 +183,7 @@ public override object Get(int recordNo) return _nullValue; } - private Families GetFamily(Type dataType) + private static Families GetFamily(Type dataType) { switch (Type.GetTypeCode(dataType)) { diff --git a/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs b/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs index 275c652b3ee82..2efbd4faacaca 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ConstraintCollection.cs @@ -247,7 +247,7 @@ private void AddForeignKeyConstraint(ForeignKeyConstraint constraint) constraint.CheckCanAddToCollection(this); } - private bool AutoGenerated(Constraint constraint) + private static bool AutoGenerated(Constraint constraint) { ForeignKeyConstraint? fk = (constraint as ForeignKeyConstraint); if (null != fk) @@ -641,7 +641,7 @@ internal int InternalIndexOf(string? constraintName) /// /// Makes a default name with the given index. e.g. Constraint1, Constraint2, ... Constrainti /// - private string MakeName(int index) + private static string MakeName(int index) { if (1 == index) { 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 5d98ebf62ef9d..a0650ddaad80d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataColumn.cs @@ -1383,7 +1383,7 @@ public virtual MappingType ColumnMapping internal void CheckColumnConstraint(DataRow row, DataRowAction action) { - if (_table!.UpdatingCurrent(row, action)) + if (DataTable.UpdatingCurrent(row, action)) { CheckNullable(row); CheckMaxLength(row); @@ -1639,14 +1639,14 @@ internal static bool IsAutoIncrementType(Type dataType) => dataType == typeof(SqlInt16) || dataType == typeof(SqlDecimal); - private bool IsColumnMappingValid(StorageType typeCode, MappingType mapping) => + private static bool IsColumnMappingValid(StorageType typeCode, MappingType mapping) => !((mapping != MappingType.Element) && DataStorage.IsTypeCustomType(typeCode)); internal bool IsCustomType => _storage != null ? _storage._isCustomDefinedType : DataStorage.IsTypeCustomType(DataType); - internal bool IsValueCustomTypeInstance(object value) => + internal static bool IsValueCustomTypeInstance(object value) => // if instance is not a storage supported type (built in or SQL types) (DataStorage.IsTypeCustomType(value.GetType()) && !(value is Type)); @@ -1783,8 +1783,6 @@ internal void SetCapacity(int capacity) private bool ShouldSerializeDefaultValue() => !DefaultValueIsNull; - internal void OnSetDataSet() { } - // Returns the of the column, if one exists. public override string ToString() => _expression == null ? ColumnName : diff --git a/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs b/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs index 252b84fa2efaa..15707b9c2ce27 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataColumnCollection.cs @@ -359,11 +359,6 @@ private void BaseAdd([NotNull] DataColumn? column) { column.InitializeRecord(record); } - - if (_table.DataSet != null) - { - column.OnSetDataSet(); - } } catch (Exception e) when (ADP.IsCatchableOrSecurityExceptionType(e)) { @@ -769,7 +764,7 @@ internal void FinishInitCollection() /// /// Makes a default name with the given index. e.g. Column1, Column2, ... Columni /// - private string MakeName(int index) => index == 1 ? + private static string MakeName(int index) => index == 1 ? "Column1" : "Column" + index.ToString(System.Globalization.CultureInfo.InvariantCulture); diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs b/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs index 31ea724027437..bd843f925ae7c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRelation.cs @@ -291,15 +291,15 @@ internal void SetParentRowRecords(DataRow childRow, DataRow parentRow) object[] parentKeyValues = parentRow.GetKeyValues(ParentKey); if (childRow._tempRecord != -1) { - ChildTable._recordManager.SetKeyValues(childRow._tempRecord, ChildKey, parentKeyValues); + RecordManager.SetKeyValues(childRow._tempRecord, ChildKey, parentKeyValues); } if (childRow._newRecord != -1) { - ChildTable._recordManager.SetKeyValues(childRow._newRecord, ChildKey, parentKeyValues); + RecordManager.SetKeyValues(childRow._newRecord, ChildKey, parentKeyValues); } if (childRow._oldRecord != -1) { - ChildTable._recordManager.SetKeyValues(childRow._oldRecord, ChildKey, parentKeyValues); + RecordManager.SetKeyValues(childRow._oldRecord, ChildKey, parentKeyValues); } } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataRelationCollection.cs b/src/libraries/System.Data.Common/src/System/Data/DataRelationCollection.cs index 7738305236ee7..845d591823ad8 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataRelationCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataRelationCollection.cs @@ -362,7 +362,7 @@ internal int InternalIndexOf(string? name) /// /// Makes a default name with the given index. e.g. Relation1, Relation2, ... Relationi /// - private string MakeName(int index) => index == 1 ? + private static string MakeName(int index) => index == 1 ? "Relation1" : "Relation" + index.ToString(System.Globalization.CultureInfo.InvariantCulture); 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 b7727306d8d9b..d86ecab3d3755 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs @@ -1240,7 +1240,7 @@ public DataSet Copy() foreach (DataRow row in table.Rows) { - table.CopyRow(destTable, row); + DataTable.CopyRow(destTable, row); } } @@ -1347,7 +1347,7 @@ internal bool this[int index] // Loop through the rows. if (bitMatrix[i][j]) { - table.CopyRow(destTable, table.Rows[j]); + DataTable.CopyRow(destTable, table.Rows[j]); bitMatrix[i].HasChanges--; } } @@ -1428,7 +1428,7 @@ private void MarkRelatedRowsAsModified(TableChanges[] bitMatrix, DataRow row) IList IListSource.GetList() => DefaultViewManager; [RequiresUnreferencedCode(RequiresUnreferencedCodeMessage)] - internal string GetRemotingDiffGram(DataTable table) + internal static string GetRemotingDiffGram(DataTable table) { StringWriter strWriter = new StringWriter(CultureInfo.InvariantCulture); XmlTextWriter writer = new XmlTextWriter(strWriter); @@ -1750,7 +1750,7 @@ internal void ReadXmlSchema(XmlReader? reader, bool denyResolving) } } - internal bool MoveToElement(XmlReader reader, int depth) + internal static bool MoveToElement(XmlReader reader, int depth) { while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement && reader.NodeType != XmlNodeType.Element && reader.Depth > depth) { @@ -1766,7 +1766,7 @@ private static void MoveToElement(XmlReader reader) reader.Read(); } } - internal void ReadEndElement(XmlReader reader) + internal static void ReadEndElement(XmlReader reader) { while (reader.NodeType == XmlNodeType.Whitespace) { @@ -2942,7 +2942,7 @@ public void WriteXml(string fileName, XmlWriteMode mode) /// Gets the collection of parent relations which belong to a /// specified table. /// - internal DataRelationCollection GetParentRelations(DataTable table) => table.ParentRelations; + internal static DataRelationCollection GetParentRelations(DataTable table) => table.ParentRelations; /// /// Merges this into a specified . 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 0821109b5a408..d250bdf215af0 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs @@ -279,7 +279,7 @@ private void SerializeDataTable(SerializationInfo info, StreamingContext context } info.AddValue(KEY_XMLSCHEMA, _dataSet!.GetXmlSchemaForRemoting(this)); - info.AddValue(KEY_XMLDIFFGRAM, _dataSet.GetRemotingDiffGram(this)); + info.AddValue(KEY_XMLDIFFGRAM, DataSet.GetRemotingDiffGram(this)); if (fCreatedDataSet) { @@ -854,7 +854,7 @@ internal void DeserializeTableData(SerializationInfo info, StreamingContext cont } // Constructs the RowState from the two bits in the bitarray. - private DataRowState ConvertToRowState(BitArray bitStates, int bitIndex) + private static DataRowState ConvertToRowState(BitArray bitStates, int bitIndex) { Debug.Assert(bitStates != null); Debug.Assert(bitStates.Length > bitIndex); @@ -1214,13 +1214,6 @@ internal void SetDataSet(DataSet? dataSet) { _dataSet = dataSet; - // Inform all the columns of the dataset being set. - DataColumnCollection cols = Columns; - for (int i = 0; i < cols.Count; i++) - { - cols[i].OnSetDataSet(); - } - if (DataSet != null) { _defaultView = null; @@ -2124,7 +2117,7 @@ internal decimal MinOccurs set { _minOccurs = value; } } - internal void SetKeyValues(DataKey key, object[] keyValues, int record) + internal static void SetKeyValues(DataKey key, object[] keyValues, int record) { for (int i = 0; i < keyValues.Length; i++) { @@ -2349,7 +2342,7 @@ internal DataTable Clone(DataSet? cloneDS) } } - private DataTable IncrementalCloneTo(DataTable sourceTable, DataTable targetTable) + private static DataTable IncrementalCloneTo(DataTable sourceTable, DataTable targetTable) { foreach (DataColumn dc in sourceTable.Columns) { @@ -2829,7 +2822,7 @@ internal void InsertRow(DataRow row, long proposedID, int pos, bool fireEvent) } } - internal void CheckNotModifying(DataRow row) + internal static void CheckNotModifying(DataRow row) { if (row._tempRecord != -1) { @@ -2984,7 +2977,7 @@ public object Compute(string? expression, string? filter) bool IListSource.ContainsListCollection => false; - internal void CopyRow(DataTable table, DataRow row) + internal static void CopyRow(DataTable table, DataRow row) { int oldRecord = -1, newRecord = -1; @@ -3075,7 +3068,7 @@ private void CheckPrimaryKey() return _recordManager[index.GetRecord(range.Min)]; } - internal string FormatSortString(IndexField[] indexDesc) + internal static string FormatSortString(IndexField[] indexDesc) { var builder = new StringBuilder(); foreach (IndexField field in indexDesc) @@ -3377,7 +3370,7 @@ internal void InsertRow(DataRow row, long proposedID) } } - private IndexField[] NewIndexDesc(DataKey key) + private static IndexField[] NewIndexDesc(DataKey key) { Debug.Assert(key.HasValue); IndexField[] indexDesc = key.GetIndexDesc(); @@ -3933,7 +3926,7 @@ internal int[] InsertRecordToIndexes(DataRow row, DataRowVersion version) return positionIndexes; } - internal void SilentlySetValue(DataRow dr, DataColumn dc, DataRowVersion version, object newValue) + internal static void SilentlySetValue(DataRow dr, DataColumn dc, DataRowVersion version, object newValue) { // get record for version int record = dr.GetRecordFromVersion(version); @@ -4845,7 +4838,7 @@ internal DataRow UpdatingAdd(object?[] values) return Rows.Add(values); } - internal bool UpdatingCurrent(DataRow row, DataRowAction action) + internal static bool UpdatingCurrent(DataRow row, DataRowAction action) { return (action == DataRowAction.Add || action == DataRowAction.Change || action == DataRowAction.Rollback || action == DataRowAction.ChangeOriginal || @@ -5537,7 +5530,7 @@ private bool CheckForClosureOnExpressions(DataTable dt, bool writeHierarchy) return CheckForClosureOnExpressionTables(tableList); } - private bool CheckForClosureOnExpressionTables(List tableList) + private static bool CheckForClosureOnExpressionTables(List tableList) { Debug.Assert(tableList != null, "tableList shouldnot be null"); @@ -6272,7 +6265,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol } } - internal void ReadEndElement(XmlReader reader) + internal static void ReadEndElement(XmlReader reader) { while (reader.NodeType == XmlNodeType.Whitespace) { @@ -6287,14 +6280,14 @@ internal void ReadEndElement(XmlReader reader) reader.ReadEndElement(); } } - internal void ReadXDRSchema(XmlReader reader) + internal static void ReadXDRSchema(XmlReader reader) { XmlDocument xdoc = new XmlDocument(); // we may need this to infer the schema xdoc.ReadNode(reader); //consume and ignore it - No support } - internal bool MoveToElement(XmlReader reader, int depth) + internal static bool MoveToElement(XmlReader reader, int depth) { while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement && reader.NodeType != XmlNodeType.Element && reader.Depth > depth) { @@ -6668,7 +6661,7 @@ private void CreateTableList(DataTable currentTable, List tableList) } } } - private void CreateRelationList(List tableList, List relationList) + private static void CreateRelationList(List tableList, List relationList) { foreach (DataTable table in tableList) { diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTableCollection.cs b/src/libraries/System.Data.Common/src/System/Data/DataTableCollection.cs index 0dc5aa0510d6d..282456d6d7304 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTableCollection.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTableCollection.cs @@ -701,7 +701,7 @@ internal void FinishInitCollection() /// /// Makes a default name with the given index. e.g. Table1, Table2, ... Tablei /// - private string MakeName(int index) => 1 == index ? + private static string MakeName(int index) => 1 == index ? "Table1" : "Table" + index.ToString(System.Globalization.CultureInfo.InvariantCulture); 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 6f9793333c506..eed5320ae7649 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataView.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataView.cs @@ -425,7 +425,7 @@ public string Sort { if (_sort.Length == 0 && _applyDefaultSort && _table != null && _table._primaryIndex.Length > 0) { - return _table.FormatSortString(_table._primaryIndex); + return DataTable.FormatSortString(_table._primaryIndex); } else { @@ -1110,7 +1110,7 @@ void IBindingListView.ApplySort(ListSortDescriptionCollection sorts) Sort = sortString.ToString(); // what if we dont have any valid sort criteira? we would reset the sort } - private string CreateSortString(PropertyDescriptor property, ListSortDirection direction) + private static string CreateSortString(PropertyDescriptor property, ListSortDirection direction) { Debug.Assert(property != null, "property is null"); StringBuilder resultString = new StringBuilder(); @@ -1754,7 +1754,7 @@ public DataTable ToTable(string? tableName, bool distinct, params string[] colum return dt; } - private bool RowExist(List arraylist, object[] objectArray) + private static bool RowExist(List arraylist, object[] objectArray) { for (int i = 0; i < arraylist.Count; i++) { 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 0919dc0361394..6ace6e1629b39 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 @@ -133,7 +133,7 @@ internal override ExpressionNode Optimize() return this; } - internal void SetTypeMismatchError(int op, Type left, Type right) + internal static void SetTypeMismatchError(int op, Type left, Type right) { throw ExprException.TypeMismatchInBinop(op, left, right); } @@ -1180,7 +1180,7 @@ private enum DataTypePrecedence SqlBinary = -10, } - private DataTypePrecedence GetPrecedence(StorageType storageType) + private static DataTypePrecedence GetPrecedence(StorageType storageType) { switch (storageType) { @@ -1268,19 +1268,19 @@ private static StorageType GetPrecedenceType(DataTypePrecedence code) } } - private bool IsMixed(StorageType left, StorageType right) + private static bool IsMixed(StorageType left, StorageType right) { return ((IsSigned(left) && IsUnsigned(right)) || (IsUnsigned(left) && IsSigned(right))); } - private bool IsMixedSql(StorageType left, StorageType right) + private static bool IsMixedSql(StorageType left, StorageType right) { return ((IsSignedSql(left) && IsUnsignedSql(right)) || (IsUnsignedSql(left) && IsSignedSql(right))); } - internal StorageType ResultType(StorageType left, StorageType right, bool lc, bool rc, int op) + internal static StorageType ResultType(StorageType left, StorageType right, bool lc, bool rc, int op) { if ((left == StorageType.Guid) && (right == StorageType.Guid) && Operators.IsRelational(op)) return left; @@ -1370,7 +1370,7 @@ internal StorageType ResultType(StorageType left, StorageType right, bool lc, bo return result; } - internal StorageType ResultSqlType(StorageType left, StorageType right, bool lc, bool rc, int op) + internal static StorageType ResultSqlType(StorageType left, StorageType right, bool lc, bool rc, int op) { int leftPrecedence = (int)GetPrecedence(left); if (leftPrecedence == (int)DataTypePrecedence.Error) @@ -1483,7 +1483,7 @@ internal StorageType ResultSqlType(StorageType left, StorageType right, bool lc, return result; } - private int SqlResultType(int typeCode) + private static int SqlResultType(int typeCode) { switch (typeCode) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/ConstNode.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/ConstNode.cs index 308352fe6dbfc..5a8f16bf62030 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/ConstNode.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/ConstNode.cs @@ -111,7 +111,7 @@ internal override ExpressionNode Optimize() return this; } - private object SmallestDecimal(object constant) + private static object SmallestDecimal(object constant) { if (null == constant) { @@ -185,7 +185,7 @@ private object SmallestDecimal(object constant) return constant; } - private object SmallestNumeric(object constant) + private static object SmallestNumeric(object constant) { if (null == constant) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionParser.cs b/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionParser.cs index 5972b3d3c4357..b9adf16a274ba 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionParser.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Filter/ExpressionParser.cs @@ -1191,7 +1191,7 @@ private void ScanWhite() /// is the character a whitespace character? /// Consider using CharacterInfo().IsWhiteSpace(ch) (System.Globalization) /// - private bool IsWhiteSpace(char ch) + private static bool IsWhiteSpace(char ch) { return ch <= 32 && ch != '\0'; } @@ -1199,7 +1199,7 @@ private bool IsWhiteSpace(char ch) /// /// is the character an alphanumeric? /// - private bool IsAlphaNumeric(char ch) + private static bool IsAlphaNumeric(char ch) { //single comparison switch (ch) @@ -1277,7 +1277,7 @@ private bool IsAlphaNumeric(char ch) } } - private bool IsDigit(char ch) + private static bool IsDigit(char ch) { //single comparison switch (ch) @@ -1301,7 +1301,7 @@ private bool IsDigit(char ch) /// /// is the character an alpha? /// - private bool IsAlpha(char ch) + private static bool IsAlpha(char ch) { //single comparison switch (ch) diff --git a/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs b/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs index 1513b767d212b..9a48bfb9df326 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ForeignKeyConstraint.cs @@ -156,7 +156,7 @@ internal override void CheckCanAddToCollection(ConstraintCollection constraints) internal override bool CanBeRemovedFromCollection(ConstraintCollection constraints, bool fThrowException) => true; - internal bool IsKeyNull(object[] values) + internal static bool IsKeyNull(object[] values) { for (int i = 0; i < values.Length; i++) { @@ -581,7 +581,7 @@ internal override void CheckConstraint(DataRow childRow, DataRowAction action) object[] parentKeyValues = parentRow.GetKeyValues(_parentKey, action == DataRowAction.Rollback ? version : DataRowVersion.Default); int parentKeyValuesRecord = childRow.Table.NewRecord(); - childRow.Table.SetKeyValues(_childKey, parentKeyValues, parentKeyValuesRecord); + DataTable.SetKeyValues(_childKey, parentKeyValues, parentKeyValuesRecord); if (_childKey.RecordsEqual(childRow._tempRecord, parentKeyValuesRecord)) { return; diff --git a/src/libraries/System.Data.Common/src/System/Data/Merger.cs b/src/libraries/System.Data.Common/src/System/Data/Merger.cs index 109e2119790d8..36d3e682774c7 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Merger.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Merger.cs @@ -632,7 +632,7 @@ private void MergeExtendedProperties(PropertyCollection src, PropertyCollection } } - private DataKey GetSrcKey(DataTable src, DataTable dst) + private static DataKey GetSrcKey(DataTable src, DataTable dst) { if (src._primaryKey != null) { diff --git a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs index 97fd18c9ae152..b47462cd04d09 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/SchemaMapping.cs @@ -497,7 +497,7 @@ internal int LoadDataRowChapters(DataRow dataRow) return datarowadded; } - private int[] CreateIndexMap(int count, int index) + private static int[] CreateIndexMap(int count, int index) { int[] values = new int[count]; for (int i = 0; i < index; ++i) @@ -518,7 +518,7 @@ private static string[] GenerateFieldNames(DataReaderContainer dataReader) return fieldNames; } - private DataColumn[] ResizeColumnArray(DataColumn[] rgcol, int len) + private static DataColumn[] ResizeColumnArray(DataColumn[] rgcol, int len) { Debug.Assert(rgcol != null, "invalid call to ResizeArray"); Debug.Assert(len <= rgcol.Length, "invalid len passed to ResizeArray"); @@ -527,7 +527,7 @@ private DataColumn[] ResizeColumnArray(DataColumn[] rgcol, int len) return tmp; } - private void AddItemToAllowRollback(ref List? items, object value) + private static void AddItemToAllowRollback(ref List? items, object value) { if (null == items) { @@ -536,7 +536,7 @@ private void AddItemToAllowRollback(ref List? items, object value) items.Add(value); } - private void RollbackAddedItems(List? items) + private static void RollbackAddedItems(List? items) { if (null != items) { @@ -1147,7 +1147,7 @@ private void RollbackAddedItems(List? items) } [RequiresUnreferencedCode("Members from types used in the expression column may be trimmed if not referenced directly.")] - private void AddAdditionalProperties(DataColumn targetColumn, DataRow schemaRow) + private static void AddAdditionalProperties(DataColumn targetColumn, DataRow schemaRow) { DataColumnCollection columns = schemaRow.Table.Columns; DataColumn? column; diff --git a/src/libraries/System.Data.Common/src/System/Data/RecordManager.cs b/src/libraries/System.Data.Common/src/System/Data/RecordManager.cs index 585c6c248976d..6bef3843fbd60 100644 --- a/src/libraries/System.Data.Common/src/System/Data/RecordManager.cs +++ b/src/libraries/System.Data.Common/src/System/Data/RecordManager.cs @@ -79,7 +79,7 @@ internal static int NewCapacity(int capacity) => (capacity < 128) ? 128 : (capacity + capacity); // Normalization: 64, 256, 1024, 2k, 3k, .... - private int NormalizedMinimumCapacity(int capacity) + private static int NormalizedMinimumCapacity(int capacity) { if (capacity < 1024 - 10) { @@ -192,7 +192,7 @@ internal DataRow this[int record] } } - internal void SetKeyValues(int record, DataKey key, object[] keyValues) + internal static void SetKeyValues(int record, DataKey key, object[] keyValues) { for (int i = 0; i < keyValues.Length; i++) { diff --git a/src/libraries/System.Data.Common/src/System/Data/RelatedView.cs b/src/libraries/System.Data.Common/src/System/Data/RelatedView.cs index ea986ce943d0c..a5b62e2ae7849 100644 --- a/src/libraries/System.Data.Common/src/System/Data/RelatedView.cs +++ b/src/libraries/System.Data.Common/src/System/Data/RelatedView.cs @@ -118,7 +118,7 @@ public override bool Equals([NotNullWhen(true)] DataView? dv) } } - private bool CompareArray(object?[]? value1, object?[]? value2) + private static bool CompareArray(object?[]? value1, object?[]? value2) { if (value1 == null || value2 == null) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs index 336639fbf0e5b..138a7685ca08d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs @@ -1908,7 +1908,7 @@ private bool FGt10_38() (_data3 == 0x5a86c47aL) && (_data2 >= 0x098a2240L)); } - private bool FGt10_38(Span rglData) + private static bool FGt10_38(Span rglData) { Debug.Assert(rglData.Length == 4, "rglData.Length == 4", $"Wrong array length: {rglData.Length}"); diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs index 8c6726a6dbe24..90402cfc33e78 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs @@ -187,7 +187,7 @@ private void SetNull() _firstCreateReader = true; } - private Stream CreateMemoryStreamFromXmlReader(XmlReader reader) + private static Stream CreateMemoryStreamFromXmlReader(XmlReader reader) { XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.CloseOutput = false; // don't close the memory stream diff --git a/src/libraries/System.Data.Common/src/System/Data/Select.cs b/src/libraries/System.Data.Common/src/System/Data/Select.cs index 06f22adc9765a..3cf89bb11a9a5 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Select.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Select.cs @@ -49,7 +49,7 @@ public Select(DataTable table, string? filterExpression, string? sort, DataViewR _recordStates = recordStates; } - private bool IsSupportedOperator(int op) + private static bool IsSupportedOperator(int op) { return ((op >= Operators.EqualTo && op <= Operators.LessOrEqual) || op == Operators.Is || op == Operators.IsNot); } @@ -676,15 +676,15 @@ private int Eval(BinaryNode expr, DataRow row, DataRowVersion version) StorageType resultType; if (expr._left.IsSqlColumn || expr._right.IsSqlColumn) { - resultType = expr.ResultSqlType(leftType, rightType, isLConst, isRConst, expr._op); + resultType = BinaryNode.ResultSqlType(leftType, rightType, isLConst, isRConst, expr._op); } else { - resultType = expr.ResultType(leftType, rightType, isLConst, isRConst, expr._op); + resultType = BinaryNode.ResultType(leftType, rightType, isLConst, isRConst, expr._op); } if (StorageType.Empty == resultType) { - expr.SetTypeMismatchError(expr._op, vLeft.GetType(), vRight.GetType()); + BinaryNode.SetTypeMismatchError(expr._op, vLeft.GetType(), vRight.GetType()); } // if comparing a Guid column value against a string literal diff --git a/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs b/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs index 4b13c79f5eba7..655256d8e3fbd 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs @@ -213,7 +213,7 @@ public string? SimpleTypeQualifiedName } } - internal string QualifiedName(string name) + internal static string QualifiedName(string name) { if (!name.Contains(':')) return Keywords.XSD_PREFIXCOLON + name; diff --git a/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs b/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs index 37cd34e6f79e3..3277cf0e00a08 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XDRSchema.cs @@ -65,7 +65,7 @@ internal void LoadSchema(XmlElement schemaRoot, DataSet ds) ds.DataSetName = _schemaName; } - internal XmlElement? FindTypeNode(XmlElement node) + internal static XmlElement? FindTypeNode(XmlElement node) { string strType; XmlNode? vn; @@ -128,7 +128,7 @@ internal void LoadSchema(XmlElement schemaRoot, DataSet ds) return null; } - internal bool IsTextOnlyContent(XmlElement node) + internal static bool IsTextOnlyContent(XmlElement node) { Debug.Assert(FEqualIdentity(node, Keywords.XDR_ELEMENTTYPE, Keywords.XDRNS), $"Invalid node type {node.LocalName}"); @@ -151,7 +151,7 @@ internal bool IsTextOnlyContent(XmlElement node) throw ExceptionBuilder.InvalidAttributeValue("content", value); } - internal bool IsXDRField(XmlElement node, XmlElement typeNode) + internal static bool IsXDRField(XmlElement node, XmlElement typeNode) { int min = 1; int max = 1; @@ -294,7 +294,7 @@ private static NameType FindNameType(string name) private static readonly NameType s_enumerationNameType = FindNameType("enumeration"); [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] - private Type ParseDataType(string dt, string dtValues) + private static Type ParseDataType(string dt, string dtValues) { string strType = dt; string[] parts = dt.Split(':'); @@ -315,7 +315,7 @@ private Type ParseDataType(string dt, string dtValues) return nt.type; } - internal string GetInstanceName(XmlElement node) + internal static string GetInstanceName(XmlElement node) { string instanceName; @@ -490,12 +490,12 @@ internal void HandleColumn(XmlElement node, DataTable table) } } - internal void GetMinMax(XmlElement elNode, ref int minOccurs, ref int maxOccurs) + internal static void GetMinMax(XmlElement elNode, ref int minOccurs, ref int maxOccurs) { GetMinMax(elNode, false, ref minOccurs, ref maxOccurs); } - internal void GetMinMax(XmlElement elNode, bool isAttribute, ref int minOccurs, ref int maxOccurs) + internal static void GetMinMax(XmlElement elNode, bool isAttribute, ref int minOccurs, ref int maxOccurs) { string occurs = elNode.GetAttribute(Keywords.MINOCCURS); if (occurs != null && occurs.Length > 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 2ab54d821686e..cab47a7f1d10a 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XMLDiffLoader.cs @@ -175,7 +175,7 @@ internal void ProcessDiffs(ArrayList tableList, XmlReader ssync) } [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - internal void ProcessErrors(DataSet ds, XmlReader ssync) + internal static void ProcessErrors(DataSet ds, XmlReader ssync) { DataTable? table; @@ -449,7 +449,7 @@ private int ReadOldRowData(DataSet? ds, ref DataTable? table, ref int pos, XmlRe return record; } - internal void SkipWhitespaces(XmlReader reader) + internal static void SkipWhitespaces(XmlReader reader) { while (reader.NodeType == XmlNodeType.Whitespace || reader.NodeType == XmlNodeType.SignificantWhitespace) { 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 20e3c2140ba8a..30cb3539bf8ff 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XMLSchema.cs @@ -513,7 +513,7 @@ internal void HandleRelation(XmlElement node, bool fNested) } } - private bool HasAttributes(XmlSchemaObjectCollection attributes) + private static bool HasAttributes(XmlSchemaObjectCollection attributes) { foreach (XmlSchemaObject so in attributes) { @@ -574,7 +574,7 @@ private bool IsDatasetParticle(XmlSchemaParticle pt) return true; } - private int DatasetElementCount(XmlSchemaObjectCollection elements) + private static int DatasetElementCount(XmlSchemaObjectCollection elements) { int nCount = 0; foreach (XmlSchemaElement XmlElement in elements) @@ -1144,7 +1144,7 @@ internal void HandleComplexType(XmlSchemaComplexType ct, DataTable table, ArrayL _complexTypes.Remove(ct); } - internal XmlSchemaParticle? GetParticle(XmlSchemaComplexType ct) + internal static XmlSchemaParticle? GetParticle(XmlSchemaComplexType ct) { if (ct.ContentModel != null) { @@ -1173,7 +1173,7 @@ internal void HandleComplexType(XmlSchemaComplexType ct, DataTable table, ArrayL } } - internal DataColumn FindField(DataTable table, string field) + internal static DataColumn FindField(DataTable table, string field) { bool attribute = false; string colName = field; @@ -1200,7 +1200,7 @@ internal DataColumn FindField(DataTable table, string field) return col; } - internal DataColumn[] BuildKey(XmlSchemaIdentityConstraint keyNode, DataTable table) + internal static DataColumn[] BuildKey(XmlSchemaIdentityConstraint keyNode, DataTable table) { ArrayList keyColumns = new ArrayList(); @@ -1215,7 +1215,7 @@ internal DataColumn[] BuildKey(XmlSchemaIdentityConstraint keyNode, DataTable ta return key; } - internal bool GetBooleanAttribute(XmlSchemaAnnotated element, string attrName, bool defVal) + internal static bool GetBooleanAttribute(XmlSchemaAnnotated element, string attrName, bool defVal) { string? value = GetMsdataAttribute(element, attrName); if (value == null || value.Length == 0) @@ -1234,7 +1234,7 @@ internal bool GetBooleanAttribute(XmlSchemaAnnotated element, string attrName, b throw ExceptionBuilder.InvalidAttributeValue(attrName, value); } - internal string GetStringAttribute(XmlSchemaAnnotated element, string attrName, string defVal) + internal static string GetStringAttribute(XmlSchemaAnnotated element, string attrName, string defVal) { string? value = GetMsdataAttribute(element, attrName); if (value == null || value.Length == 0) @@ -1533,7 +1533,7 @@ internal DataTable InstantiateSimpleTable(XmlSchemaElement node) } - internal string GetInstanceName(XmlSchemaAnnotated node) + internal static string GetInstanceName(XmlSchemaAnnotated node) { string? instanceName = null; @@ -2790,7 +2790,7 @@ private void AddTablesToList(List tableList, DataTable dt) return GetNamespaceFromPrefix(prefix); } - private string GetTableName(XmlSchemaIdentityConstraint key) + private static string GetTableName(XmlSchemaIdentityConstraint key) { string xpath = key.Selector!.XPath!; string[] split = xpath.Split('/', ':'); 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 736b340ece89c..f8b4eae9bf74f 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XmlDataLoader.cs @@ -123,7 +123,7 @@ private void AttachRows(DataRow? parentRow, XmlNode parentElement) } } - private int CountNonNSAttributes(XmlNode node) + private static int CountNonNSAttributes(XmlNode node) { int count = 0; for (int i = 0; i < node.Attributes!.Count; i++) @@ -134,7 +134,7 @@ private int CountNonNSAttributes(XmlNode node) return count; } - private string GetValueForTextOnlyColums(XmlNode? n) + private static string GetValueForTextOnlyColums(XmlNode? n) { string? value = null; @@ -169,7 +169,7 @@ private string GetValueForTextOnlyColums(XmlNode? n) return value; } - private string GetInitialTextFromNodes(ref XmlNode? n) + private static string GetInitialTextFromNodes(ref XmlNode? n) { string? value = null; @@ -203,7 +203,7 @@ private string GetInitialTextFromNodes(ref XmlNode? n) return value; } - private DataColumn? GetTextOnlyColumn(DataRow row) + private static DataColumn? GetTextOnlyColumn(DataRow row) { DataColumnCollection columns = row.Table.Columns; int cCols = columns.Count; @@ -236,7 +236,7 @@ internal bool FColumnElement(XmlElement e) return true; } - private bool FExcludedNamespace(string ns) + private static bool FExcludedNamespace(string ns) { return ns.Equals(Keywords.XSD_XMLNS_NS); } @@ -264,7 +264,7 @@ private bool FIgnoreNamespace(XmlReader node) return false; } - internal bool IsTextLikeNode(XmlNodeType n) + internal static bool IsTextLikeNode(XmlNodeType n) { switch (n) { @@ -282,7 +282,7 @@ internal bool IsTextLikeNode(XmlNodeType n) } } - internal bool IsTextOnly(DataColumn c) + internal static bool IsTextOnly(DataColumn c) { if (c.ColumnMapping != MappingType.SimpleContent) return false; @@ -547,7 +547,7 @@ private void LoadRows(DataRow? parentRow, XmlNode parentElement) } [RequiresUnreferencedCode(DataSet.RequiresUnreferencedCodeMessage)] - private void SetRowValueFromXmlText(DataRow row, DataColumn col, string xmlText) + private static void SetRowValueFromXmlText(DataRow row, DataColumn col, string xmlText) { row[col] = col.ConvertXmlToObject(xmlText); } diff --git a/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs b/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs index f27573c55b6d9..568779d17abb5 100644 --- a/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs +++ b/src/libraries/System.Data.Common/src/System/Data/XmlToDatasetMap.cs @@ -207,7 +207,7 @@ private TableSchemaInfo AddTableSchema(XmlNameTable nameTable, DataTable table) // schema map in it } - private bool AddColumnSchema(DataColumn col, XmlNameTable nameTable, XmlNodeIdHashtable columns) + private static bool AddColumnSchema(DataColumn col, XmlNameTable nameTable, XmlNodeIdHashtable columns) { string? columnLocalName = nameTable.Get(col.EncodedColumnName); string? columnNamespace = nameTable.Get(col.Namespace); @@ -228,7 +228,7 @@ private bool AddColumnSchema(DataColumn col, XmlNameTable nameTable, XmlNodeIdHa return true; } - private bool AddColumnSchema(XmlNameTable nameTable, DataColumn col, XmlNodeIdHashtable columns) + private static bool AddColumnSchema(XmlNameTable nameTable, DataColumn col, XmlNodeIdHashtable columns) { string _columnLocalName = XmlConvert.EncodeLocalName(col.ColumnName); string? columnLocalName = nameTable.Get(_columnLocalName); // Look it up in a name table @@ -434,7 +434,7 @@ private void BuildIdentityMap(XmlNameTable nameTable, DataTable dataTable) } } - private ArrayList GetSelfAndDescendants(DataTable dt) + private static ArrayList GetSelfAndDescendants(DataTable dt) { // breadth-first ArrayList tableList = new ArrayList(); tableList.Add(dt); @@ -521,7 +521,7 @@ private ArrayList GetSelfAndDescendants(DataTable dt) return null; } - private void HandleSpecialColumn(DataColumn col, XmlNameTable nameTable, XmlNodeIdHashtable columns) + private static void HandleSpecialColumn(DataColumn col, XmlNameTable nameTable, XmlNodeIdHashtable columns) { // if column name starts with xml, we encode it manualy and add it for look up Debug.Assert(col.ColumnName.StartsWith("xml", StringComparison.OrdinalIgnoreCase), "column name should start with xml"); 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 b79b96c418472..538ced82fed4d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs +++ b/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs @@ -224,7 +224,7 @@ internal void AddXdoProperty(PropertyDescriptor pd, object instance, XmlElement [DynamicDependency(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicFields, typeof(DesignerSerializationVisibilityAttribute))] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "The DynamicDependency ensures the correct members are preserved.")] - private bool ContainsDesignerSerializationVisibleAttribute(PropertyDescriptor pd) => pd.Attributes.Contains(DesignerSerializationVisibilityAttribute.Visible); + private static bool ContainsDesignerSerializationVisibleAttribute(PropertyDescriptor pd) => pd.Attributes.Contains(DesignerSerializationVisibilityAttribute.Visible); internal static string XmlDataTypeName(Type type) { @@ -341,7 +341,7 @@ private static bool _PropsNotEmpty(PropertyCollection? props) return props != null && props.Count != 0; } - private bool HaveExtendedProperties(DataSet ds) + private static bool HaveExtendedProperties(DataSet ds) { if (_PropsNotEmpty(ds._extendedProperties)) { @@ -1567,7 +1567,7 @@ internal void AppendChildWithoutRef(XmlElement node, string Namespace, XmlElemen schNode.AppendChild(el); } - internal XmlElement? FindTypeNode(XmlElement node, string strType) + internal static XmlElement? FindTypeNode(XmlElement node, string strType) { if (node == null) return null; @@ -1600,7 +1600,7 @@ internal XmlElement HandleTable(DataTable table, XmlDocument dc, XmlElement sche // we write out column Ordinals only if the table contains columns // that map both to Attributes and Elements - private bool HasMixedColumns(DataTable table) + private static bool HasMixedColumns(DataTable table) { bool hasAttributes = false; bool hasElements = false; @@ -1676,7 +1676,7 @@ internal static bool AutoGenerated(UniqueConstraint unique) return AutoGenerated(unique.Key.ColumnsReference[0]); } - private bool AutoGenerated(ForeignKeyConstraint fk) + private static bool AutoGenerated(ForeignKeyConstraint fk) { return AutoGenerated(fk, true); } @@ -2571,7 +2571,7 @@ private void GenerateColumn(DataRow row, DataColumn col, DataRowVersion version) object columnValue = row[col, version]; // if the object is built in type or if it implements IXMLSerializable, write the start Element, otherwise //(if CDT and does not implement IXmlSerializable) skip it - if (!col.IsCustomType || !col.IsValueCustomTypeInstance(columnValue) || (typeof(IXmlSerializable).IsAssignableFrom(columnValue.GetType()))) + if (!col.IsCustomType || !DataColumn.IsValueCustomTypeInstance(columnValue) || (typeof(IXmlSerializable).IsAssignableFrom(columnValue.GetType()))) { _xmlw.WriteStartElement(colPrefix, col.EncodedColumnName, col.Namespace); startElementSkipped = false; @@ -2592,7 +2592,7 @@ private void GenerateColumn(DataRow row, DataColumn col, DataRowVersion version) { // Columns type is CDT if ((columnValue != DBNull.Value) && (!col.ImplementsINullable || !DataStorage.IsObjectSqlNull(columnValue))) { - if (col.IsValueCustomTypeInstance(columnValue)/* && valuesType != typeof(Type)*/) + if (DataColumn.IsValueCustomTypeInstance(columnValue)/* && valuesType != typeof(Type)*/) {// value is also CDT // if SkippedElement, ie does not implement IXMLSerializable: so No Polymorphysm Support. if (!startElementSkipped && columnValue.GetType() != col.DataType) @@ -2911,7 +2911,7 @@ internal void Save(XmlWriter xw, bool writeSchema) _xmlw.Flush(); } - private ArrayList GetNestedChildRelations(DataRow row) + private static ArrayList GetNestedChildRelations(DataRow row) { ArrayList list = new ArrayList(); @@ -3002,7 +3002,7 @@ internal void XmlDataRowWriter(DataRow row, string encodedTableName) if (col._columnMapping != MappingType.SimpleContent) { // again, if we need to use XmlSerializer, do not write start Element (see above for more info) - if (!col.IsCustomType || !col.IsValueCustomTypeInstance(value) || (typeof(IXmlSerializable).IsAssignableFrom(value.GetType()))) + if (!col.IsCustomType || !DataColumn.IsValueCustomTypeInstance(value) || (typeof(IXmlSerializable).IsAssignableFrom(value.GetType()))) { _xmlw.WriteStartElement(colPrefix, col.EncodedColumnName, col.Namespace); startElementSkipped = false; @@ -3023,7 +3023,7 @@ internal void XmlDataRowWriter(DataRow row, string encodedTableName) } else { // Columns type is CDT - if (col.IsValueCustomTypeInstance(value) /*&& !(value is Type) && valuesType != typeof(Type)*/) + if (DataColumn.IsValueCustomTypeInstance(value) /*&& !(value is Type) && valuesType != typeof(Type)*/) {// value is also CDT // if SkippedElement, ie does not implement IXMLSerializable: so No Polymorphism Support. if (!startElementSkipped && valuesType != col.DataType) diff --git a/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs b/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs index c7e99046842f2..3328015074373 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs @@ -54,7 +54,7 @@ internal DataPointer(DataPointer pointer) return rowElem; } - _doc.Mapper.GetRegion(_node, out rowElem); + DataSetMapper.GetRegion(_node, out rowElem); return rowElem; } @@ -499,7 +499,7 @@ internal string Name } } - private bool IsLocalNameEmpty(XmlNodeType nt) + private static bool IsLocalNameEmpty(XmlNodeType nt) { switch (nt) { diff --git a/src/libraries/System.Data.Common/src/System/Xml/DataSetMappper.cs b/src/libraries/System.Data.Common/src/System/Xml/DataSetMappper.cs index 550e3abf948e2..eccdf587c0492 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/DataSetMappper.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/DataSetMappper.cs @@ -181,7 +181,7 @@ internal DataTable SearchMatchingTableSchema(string localName, string namespaceU } return null; } - internal DataTable? GetTableSchemaForElement(XmlElement elem) + internal static DataTable? GetTableSchemaForElement(XmlElement elem) { XmlBoundElement? be = elem as XmlBoundElement; if (be == null) @@ -192,7 +192,7 @@ internal DataTable SearchMatchingTableSchema(string localName, string namespaceU return GetTableSchemaForElement(be); } - internal DataTable? GetTableSchemaForElement(XmlBoundElement be) => be.Row?.Table; + internal static DataTable? GetTableSchemaForElement(XmlBoundElement be) => be.Row?.Table; internal static bool IsNotMapped(DataColumn c) => c.ColumnMapping == MappingType.Hidden; @@ -202,14 +202,14 @@ internal DataTable SearchMatchingTableSchema(string localName, string namespaceU // XmlElement e = be; // GetRowFromElement( be ); // Calls GetRowFromElement( XmlBoundElement ) // GetRowFromElement( e ); // Calls GetRowFromElement( XmlElement ), in spite of e beeing an instance of XmlBoundElement - internal DataRow? GetRowFromElement(XmlElement? e) => (e as XmlBoundElement)?.Row; + internal static DataRow? GetRowFromElement(XmlElement? e) => (e as XmlBoundElement)?.Row; - internal DataRow? GetRowFromElement(XmlBoundElement be) => be.Row; + internal static DataRow? GetRowFromElement(XmlBoundElement be) => be.Row; // Get the row-elem associatd w/ the region node is in. // If node is in a region not mapped (like document element node) the function returns false and sets elem to null) // This function does not work if the region is not associated w/ a DataRow (it uses DataRow association to know what is the row element associated w/ the region) - internal bool GetRegion(XmlNode? node, [NotNullWhen(true)] out XmlBoundElement? rowElem) + internal static bool GetRegion(XmlNode? node, [NotNullWhen(true)] out XmlBoundElement? rowElem) { while (node != null) { @@ -372,7 +372,7 @@ private static object GetIdentity(string localName, string namespaceURI) return localName + ":" + namespaceURI; } - private bool IsNextColumn(DataColumnCollection columns, ref int iColumn, DataColumn col) + private static bool IsNextColumn(DataColumnCollection columns, ref int iColumn, DataColumn col) { for (; iColumn < columns.Count; iColumn++) { diff --git a/src/libraries/System.Data.Common/src/System/Xml/RegionIterator.cs b/src/libraries/System.Data.Common/src/System/Xml/RegionIterator.cs index 1a6545e1ea691..88c5ee6f7e364 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/RegionIterator.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/RegionIterator.cs @@ -123,7 +123,7 @@ internal bool NextInitialTextLikeNodes(out string value) Debug.Assert(CurrentNode.NodeType == XmlNodeType.Element); #if DEBUG // It's not OK to try to read the initial text value for sub-regions, because we do not know how to revert their initial state - if (CurrentNode.NodeType == XmlNodeType.Element && mapper.GetTableSchemaForElement((XmlElement)(CurrentNode)) != null) + if (CurrentNode.NodeType == XmlNodeType.Element && DataSetMapper.GetTableSchemaForElement((XmlElement)(CurrentNode)) != null) { if (CurrentNode != _rowElement) { diff --git a/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs b/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs index 5d5f7b4d268d1..6f52e630660ec 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs @@ -103,7 +103,7 @@ private XPathNodeType ConvertNodeType(XmlNode node) return (XPathNodeType)xnt; } - private bool IsNamespaceNode(XmlNodeType nt, string ns) => nt == XmlNodeType.Attribute && ns == StrReservedXmlns; + private static bool IsNamespaceNode(XmlNodeType nt, string ns) => nt == XmlNodeType.Attribute && ns == StrReservedXmlns; //when the constructor is called, the node has to be a valid XPath node at the valid location ( for example, the first //text/WS/SWS/CData nodes of a series continuous text-like nodes. @@ -453,7 +453,7 @@ internal string XmlLang return rowElem; } - _doc.Mapper.GetRegion(_node, out rowElem); + DataSetMapper.GetRegion(_node, out rowElem); return rowElem; } @@ -504,7 +504,7 @@ private void MoveTo(XmlNode node, DataColumn? column, bool fOnValue) _fOnValue = fOnValue; } - private bool IsFoliated(XmlNode node) + private static bool IsFoliated(XmlNode node) { if (node != null && node is XmlBoundElement) return ((XmlBoundElement)node).IsFoliated; @@ -693,7 +693,7 @@ internal bool MoveToNextAttribute(bool bFirst) return false; } - private bool IsValidChild(XmlNode parent, XmlNode child) + private static bool IsValidChild(XmlNode parent, XmlNode child) { int xntChildInt = s_xmlNodeType_To_XpathNodeType_Map[(int)(child.NodeType)]; if (xntChildInt == -1) @@ -719,7 +719,7 @@ private bool IsValidChild(XmlNode parent, XmlNode child) }; } - private bool IsValidChild(XmlNode parent, DataColumn c) + private static bool IsValidChild(XmlNode parent, DataColumn c) { int xntInt = s_xmlNodeType_To_XpathNodeType_Map[(int)(parent.NodeType)]; Debug.Assert(xntInt != -1); 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 c75a7afa48321..d7edf5727d000 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs @@ -149,7 +149,7 @@ internal void SyncRows(DataRow? parentRow, XmlNode node, bool fAddRowsToTable) internal void SyncTree(XmlNode node) { XmlBoundElement? be; - _mapper.GetRegion(node, out be); + DataSetMapper.GetRegion(node, out be); DataRow? parentRow = null; bool fAddRowsToTable = IsConnected(node); @@ -601,7 +601,7 @@ internal void Foliate(XmlBoundElement node, ElementState newState) { XmlBoundElement? rowElem; ElementState rowElemState = ElementState.None; - if (_mapper.GetRegion(node, out rowElem)) + if (DataSetMapper.GetRegion(node, out rowElem)) { rowElemState = rowElem.ElementState; Debug.Assert(rowElemState == ElementState.StrongFoliation || rowElemState == ElementState.WeakFoliation); @@ -786,7 +786,7 @@ private void ForceFoliation(XmlBoundElement node, ElementState newState) XmlElement? e = node as XmlElement; // insert location must be before any non-mapped elements or separate regions - if (_mapper.GetRowFromElement(e) != null) + if (DataSetMapper.GetRowFromElement(e) != null) break; object? schema = _mapper.GetColumnSchemaForNode(rowElement, node); @@ -860,7 +860,7 @@ private ArrayList GetNestedChildRelations(DataRow row) /// public DataRow? GetRowFromElement(XmlElement? e) { - return _mapper.GetRowFromElement(e); + return DataSetMapper.GetRowFromElement(e); } private XmlNode? GetRowInsertBeforeLocation(DataRow row, XmlElement rowElement, XmlNode parentElement) @@ -1813,7 +1813,7 @@ private void OnNodeChanged(object sender, XmlNodeChangedEventArgs args) Debug.Assert(DataSet.EnforceConstraints == false); - if (_mapper.GetRegion(args.Node, out rowElement)) + if (DataSetMapper.GetRegion(args.Node, out rowElement)) { SynchronizeRowFromRowElement(rowElement); } @@ -1949,7 +1949,7 @@ private void OnNodeRemovedFromTree(XmlNode node, XmlNode? oldParent) XmlBoundElement? oldRowElem; // Synchronize values from old region - if (_mapper.GetRegion(oldParent, out oldRowElem)) + if (DataSetMapper.GetRegion(oldParent, out oldRowElem)) SynchronizeRowFromRowElement(oldRowElem); // Disconnect all regions, starting w/ node (if it is a row-elem) @@ -1973,7 +1973,7 @@ private void OnNodeRemovedFromFragment(XmlNode node, XmlNode? oldParent) { XmlBoundElement? oldRowElem; - if (_mapper.GetRegion(oldParent, out oldRowElem)) + if (DataSetMapper.GetRegion(oldParent, out oldRowElem)) { // Sync the old region if it is not deleted DataRow row = oldRowElem.Row!; @@ -2307,7 +2307,7 @@ private void PromoteInnerRegions(XmlNode parent) XmlNode prevSibling = parent; XmlBoundElement? parentRegionRowElem; - _mapper.GetRegion(parent.ParentNode, out parentRegionRowElem); + DataSetMapper.GetRegion(parent.ParentNode, out parentRegionRowElem); TreeIterator iter = new TreeIterator(parent); bool fMore = iter.NextRowElement(); @@ -2712,7 +2712,7 @@ private void OnNodeInsertedInTree(XmlNode node) { XmlBoundElement? be; ArrayList rowElemList = new ArrayList(); - if (_mapper.GetRegion(node, out be)) + if (DataSetMapper.GetRegion(node, out be)) { if (be == node) { @@ -2750,7 +2750,7 @@ private void OnNodeInsertedInTree(XmlNode node) private void OnNodeInsertedInFragment(XmlNode node) { XmlBoundElement? be; - if (_mapper.GetRegion(node, out be)) + if (DataSetMapper.GetRegion(node, out be)) { if (be == node) { @@ -2938,7 +2938,7 @@ private void SetNestedParentRegion(XmlBoundElement childRowElem) Debug.Assert(childRowElem.Row != null); XmlBoundElement? parentRowElem; - _mapper.GetRegion(childRowElem.ParentNode, out parentRowElem); + DataSetMapper.GetRegion(childRowElem.ParentNode, out parentRowElem); SetNestedParentRegion(childRowElem, parentRowElem); } diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DBConnectionString.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DBConnectionString.cs index 1e6a0a019a62a..b6f03f5911683 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DBConnectionString.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DBConnectionString.cs @@ -294,7 +294,7 @@ internal DBConnectionString Intersect(DBConnectionString? entry) } [Conditional("DEBUG")] - private void ValidateCombinedSet(DBConnectionString? componentSet, DBConnectionString combinedSet) + private static void ValidateCombinedSet(DBConnectionString? componentSet, DBConnectionString combinedSet) { Debug.Assert(combinedSet != null, "The combined connection string should not be null"); if ((componentSet != null) && (combinedSet._restrictionValues != null) && (componentSet._restrictionValues != null)) diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs index 56abf205f6e3c..b26fec8a2d057 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/Common/DbConnectionOptions.cs @@ -201,7 +201,7 @@ public bool ConvertValueToIntegratedSecurity() return ConvertValueToIntegratedSecurityInternal((string)value); } - internal bool ConvertValueToIntegratedSecurityInternal(string stringValue) + internal static bool ConvertValueToIntegratedSecurityInternal(string stringValue) { if (CompareInsensitiveInvariant(stringValue, "sspi") || CompareInsensitiveInvariant(stringValue, "true") || CompareInsensitiveInvariant(stringValue, "yes")) return true; diff --git a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbBuffer.cs b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbBuffer.cs index e885ac9380b67..4c9bf45e2d9bd 100644 --- a/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbBuffer.cs +++ b/src/libraries/System.Data.Odbc/src/Common/System/Data/ProviderBase/DbBuffer.cs @@ -36,7 +36,7 @@ protected DbBuffer(IntPtr invalidHandleValue, bool ownsHandle) : base(invalidHan { } - private int BaseOffset { get { return 0; } } + private static int BaseOffset { get { return 0; } } public override bool IsInvalid { diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs index 5de32103c9e0c..d1cee50654a96 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnection.cs @@ -373,10 +373,6 @@ public override void Close() } } - private void DisposeMe(bool disposing) - { // MDAC 65459 - } - internal string GetConnectAttrString(ODBC32.SQL_ATTR attribute) { string value = ""; diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHelper.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHelper.cs index a84658b4b543f..36e0a8e25d417 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHelper.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcConnectionHelper.cs @@ -52,7 +52,7 @@ internal int CloseCount } } - internal DbConnectionFactory ConnectionFactory + internal static DbConnectionFactory ConnectionFactory { get { @@ -167,7 +167,6 @@ protected override void Dispose(bool disposing) _poolGroup = null; Close(); } - DisposeMe(disposing); base.Dispose(disposing); } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs index fb9e8d88c4bea..fb02819ad0b8a 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs @@ -2679,7 +2679,7 @@ private int RetrieveKeyInfoFromStatistics(QualifiedTableName qualifiedTableName, return keyColumns; } - internal bool SameIndexColumn(string currentindexname, string indexname, int ordinal, int ncols) + internal static bool SameIndexColumn(string currentindexname, string indexname, int ordinal, int ncols) { if (string.IsNullOrEmpty(currentindexname)) { diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs index 8b4f0ae845e3d..cc22a8b8398c3 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs @@ -134,7 +134,7 @@ internal OdbcMetaDataFactory(Stream XMLStream, } } - private object BooleanFromODBC(object odbcSource) + private static object BooleanFromODBC(object odbcSource) { if (odbcSource != DBNull.Value) { @@ -154,7 +154,7 @@ private object BooleanFromODBC(object odbcSource) return DBNull.Value; } - private OdbcCommand GetCommand(OdbcConnection connection) + private static OdbcCommand GetCommand(OdbcConnection connection) { OdbcCommand command = connection.CreateCommand(); @@ -164,7 +164,7 @@ private OdbcCommand GetCommand(OdbcConnection connection) return command; } - private DataTable DataTableFromDataReader(IDataReader reader, string tableName) + private static DataTable DataTableFromDataReader(IDataReader reader, string tableName) { // set up the column structure of the data table from the reader object[] values; @@ -179,7 +179,7 @@ private DataTable DataTableFromDataReader(IDataReader reader, string tableName) return resultTable; } - private void DataTableFromDataReaderDataTypes(DataTable dataTypesTable, OdbcDataReader dataReader, OdbcConnection connection) + private static void DataTableFromDataReaderDataTypes(DataTable dataTypesTable, OdbcDataReader dataReader, OdbcConnection connection) { DataTable? schemaTable; // @@ -425,7 +425,7 @@ private void DataTableFromDataReaderDataTypes(DataTable dataTypesTable, OdbcData } } - private DataTable DataTableFromDataReaderIndex(IDataReader reader, + private static DataTable DataTableFromDataReaderIndex(IDataReader reader, string tableName, string? restrictionIndexName) { @@ -449,7 +449,7 @@ private DataTable DataTableFromDataReaderIndex(IDataReader reader, return resultTable; } - private DataTable DataTableFromDataReaderProcedureColumns(IDataReader reader, string tableName, bool isColumn) + private static DataTable DataTableFromDataReaderProcedureColumns(IDataReader reader, string tableName, bool isColumn) { // set up the column structure of the data table from the reader object[] values; @@ -473,7 +473,7 @@ private DataTable DataTableFromDataReaderProcedureColumns(IDataReader reader, st return resultTable; } - private DataTable DataTableFromDataReaderProcedures(IDataReader reader, string tableName, short procedureType) + private static DataTable DataTableFromDataReaderProcedures(IDataReader reader, string tableName, short procedureType) { // Build a DataTable from the reader @@ -498,7 +498,7 @@ private DataTable DataTableFromDataReaderProcedures(IDataReader reader, string t return resultTable; } - private void FillOutRestrictions(int restrictionsCount, string?[]? restrictions, object?[] allRestrictions, string collectionName) + private static void FillOutRestrictions(int restrictionsCount, string?[]? restrictions, object?[] allRestrictions, string collectionName) { Debug.Assert(allRestrictions.Length >= restrictionsCount); @@ -529,7 +529,7 @@ private void FillOutRestrictions(int restrictionsCount, string?[]? restrictions, } - private DataTable GetColumnsCollection(string?[]? restrictions, OdbcConnection connection) + private static DataTable GetColumnsCollection(string?[]? restrictions, OdbcConnection connection) { OdbcCommand? command = null; OdbcDataReader? dataReader = null; @@ -830,7 +830,7 @@ private DataTable GetDataTypesCollection(string?[]? restrictions, OdbcConnection return dataTypesTable; } - private DataTable GetIndexCollection(string?[]? restrictions, OdbcConnection connection) + private static DataTable GetIndexCollection(string?[]? restrictions, OdbcConnection connection) { OdbcCommand? command = null; OdbcDataReader? dataReader = null; @@ -884,7 +884,7 @@ private DataTable GetIndexCollection(string?[]? restrictions, OdbcConnection con return resultTable; } - private DataTable GetProcedureColumnsCollection(string?[]? restrictions, OdbcConnection connection, bool isColumns) + private static DataTable GetProcedureColumnsCollection(string?[]? restrictions, OdbcConnection connection, bool isColumns) { OdbcCommand? command = null; OdbcDataReader? dataReader = null; @@ -927,7 +927,7 @@ private DataTable GetProcedureColumnsCollection(string?[]? restrictions, OdbcCon return resultTable; } - private DataTable GetProceduresCollection(string?[]? restrictions, OdbcConnection connection) + private static DataTable GetProceduresCollection(string?[]? restrictions, OdbcConnection connection) { OdbcCommand? command = null; OdbcDataReader? dataReader = null; @@ -1030,7 +1030,7 @@ private DataTable GetReservedWordsCollection(string?[]? restrictions, OdbcConnec return reservedWordsTable; } - private DataTable GetTablesCollection(string?[]? restrictions, OdbcConnection connection, bool isTables) + private static DataTable GetTablesCollection(string?[]? restrictions, OdbcConnection connection, bool isTables) { OdbcCommand? command = null; OdbcDataReader? dataReader = null; @@ -1079,7 +1079,7 @@ private DataTable GetTablesCollection(string?[]? restrictions, OdbcConnection co return resultTable; } - private bool IncludeIndexRow(object rowIndexName, + private static bool IncludeIndexRow(object rowIndexName, string? restrictionIndexName, short rowIndexType) { @@ -1097,7 +1097,7 @@ private bool IncludeIndexRow(object rowIndexName, return true; } - private DataTable NewDataTableFromReader(IDataReader reader, out object[] values, string tableName) + private static DataTable NewDataTableFromReader(IDataReader reader, out object[] values, string tableName) { DataTable resultTable = new DataTable(tableName); resultTable.Locale = System.Globalization.CultureInfo.InvariantCulture; diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs index 15f00fd2c8b9f..088b2e5e8464e 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameter.cs @@ -1124,17 +1124,17 @@ public override object? Value } } - private byte ValuePrecision(object? value) + private static byte ValuePrecision(object? value) { return ValuePrecisionCore(value); } - private byte ValueScale(object? value) + private static byte ValueScale(object? value) { return ValueScaleCore(value); } - private int ValueSize(object? value) + private static int ValueSize(object? value) { return ValueSizeCore(value); } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterHelper.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterHelper.cs index 60634ace15121..03a01c9735a5e 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterHelper.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcParameterHelper.cs @@ -216,7 +216,7 @@ public override string ToString() return ParameterName; } - private byte ValuePrecisionCore(object? value) + private static byte ValuePrecisionCore(object? value) { if (value is decimal) { @@ -225,7 +225,7 @@ private byte ValuePrecisionCore(object? value) return 0; } - private byte ValueScaleCore(object? value) + private static byte ValueScaleCore(object? value) { if (value is decimal) { @@ -234,7 +234,7 @@ private byte ValueScaleCore(object? value) return 0; } - private int ValueSizeCore(object? value) + private static int ValueSizeCore(object? value) { if (!ADP.IsNull(value)) { diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcUtils.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcUtils.cs index f3c8d232268cb..a9c6e5fcb075d 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcUtils.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcUtils.cs @@ -499,7 +499,7 @@ private int GetTokenFromQuote(int curidx) return localidx; } - private bool IsValidNameChar(char ch) + private static bool IsValidNameChar(char ch) { return (char.IsLetterOrDigit(ch) || (ch == '_') || (ch == '-') || (ch == '.') || diff --git a/src/libraries/System.Data.OleDb/src/DbBindings.cs b/src/libraries/System.Data.OleDb/src/DbBindings.cs index c380281285445..f5d0fd868f2cf 100644 --- a/src/libraries/System.Data.OleDb/src/DbBindings.cs +++ b/src/libraries/System.Data.OleDb/src/DbBindings.cs @@ -288,7 +288,7 @@ internal void ApplyInputParameters() { if (ADP.IsDirection(parameters[i], ParameterDirection.Input)) { - columnBindings[i].SetOffset(parameters[i].Offset); + columnBindings[i].SetOffset(OleDbParameter.Offset); columnBindings[i].Value(parameters[i].GetCoercedValue()); } else diff --git a/src/libraries/System.Data.OleDb/src/DbParameterHelper.cs b/src/libraries/System.Data.OleDb/src/DbParameterHelper.cs index a89572d1f606a..0a25ac9fcc53c 100644 --- a/src/libraries/System.Data.OleDb/src/DbParameterHelper.cs +++ b/src/libraries/System.Data.OleDb/src/DbParameterHelper.cs @@ -88,13 +88,7 @@ public override bool IsNullable } } - internal int Offset - { - get - { - return 0; - } - } + internal const int Offset = 0; public override int Size { // V1.2.3300, XXXParameter V1.0.3300 @@ -226,7 +220,7 @@ public override string ToString() return ParameterName; } - private byte ValuePrecisionCore(object? value) + private static byte ValuePrecisionCore(object? value) { // V1.2.3300 if (value is decimal) { @@ -235,7 +229,7 @@ private byte ValuePrecisionCore(object? value) return 0; } - private byte ValueScaleCore(object? value) + private static byte ValueScaleCore(object? value) { // V1.2.3300 if (value is decimal) { @@ -244,7 +238,7 @@ private byte ValueScaleCore(object? value) return 0; } - private int ValueSizeCore(object? value) + private static int ValueSizeCore(object? value) { // V1.2.3300 if (!ADP.IsNull(value)) { diff --git a/src/libraries/System.Data.OleDb/src/OleDbCommand.cs b/src/libraries/System.Data.OleDb/src/OleDbCommand.cs index a6b9503e0abf6..31a79543b7923 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbCommand.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbCommand.cs @@ -1093,7 +1093,7 @@ private string ExpandOdbcMaximumToText(string sproctext, int parameterCount) return builder.ToString(); } - private string ExpandOdbcMinimumToText(string sproctext, int parameterCount) + private static string ExpandOdbcMinimumToText(string sproctext, int parameterCount) { //if ((0 < parameterCount) && (ParameterDirection.ReturnValue == Parameters[0].Direction)) { // Debug.Assert("doesn't support ReturnValue parameters"); diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs index 1a605f9e2c4fa..e1625e1ea43e5 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnection.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnection.cs @@ -307,8 +307,6 @@ internal int QuotedIdentifierCase() return quotedIdentifierCase; } - internal bool ForceNewConnection { get { return false; } set {; } } - public new OleDbTransaction BeginTransaction() { return BeginTransaction(IsolationLevel.Unspecified); diff --git a/src/libraries/System.Data.OleDb/src/OleDbConnectionStringBuilder.cs b/src/libraries/System.Data.OleDb/src/OleDbConnectionStringBuilder.cs index 385b096029ace..42af1aeaca9af 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbConnectionStringBuilder.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbConnectionStringBuilder.cs @@ -723,7 +723,7 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( return base.ConvertTo(context, culture, value, destinationType); } - private System.ComponentModel.Design.Serialization.InstanceDescriptor ConvertToInstanceDescriptor(OleDbConnectionStringBuilder options) + private static System.ComponentModel.Design.Serialization.InstanceDescriptor ConvertToInstanceDescriptor(OleDbConnectionStringBuilder options) { Type[] ctorParams = new Type[] { typeof(string) }; object[] ctorValues = new object[] { options.ConnectionString }; diff --git a/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs b/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs index eeccb6f1caf43..9a358d699a6d8 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbDataAdapter.cs @@ -415,7 +415,7 @@ private int FillFromRecord(object data, UnsafeNativeMethods.ADORecordConstructio return 0; } - private void FillClose(bool isrecordset, object value) + private static void FillClose(bool isrecordset, object value) { OleDbHResult hr; if (isrecordset) diff --git a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs index 966ec039781eb..cb2c9b06dc5ed 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs @@ -1927,7 +1927,7 @@ private void GetRowValue() _nextAccessorForRetrieval++; } - private int IndexOf(Hashtable hash, string name) + private static int IndexOf(Hashtable hash, string name) { // via case sensitive search, first match with lowest ordinal matches object? index = hash[name]; diff --git a/src/libraries/System.Data.OleDb/src/OleDbMetaDataFactory.cs b/src/libraries/System.Data.OleDb/src/OleDbMetaDataFactory.cs index d2620c38b1c53..4c0296ef55d52 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbMetaDataFactory.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbMetaDataFactory.cs @@ -175,7 +175,7 @@ internal OleDbMetaDataFactory(Stream XMLStream, } - private string BuildRegularExpression(string invalidChars, string invalidStartingChars) + private static string BuildRegularExpression(string invalidChars, string invalidStartingChars) { StringBuilder regularExpression = new StringBuilder("[^"); ADP.EscapeSpecialCharacters(invalidStartingChars, regularExpression); @@ -656,7 +656,7 @@ protected override DataTable PrepareCollection(string collectionName, string?[]? return resultTable; } - private void SetIdentifierCase(string columnName, int propertyID, DataRow row, OleDbConnection connection) + private static void SetIdentifierCase(string columnName, int propertyID, DataRow row, OleDbConnection connection) { object? property = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, propertyID); IdentifierCase identifierCase = IdentifierCase.Unknown; diff --git a/src/libraries/System.Data.OleDb/src/OleDbParameter.cs b/src/libraries/System.Data.OleDb/src/OleDbParameter.cs index 25265936603b6..dcd2c4f852648 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbParameter.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbParameter.cs @@ -575,17 +575,17 @@ public override object? Value } } - private byte ValuePrecision(object? value) + private static byte ValuePrecision(object? value) { return ValuePrecisionCore(value); } - private byte ValueScale(object? value) + private static byte ValueScale(object? value) { return ValueScaleCore(value); } - private int ValueSize(object? value) + private static int ValueSize(object? value) { return ValueSizeCore(value); } @@ -650,7 +650,7 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( return base.ConvertTo(context, culture, value, destinationType); } - private System.ComponentModel.Design.Serialization.InstanceDescriptor ConvertToInstanceDescriptor(OleDbParameter p) + private static System.ComponentModel.Design.Serialization.InstanceDescriptor ConvertToInstanceDescriptor(OleDbParameter p) { int flags = 0; diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbBuffer.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbBuffer.cs index 7ffbdea2af69c..3f50fd38f3814 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbBuffer.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbBuffer.cs @@ -43,7 +43,7 @@ protected DbBuffer(IntPtr invalidHandleValue, bool ownsHandle) : base(invalidHan { } - private int BaseOffset { get { return 0; } } + private const int BaseOffset = 0; public override bool IsInvalid { diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs index aae9ec2029485..a67b45401a2a1 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionFactory.cs @@ -256,17 +256,9 @@ internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSour } else { - if (((System.Data.OleDb.OleDbConnection)owningConnection).ForceNewConnection) + if (!connectionPool.TryGetConnection(owningConnection, retry, userOptions, out connection)) { - Debug.Assert(!(oldConnection is DbConnectionClosed), "Force new connection, but there is no old connection"); - connection = connectionPool.ReplaceConnection(owningConnection, userOptions, oldConnection); - } - else - { - if (!connectionPool.TryGetConnection(owningConnection, retry, userOptions, out connection)) - { - return false; - } + return false; } if (connection == null) diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionHelper.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionHelper.cs index 92f8137771f38..d1f710dbf9c29 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionHelper.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionHelper.cs @@ -44,7 +44,7 @@ private void CopyFrom(OleDbConnection connection) } } - internal DbConnectionFactory ConnectionFactory + private static DbConnectionFactory ConnectionFactory { get { diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs index e1ba5c74bfa59..9f02ad2763b38 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPool.cs @@ -658,8 +658,6 @@ private Timer CreateCleanupTimer() return (new Timer(new TimerCallback(this.CleanupCallback), null, _cleanupWait, _cleanupWait)); } - private bool IsBlockingPeriodEnabled() => true; - private DbConnectionInternal CreateObject(DbConnection? owningObject, DbConnectionOptions? userOptions, DbConnectionInternal? oldConnection) { DbConnectionInternal? newObj = null; @@ -716,11 +714,6 @@ private DbConnectionInternal CreateObject(DbConnection? owningObject, DbConnecti ADP.TraceExceptionForCapture(e); - if (!IsBlockingPeriodEnabled()) - { - throw; - } - newObj = null; // set to null, so we do not return bad new object // Failed to create instance _resError = e; diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolCounters.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolCounters.cs index 015511d792f4c..990461c6d4919 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolCounters.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbConnectionPoolCounters.cs @@ -217,7 +217,7 @@ protected DbConnectionPoolCounters(string? categoryName, string? categoryHelp) NumberOfActiveConnections = new Counter(verboseCategoryName, instanceName, CreationData.NumberOfActiveConnections.CounterName, CreationData.NumberOfActiveConnections.CounterType); NumberOfFreeConnections = new Counter(verboseCategoryName, instanceName, CreationData.NumberOfFreeConnections.CounterName, CreationData.NumberOfFreeConnections.CounterType); } - private string? GetAssemblyName() + private static string? GetAssemblyName() { string? result = null; @@ -236,7 +236,7 @@ protected DbConnectionPoolCounters(string? categoryName, string? categoryHelp) } // SxS: this method uses GetCurrentProcessId to construct the instance name. - private string GetInstanceName() + private static string GetInstanceName() { string? instanceName = GetAssemblyName(); // instance perfcounter name @@ -296,7 +296,7 @@ public void Dispose() SafeDispose(NumberOfReclaimedConnections); } - private void SafeDispose(Counter counter) + private static void SafeDispose(Counter counter) { if (null != counter) { diff --git a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbMetaDataFactory.cs b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbMetaDataFactory.cs index 2361fc26095c6..0700b543a1b6f 100644 --- a/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbMetaDataFactory.cs +++ b/src/libraries/System.Data.OleDb/src/System/Data/ProviderBase/DbMetaDataFactory.cs @@ -210,7 +210,7 @@ private DataTable ExecuteCommand(DataRow requestedCollectionRow, string?[]? rest return resultTable; } - private DataColumn[] FilterColumns(DataTable sourceTable, string[]? hiddenColumnNames, DataColumnCollection destinationColumns) + private static DataColumn[] FilterColumns(DataTable sourceTable, string[]? hiddenColumnNames, DataColumnCollection destinationColumns) { DataColumn newDestinationColumn; int currentColumn; @@ -479,7 +479,7 @@ public virtual DataTable GetSchema(DbConnection connection, string collectionNam return requestedSchema; } - private bool IncludeThisColumn(DataColumn sourceColumn, string[]? hiddenColumnNames) + private static bool IncludeThisColumn(DataColumn sourceColumn, string[]? hiddenColumnNames) { bool result = true; string sourceColumnName = sourceColumn.ColumnName; diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs index 703f1d99ab2bd..7ad3a914d15f7 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.cs @@ -1201,6 +1201,7 @@ private string GetRootId(string id) return id.Substring(rootStart, rootEnd - rootStart); } +#pragma warning disable CA1822 private string AppendSuffix(string parentId, string suffix, char delimiter) { #if DEBUG @@ -1227,6 +1228,8 @@ private string AppendSuffix(string parentId, string suffix, char delimiter) string overflowSuffix = ((int)GetRandomNumber()).ToString("x8"); return parentId.Substring(0, trimPosition) + overflowSuffix + '#'; } +#pragma warning restore CA1822 + #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/HttpHandlerDiagnosticListener.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/HttpHandlerDiagnosticListener.cs index 87b19412d229c..01a872e660d2c 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/HttpHandlerDiagnosticListener.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/HttpHandlerDiagnosticListener.cs @@ -676,7 +676,7 @@ private void RaiseResponseEvent(HttpWebRequest request, HttpStatusCode statusCod } } - private bool IsLastResponse(HttpWebRequest request, HttpStatusCode statusCode) + private static bool IsLastResponse(HttpWebRequest request, HttpStatusCode statusCode) { if (request.AllowAutoRedirect) { diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ExponentialHistogramAggregator.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ExponentialHistogramAggregator.cs index b12603b85f0a9..678cf6ea890ac 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ExponentialHistogramAggregator.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ExponentialHistogramAggregator.cs @@ -126,7 +126,7 @@ public override IAggregationStatistics Collect() return new HistogramStatistics(Array.Empty()); } - private int GetInvalidCount(int[]?[] counters) + private static int GetInvalidCount(int[]?[] counters) { int[]? positiveInfAndNan = counters[ExponentArraySize / 2 - 1]; int[]? negativeInfAndNan = counters[ExponentArraySize - 1]; @@ -209,7 +209,7 @@ public override void Update(double measurement) } } - private int QuantileToRank(double quantile, int count) + private static int QuantileToRank(double quantile, int count) { return Math.Min(Math.Max(0, (int)(quantile * count)), count - 1); } diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/MetricsEventSource.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/MetricsEventSource.cs index 9923589b24627..de3a6cb340f19 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/MetricsEventSource.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/MetricsEventSource.cs @@ -391,7 +391,7 @@ private void ParseSpecs(string? metricsSpecs) } } - private void TransmitMetricValue(Instrument instrument, LabeledAggregationStatistics stats, string sessionId) + private static void TransmitMetricValue(Instrument instrument, LabeledAggregationStatistics stats, string sessionId) { if (stats.AggregationStatistics is RateStatistics rateStats) { @@ -409,7 +409,7 @@ private void TransmitMetricValue(Instrument instrument, LabeledAggregationStatis } } - private string FormatTags(KeyValuePair[] labels) + private static string FormatTags(KeyValuePair[] labels) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < labels.Length; i++) @@ -423,7 +423,7 @@ private string FormatTags(KeyValuePair[] labels) return sb.ToString(); } - private string FormatQuantiles(QuantileValue[] quantiles) + private static string FormatQuantiles(QuantileValue[] quantiles) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < quantiles.Length; i++) diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableInstrument.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableInstrument.cs index 1cbcd59ef3ee4..7e76ac3bd264c 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableInstrument.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Metrics/ObservableInstrument.cs @@ -62,7 +62,7 @@ internal override void Observe(MeterListener listener) // Will be called from the concrete classes which extends ObservabilityInstrument when calling Observe() method. [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal IEnumerable> Observe(object callback) + internal static IEnumerable> Observe(object callback) { if (callback is Func valueOnlyFunc) { diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/RandomNumberGenerator.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/RandomNumberGenerator.cs index 07cbd932f3ad7..71c686edf3a10 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/RandomNumberGenerator.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/RandomNumberGenerator.cs @@ -51,7 +51,7 @@ public unsafe RandomNumberGenerator() while ((_s0 | _s1 | _s2 | _s3) == 0); } - private ulong Rol64(ulong x, int k) => (x << k) | (x >> (64 - k)); + private static ulong Rol64(ulong x, int k) => (x << k) | (x >> (64 - k)); public long Next() { diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogEntry.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogEntry.cs index ad457260c4e46..2f963d060616e 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogEntry.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogEntry.cs @@ -293,7 +293,7 @@ public string UserName } } - private char CharFrom(byte[] buf, int offset) + private static char CharFrom(byte[] buf, int offset) { return (char)ShortFrom(buf, offset); } @@ -320,7 +320,7 @@ public bool Equals(EventLogEntry otherEntry) return true; } - private int IntFrom(byte[] buf, int offset) + private static int IntFrom(byte[] buf, int offset) { // assumes Little Endian byte order. return (unchecked((int)0xFF000000) & (buf[offset + 3] << 24)) | (0xFF0000 & (buf[offset + 2] << 16)) | @@ -442,7 +442,7 @@ private string GetMessageLibraryNames(string libRegKey) } } - private short ShortFrom(byte[] buf, int offset) + private static short ShortFrom(byte[] buf, int offset) { // assumes little Endian byte order. return (short)((0xFF00 & (buf[offset + 1] << 8)) | (0xFF & buf[offset])); diff --git a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogTraceListener.cs b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogTraceListener.cs index 242f019105285..644a87be97a7f 100644 --- a/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogTraceListener.cs +++ b/src/libraries/System.Diagnostics.EventLog/src/System/Diagnostics/EventLogTraceListener.cs @@ -148,7 +148,7 @@ public override void TraceData(TraceEventCache eventCache, string source, TraceE EventLog.WriteEvent(inst, new object[] { sb.ToString() }); } - private EventInstance CreateEventInstance(TraceEventType severity, int id) + private static EventInstance CreateEventInstance(TraceEventType severity, int id) { // Win32 EventLog has an implicit cap at ushort.MaxValue // We need to cap this explicitly to prevent larger value 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 87da3cd584107..48ad029b33909 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounter.cs @@ -432,7 +432,7 @@ public long Increment() return _sharedCounter.Increment(); } - private void ThrowReadOnly() + private static void ThrowReadOnly() { throw new InvalidOperationException(SR.ReadOnlyCounter); } diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs index 1819697f819b6..220156f369c0d 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceCounterLib.cs @@ -1046,9 +1046,9 @@ internal byte[] GetPerformanceData(string item, bool usePool = false) return _performanceMonitor.GetData(item, usePool); } - internal void ReleasePerformanceData(byte[] data) + internal static void ReleasePerformanceData(byte[] data) { - _performanceMonitor.ReleaseData(data); + PerformanceMonitor.ReleaseData(data); } private Hashtable GetStringTable(bool isHelp) @@ -1385,9 +1385,9 @@ internal byte[] GetData(string item, bool usePool) throw new Win32Exception(error); } - internal void ReleaseData(byte[] data) + internal static void ReleaseData(byte[] data) { - perfDataKey.ReleaseData(data); + PerformanceDataRegistryKey.ReleaseData(data); } } @@ -1678,7 +1678,7 @@ public void Dispose() _disposed = true; - _library.ReleasePerformanceData(_data); + PerformanceCounterLib.ReleasePerformanceData(_data); } private void CheckDisposed() diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceDataRegistryKey.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceDataRegistryKey.cs index 98ef10aa35379..c1ba8ddabc3f2 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceDataRegistryKey.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceDataRegistryKey.cs @@ -93,7 +93,7 @@ public byte[] GetValue(string name, bool usePool) return data; } - public void ReleaseData(byte[] data, bool usePool = true) + internal static void ReleaseData(byte[] data, bool usePool = true) { if (usePool) { @@ -111,7 +111,7 @@ public void Dispose() _hkey.Dispose(); } - private byte[] CreateBlob(int size, in bool usePool) + private static byte[] CreateBlob(int size, in bool usePool) { return usePool ? ArrayPool.Shared.Rent(size) diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.BSD.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.BSD.cs index 70c408cea290b..1bc72cd9b0042 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.BSD.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.BSD.cs @@ -44,7 +44,7 @@ public static Process[] GetProcessesByName(string? processName, string machineNa /// /// Gets or sets which processors the threads in this process can be scheduled to run on. /// - private IntPtr ProcessorAffinityCore + private static IntPtr ProcessorAffinityCore { get { diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.FreeBSD.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.FreeBSD.cs index 3fe4314636d33..6745f39caeaf1 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.FreeBSD.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.FreeBSD.cs @@ -88,7 +88,7 @@ private unsafe int ParentProcessId } // Gets execution path - private string? GetPathToOpenFile() + private static string? GetPathToOpenFile() { if (Interop.Sys.Stat("/usr/local/bin/open", out _) == 0) { 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 e4b149b84a6d2..5d5bf3b698464 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 @@ -108,7 +108,7 @@ private static DateTime BootTime GetStat().ppid; /// Gets execution path - private string? GetPathToOpenFile() + private static string? GetPathToOpenFile() { string[] allowedProgramsToRun = { "xdg-open", "gnome-open", "kfmclient" }; foreach (var program in allowedProgramsToRun) @@ -238,7 +238,7 @@ 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. - private void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr resultingMin, out IntPtr resultingMax) + 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); diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.OSX.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.OSX.cs index c06f622880ddd..5cdc48581b00f 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.OSX.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.OSX.cs @@ -42,7 +42,7 @@ internal DateTime StartTimeCore } /// Gets execution path - private string GetPathToOpenFile() + private static string GetPathToOpenFile() { return "/usr/bin/open"; } @@ -95,7 +95,7 @@ private int ParentProcessId // ---- Unix PAL layer ends here ---- // ---------------------------------- - private Interop.libproc.rusage_info_v3 GetCurrentProcessRUsage() + private static Interop.libproc.rusage_info_v3 GetCurrentProcessRUsage() { return Interop.libproc.proc_pid_rusage(Environment.ProcessId); } 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 2a19a2de58777..bb5298411d313 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 @@ -142,10 +142,7 @@ private void KillTree(ref List? exceptions) } /// Discards any information about the associated process. - private void RefreshCore() - { - // Nop. No additional state to reset. - } + partial void RefreshCore(); /// Additional logic invoked when the Process is closed. private void CloseCore() @@ -249,7 +246,7 @@ private DateTime ExitTimeCore /// should be temporarily boosted by the operating system when the main window /// has focus. /// - private bool PriorityBoostEnabledCore + private static bool PriorityBoostEnabledCore { get { return false; } //Nop set { } // Nop @@ -1055,13 +1052,13 @@ private static unsafe bool TryGetPasswd(string name, byte* buf, int bufLen, out public IntPtr MainWindowHandle => IntPtr.Zero; - private bool CloseMainWindowCore() => false; + private static bool CloseMainWindowCore() => false; public string MainWindowTitle => string.Empty; public bool Responding => true; - private bool WaitForInputIdleCore(int milliseconds) => throw new InvalidOperationException(SR.InputIdleUnkownError); + private static bool WaitForInputIdleCore(int milliseconds) => throw new InvalidOperationException(SR.InputIdleUnkownError); private static unsafe void EnsureInitialized() { diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs index d333809adaeeb..84fc7fb2b54eb 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Win32.cs @@ -109,7 +109,7 @@ private unsafe bool StartWithShellExecuteEx(ProcessStartInfo startInfo) return false; } - private int GetShellError(IntPtr error) + private static int GetShellError(IntPtr error) { switch ((long)error) { diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs index 8635a81f9f145..b01c29854a32c 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Windows.cs @@ -133,10 +133,7 @@ private void RefreshCore() } /// Additional logic invoked when the Process is closed. - private void CloseCore() - { - // Nop - } + partial void CloseCore(); /// /// Make sure we are watching for a process exit. @@ -793,7 +790,7 @@ private static void CreatePipeWithSecurityAttributes(out SafeFileHandle hReadPip // methods such as WriteLine as well as native CRT functions like printf) which are making an // assumption that the console standard handles (obtained via GetStdHandle()) are opened // for synchronous I/O and hence they can work fine with ReadFile/WriteFile synchronously! - private void CreatePipe(out SafeFileHandle parentHandle, out SafeFileHandle childHandle, bool parentInputs) + private static void CreatePipe(out SafeFileHandle parentHandle, out SafeFileHandle childHandle, bool parentInputs) { Interop.Kernel32.SECURITY_ATTRIBUTES securityAttributesParent = default; securityAttributesParent.bInheritHandle = Interop.BOOL.TRUE; 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 abbb712d4006a..70fb58c3b4cb0 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 @@ -40,7 +40,7 @@ public TimeSpan PrivilegedProcessorTime /// Gets the time the associated process was started. [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] - internal DateTime StartTimeCore + internal static DateTime StartTimeCore { get { throw new PlatformNotSupportedException(); } } @@ -71,19 +71,19 @@ public TimeSpan UserProcessorTime /// /// Returns all immediate child processes. /// - private IReadOnlyList GetChildProcesses(Process[]? processes = null) + private static IReadOnlyList GetChildProcesses(Process[]? processes = null) { throw new PlatformNotSupportedException(); } /// Gets parent process ID - private int GetParentProcessId => + private static int GetParentProcessId => throw new PlatformNotSupportedException(); /// /// Gets or sets which processors the threads in this process can be scheduled to run on. /// - private IntPtr ProcessorAffinityCore + private static IntPtr ProcessorAffinityCore { get { throw new PlatformNotSupportedException(); } set { throw new PlatformNotSupportedException(); } @@ -92,7 +92,7 @@ private IntPtr ProcessorAffinityCore /// /// Make sure we have obtained the min and max working set limits. /// - private void GetWorkingSetLimits(out IntPtr minWorkingSet, out IntPtr maxWorkingSet) + private static void GetWorkingSetLimits(out IntPtr minWorkingSet, out IntPtr maxWorkingSet) { throw new PlatformNotSupportedException(); } @@ -102,18 +102,20 @@ 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. - private void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr resultingMin, out IntPtr resultingMax) + private static void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr resultingMin, out IntPtr resultingMax) { throw new PlatformNotSupportedException(); } /// Gets execution path - private string GetPathToOpenFile() + private static string GetPathToOpenFile() { throw new PlatformNotSupportedException(); } +#pragma warning disable CA1822 private int ParentProcessId => throw new PlatformNotSupportedException(); +#pragma warning restore CA1822 private static bool IsProcessInvalidException(Exception e) => // InvalidOperationException signifies conditions such as the process already being dead. diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessThread.FreeBSD.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessThread.FreeBSD.cs index a6b17bee36fb5..c8d7abffeea91 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessThread.FreeBSD.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessThread.FreeBSD.cs @@ -25,7 +25,7 @@ private ThreadPriorityLevel PriorityLevelCore // kinfo_proc has one entry per thread but ki_start seems to be same for // all threads e.g. reflects process start. This may be re-visited later. - private DateTime GetStartTime() => throw new PlatformNotSupportedException(); + private static DateTime GetStartTime() => throw new PlatformNotSupportedException(); /// /// Returns the amount of time the associated thread has spent utilizing the CPU. diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessThread.OSX.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessThread.OSX.cs index e95abff9af741..48690a3dd0299 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessThread.OSX.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessThread.OSX.cs @@ -10,7 +10,7 @@ public partial class ProcessThread /// not an absolute level, but instead contributes to the actual thread priority by /// considering the priority class of the process. /// - private ThreadPriorityLevel PriorityLevelCore + private static ThreadPriorityLevel PriorityLevelCore { // Does not appear to be a POSIX API to do this on macOS. // Considered the posix pthread_getschedparam, and pthread_setschedparam, @@ -25,7 +25,7 @@ private ThreadPriorityLevel PriorityLevelCore /// public TimeSpan PrivilegedProcessorTime => new TimeSpan((long)GetThreadInfo().pth_system_time); - private DateTime GetStartTime() => throw new PlatformNotSupportedException(); // macOS does not provide a way to get this data + private static DateTime GetStartTime() => throw new PlatformNotSupportedException(); // macOS does not provide a way to get this data /// /// Returns the amount of time the associated thread has spent using the CPU. diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessThread.Unix.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessThread.Unix.cs index ccee750841cd7..0d954fa39a74b 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessThread.Unix.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessThread.Unix.cs @@ -29,7 +29,7 @@ public void ResetIdealProcessor() /// Returns or sets whether this thread would like a priority boost if the user interacts /// with user interface associated with this thread. /// - private bool PriorityBoostEnabledCore + private static bool PriorityBoostEnabledCore { get { return false; } set { } // Nop diff --git a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessThread.iOS.cs b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessThread.iOS.cs index 8faa430900aab..14aae34e6bf2f 100644 --- a/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessThread.iOS.cs +++ b/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessThread.iOS.cs @@ -12,7 +12,7 @@ public partial class ProcessThread /// not an absolute level, but instead contributes to the actual thread priority by /// considering the priority class of the process. /// - private ThreadPriorityLevel PriorityLevelCore + private static ThreadPriorityLevel PriorityLevelCore { get { throw new PlatformNotSupportedException(); } set { throw new PlatformNotSupportedException(); } @@ -29,7 +29,7 @@ public TimeSpan PrivilegedProcessorTime get { throw new PlatformNotSupportedException(); } } - private DateTime GetStartTime() => throw new PlatformNotSupportedException(); + private static DateTime GetStartTime() => throw new PlatformNotSupportedException(); /// /// Returns the amount of time the associated thread has spent utilizing the CPU. /// It is the sum of the System.Diagnostics.ProcessThread.UserProcessorTime and diff --git a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/DelimitedListTraceListener.cs b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/DelimitedListTraceListener.cs index 52454f94c6906..3cc0e04be6a9e 100644 --- a/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/DelimitedListTraceListener.cs +++ b/src/libraries/System.Diagnostics.TextWriterTraceListener/src/System/Diagnostics/DelimitedListTraceListener.cs @@ -239,7 +239,7 @@ private void WriteStackEscaped(Stack stack) Write(sb.ToString()); } - private void EscapeMessage(string? message, StringBuilder sb) + private static void EscapeMessage(string? message, StringBuilder sb) { if (!string.IsNullOrEmpty(message)) { diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/CorrelationManager.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/CorrelationManager.cs index 518eb61be5101..4d1fd4db4be2f 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/CorrelationManager.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/CorrelationManager.cs @@ -90,7 +90,7 @@ public override void CopyTo(Array array, int index) } } - private IEnumerator GetEnumerator(StackNode? n) + private static IEnumerator GetEnumerator(StackNode? n) { while (n != null) { diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListeners.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListeners.cs index a1045d0ab7e7b..3decbbb537b17 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListeners.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceListeners.cs @@ -142,7 +142,7 @@ public IEnumerator GetEnumerator() return _list.GetEnumerator(); } - internal void InitializeListener(TraceListener listener!!) + internal static void InitializeListener(TraceListener listener!!) { listener.IndentSize = TraceInternal.IndentSize; listener.IndentLevel = TraceInternal.IndentLevel; 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 8c92ed4fc9ed8..b918883f7192d 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 + $(NoWarn);CA1845;CA1846;IDE0059;CA1822 annotations true true diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs index 69ceeeb774e2e..5b49c535f8016 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs @@ -1208,7 +1208,7 @@ protected virtual void Dispose(bool disposing) _disposed = true; } - internal LdapControl[] BuildControlArray(DirectoryControlCollection controls, bool serverControl) + internal static LdapControl[] BuildControlArray(DirectoryControlCollection controls, bool serverControl) { LdapControl[] managedControls = null; @@ -1274,7 +1274,7 @@ internal LdapControl[] BuildControlArray(DirectoryControlCollection controls, bo return managedControls; } - internal LdapMod[] BuildAttributes(CollectionBase directoryAttributes, ArrayList ptrToFree) + internal static LdapMod[] BuildAttributes(CollectionBase directoryAttributes, ArrayList ptrToFree) { LdapMod[] attributes = null; @@ -1958,7 +1958,7 @@ private DirectoryException ConstructException(int error, LdapOperation operation } } - private DirectoryControl ConstructControl(IntPtr controlPtr) + private static DirectoryControl ConstructControl(IntPtr controlPtr) { LdapControl control = new LdapControl(); Marshal.PtrToStructure(controlPtr, control); @@ -1974,7 +1974,7 @@ private DirectoryControl ConstructControl(IntPtr controlPtr) return new DirectoryControl(controlType, bytes, criticality, true); } - private bool SameCredential(NetworkCredential oldCredential, NetworkCredential newCredential) + private static bool SameCredential(NetworkCredential oldCredential, NetworkCredential newCredential) { if (oldCredential == null && newCredential == null) { diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapPartialResultsProcessor.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapPartialResultsProcessor.cs index 4f5b6b37f529a..9c57a04d07655 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapPartialResultsProcessor.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapPartialResultsProcessor.cs @@ -124,7 +124,7 @@ public void RetrievingSearchResults() tmpCallback?.Invoke(asyncResult); } - private void GetResultsHelper(LdapPartialAsyncResult asyncResult) + private static void GetResultsHelper(LdapPartialAsyncResult asyncResult) { LdapConnection connection = asyncResult._con; ResultAll resultType = ResultAll.LDAP_MSG_RECEIVED; @@ -308,7 +308,7 @@ public DirectoryResponse GetCompleteResult(LdapPartialAsyncResult asyncResult) } } - private void AddResult(SearchResponse partialResults, SearchResponse newResult) + private static void AddResult(SearchResponse partialResults, SearchResponse newResult) { if (newResult == null) { diff --git a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs index c0e9780ad478f..3de255e206753 100644 --- a/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs +++ b/src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs @@ -556,7 +556,7 @@ public unsafe void StartTransportLayerSecurity(DirectoryControlCollection contro IntPtr tempPtr = IntPtr.Zero; // build server control - managedServerControls = _connection.BuildControlArray(controls, true); + managedServerControls = LdapConnection.BuildControlArray(controls, true); int structSize = Marshal.SizeOf(typeof(LdapControl)); if (managedServerControls != null) { @@ -574,7 +574,7 @@ public unsafe void StartTransportLayerSecurity(DirectoryControlCollection contro } // Build client control. - managedClientControls = _connection.BuildControlArray(controls, false); + managedClientControls = LdapConnection.BuildControlArray(controls, false); if (managedClientControls != null) { clientControlArray = Utility.AllocHGlobalIntPtrArray(managedClientControls.Length + 1); diff --git a/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj b/src/libraries/System.DirectoryServices/src/System.DirectoryServices.csproj index 409bae7e786ba..77560b036deae 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 + $(NoWarn);CA1845;CA1846;IDE0059;CA1822 enable true true diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.Unix.cs index f9c86b948d674..79e54f00e2555 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.Unix.cs @@ -37,16 +37,16 @@ namespace System.Drawing { public sealed partial class BufferedGraphicsContext : IDisposable { +#pragma warning disable CA1822 private BufferedGraphics AllocBuffer(Graphics? targetGraphics, IntPtr targetDC, Rectangle targetRectangle) { BufferedGraphics graphics = new BufferedGraphics(targetGraphics, targetDC, targetRectangle); return graphics; } +#pragma warning restore CA1822 - private void Dispose(bool disposing) - { - // Do nothing on Unix. - } + // Do nothing on Unix. + partial void Dispose(bool disposing); public void Invalidate() { 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 653f9b9ce00da..c74b1e3860001 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.cs @@ -81,7 +81,7 @@ public BufferedGraphics Allocate(IntPtr targetDC, Rectangle targetRectangle) /// /// Returns a BufferedGraphics that is matched for the specified target HDC object. /// - private BufferedGraphics AllocBufferInTempManager(Graphics? targetGraphics, IntPtr targetDC, Rectangle targetRectangle) + private static BufferedGraphics AllocBufferInTempManager(Graphics? targetGraphics, IntPtr targetDC, Rectangle targetRectangle) { BufferedGraphicsContext? tempContext = null; BufferedGraphics? tempBuffer = null; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/ClientUtils.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/ClientUtils.cs index ec731f3ba858e..ec595b11cc034 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/ClientUtils.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/ClientUtils.cs @@ -126,7 +126,7 @@ public override bool Equals(object? obj) public override int GetHashCode() => base.GetHashCode(); [return: NotNullIfNotNull("value")] - private WeakRefObject? CreateWeakRefObject(object? value) + private static WeakRefObject? CreateWeakRefObject(object? value) { if (value == null) { diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Unix.cs index c30f21eeb4bcb..86f5c105ae69d 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Unix.cs @@ -70,7 +70,7 @@ private void CreateFont(string familyName, float emSize, FontStyle style, Graphi Gdip.CheckStatus(status); } - internal void unitConversion(GraphicsUnit fromUnit, GraphicsUnit toUnit, float nSrc, out float nTrg) + internal static void unitConversion(GraphicsUnit fromUnit, GraphicsUnit toUnit, float nSrc, out float nTrg) { float inchs; nTrg = 0; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs index 396de1bce7acf..42fe50531576d 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/FontConverter.cs @@ -216,7 +216,7 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( static TypeConverter GetFloatConverter() => TypeDescriptor.GetConverter(typeof(float)); } - private (string?, string?) ParseSizeTokens(string text, char separator) + private static (string?, string?) ParseSizeTokens(string text, char separator) { string? size = null; string? units = null; @@ -257,7 +257,7 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, [NotNullWhen( return (size, units); } - private GraphicsUnit ParseGraphicsUnits(string units) => + private static GraphicsUnit ParseGraphicsUnits(string units) => units switch { "display" => GraphicsUnit.Display, diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Unix.cs index b00cb16f937ac..6667baf90962b 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Unix.cs @@ -563,7 +563,7 @@ public void GetContextInfo(out PointF offset, out Region? clip) } #endif - private void CheckErrorStatus(int status) + private static void CheckErrorStatus(int status) { Gdip.CheckStatus(status); } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Windows.cs index afba2a3306ee3..9660603292c2e 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.Windows.cs @@ -191,10 +191,8 @@ private void Dispose(bool disposing) ~Graphics() => Dispose(false); - private void FlushCore() - { - // Libgdiplus needs to synchronize a macOS context. Windows does not do anything. - } + // Libgdiplus needs to synchronize a macOS context. Windows does not do anything. + partial void FlushCore(); /// /// Represents an object used in connection with the printing API, it is used to hold a reference to a @@ -936,7 +934,7 @@ private static void OnDomainUnload(object? sender, EventArgs e) /// the desktop switch message and absorbing all the exceptions that get thrown while /// it's the secure desktop. /// - private void CheckErrorStatus(int status) + private static void CheckErrorStatus(int status) { if (status == Gdip.Ok) return; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.cs index 6120f55482902..9bcc9e52f8a80 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Graphics.cs @@ -2225,7 +2225,7 @@ public unsafe void TransformPoints(CoordinateSpace destSpace, CoordinateSpace sr /// for height || width == 1 here because transforms can be applied to /// the Graphics object making it difficult to identify this scenario. /// - private void IgnoreMetafileErrors(Image image, ref int errorStatus) + private static void IgnoreMetafileErrors(Image image, ref int errorStatus) { if (errorStatus != Gdip.Ok && image.RawFormat.Equals(ImageFormat.Emf)) errorStatus = Gdip.Ok; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Unix.cs index ba97e2636f8e3..5b53e6924c751 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Unix.cs @@ -344,7 +344,7 @@ public static Icon FromHandle(IntPtr handle) return new Icon(handle); } - private void SaveIconImage(BinaryWriter writer, IconImage ii) + private static void SaveIconImage(BinaryWriter writer, IconImage ii) { BitmapInfoHeader bih = ii.iconHeader; writer.Write(bih.biSize); @@ -371,12 +371,12 @@ private void SaveIconImage(BinaryWriter writer, IconImage ii) writer.Write(ii.iconAND!); } - private void SaveIconDump(BinaryWriter writer, IconDump id) + private static void SaveIconDump(BinaryWriter writer, IconDump id) { writer.Write(id.data!); } - private void SaveIconDirEntry(BinaryWriter writer, IconDirEntry ide, uint offset) + private static void SaveIconDirEntry(BinaryWriter writer, IconDirEntry ide, uint offset) { writer.Write(ide.width); writer.Write(ide.height); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Unix.cs index 27b994fa9d472..8879db8a8e9a3 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Image.Unix.cs @@ -116,7 +116,7 @@ public Image GetThumbnailImage(int thumbWidth, int thumbHeight, Image.GetThumbna return ThumbNail; } - internal ImageCodecInfo? FindEncoderForFormat(ImageFormat format) + internal static ImageCodecInfo? FindEncoderForFormat(ImageFormat format) { ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo? encoder = null; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/ImageConverter.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/ImageConverter.cs index 9eb684fc502a5..6b6717382c645 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/ImageConverter.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/ImageConverter.cs @@ -111,7 +111,7 @@ public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContex public override bool GetPropertiesSupported(ITypeDescriptorContext? context) => true; - private unsafe Stream? GetBitmapStream(ReadOnlySpan rawData) + private static unsafe Stream? GetBitmapStream(ReadOnlySpan rawData) { try { diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/Margins.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/Margins.cs index 05764ce8f21a1..bcf82122dc533 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/Margins.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/Margins.cs @@ -175,7 +175,7 @@ internal double DoubleBottom } } - private void CheckMargin(int margin, string name) + private static void CheckMargin(int margin, string name) { if (margin < 0) { diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Windows.cs index 24c8e0761adb2..c71ab7985cc2e 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Windows.cs @@ -1234,7 +1234,7 @@ public override string ToString() } // Write null terminated string, return length of string in characters (including null) - private short WriteOneDEVNAME(string str, IntPtr bufferStart, int index) + private static short WriteOneDEVNAME(string str, IntPtr bufferStart, int index) { if (str == null) str = ""; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.Unix.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.Unix.cs index 8cfd099273604..51e27912e286e 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.Unix.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.Unix.cs @@ -5,9 +5,7 @@ namespace System.Drawing.Text { public partial class PrivateFontCollection { - private void GdiAddFontFile(string filename) - { - // There is no GDI on Unix, only libgdiplus, so this is a no-op. - } + // There is no GDI on Unix, only libgdiplus, so this is a no-op. + partial void GdiAddFontFile(string filename); } } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.Windows.cs index e84b0bfe7405e..533cb1ebc8e79 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.Windows.cs @@ -5,7 +5,7 @@ namespace System.Drawing.Text { public partial class PrivateFontCollection { - private void GdiAddFontFile(string filename) + private static void GdiAddFontFile(string filename) { Interop.Gdi32.AddFontFile(filename); } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs index 609ccae35b8de..3a43631f526f2 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs @@ -85,7 +85,7 @@ public void AddFontFile(string filename) // Register private font with GDI as well so pure GDI-based controls (TextBox, Button for instance) can access it. // This is a no-op on Unix which has GDI+ (libgdiplus), not GDI; and we don't have System.Windows.Forms // on Unix. - this.GdiAddFontFile(filename); + GdiAddFontFile(filename); } /// diff --git a/src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Reader/CborReader.String.cs b/src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Reader/CborReader.String.cs index 6145ac0d065c9..284619e83d3d0 100644 --- a/src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Reader/CborReader.String.cs +++ b/src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Reader/CborReader.String.cs @@ -503,7 +503,7 @@ private void SkipString(CborMajorType type) AdvanceDataItemCounters(); } - private int ValidateUtf8AndGetCharCount(ReadOnlySpan buffer, Encoding utf8Encoding) + private static int ValidateUtf8AndGetCharCount(ReadOnlySpan buffer, Encoding utf8Encoding) { try { diff --git a/src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.Integer.cs b/src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.Integer.cs index 67307d59ffbb8..d70e0d616a082 100644 --- a/src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.Integer.cs +++ b/src/libraries/System.Formats.Cbor/src/System/Formats/Cbor/Writer/CborWriter.Integer.cs @@ -118,7 +118,7 @@ private void WriteUnsignedInteger(CborMajorType type, ulong value) } } - private int GetIntegerEncodingLength(ulong value) + private static int GetIntegerEncodingLength(ulong value) { if (value < (byte)CborAdditionalInfo.Additional8BitData) { diff --git a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/InputBuffer.cs b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/InputBuffer.cs index 42e3e6659e387..0fde03f8492a8 100644 --- a/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/InputBuffer.cs +++ b/src/libraries/System.IO.Compression/src/System/IO/Compression/DeflateManaged/InputBuffer.cs @@ -102,7 +102,7 @@ public uint TryLoad16Bits() return _bitBuffer; } - private uint GetBitMask(int count) => ((uint)1 << count) - 1; + private static uint GetBitMask(int count) => ((uint)1 << count) - 1; /// Gets count bits from the input buffer. Returns -1 if not enough bits available. public int GetBits(int count) diff --git a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs index 7c755536ab728..7938fe9b92b89 100644 --- a/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs +++ b/src/libraries/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.OSX.cs @@ -601,7 +601,7 @@ private WatcherChangeTypes FilterEvents(FSEventStreamEventFlags eventFlags) return eventType; } - private bool ShouldRescanOccur(FSEventStreamEventFlags flags) + private static bool ShouldRescanOccur(FSEventStreamEventFlags flags) { // Check if any bit is set that signals that the caller should rescan return (flags.HasFlag(FSEventStreamEventFlags.kFSEventStreamEventFlagMustScanSubDirs) || @@ -620,7 +620,7 @@ private bool CheckIfPathIsNested(ReadOnlySpan eventPath) return _includeChildren || _fullDirectory.AsSpan().StartsWith(System.IO.Path.GetDirectoryName(eventPath), StringComparison.OrdinalIgnoreCase); } - private int? FindRenameChangePairedChange( + private static int? FindRenameChangePairedChange( int currentIndex, Span flags, Span ids) { diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/InternalRelationshipCollection.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/InternalRelationshipCollection.cs index 6b034018d4d81..f1f2481893c58 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/InternalRelationshipCollection.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/InternalRelationshipCollection.cs @@ -357,7 +357,7 @@ private void ProcessRelationshipAttributes(XmlCompatibilityReader reader) } //If End element is present for Relationship then we process it - private void ProcessEndElementForRelationshipTag(XmlCompatibilityReader reader) + private static void ProcessEndElementForRelationshipTag(XmlCompatibilityReader reader) { Debug.Assert(!reader.IsEmptyElement, "This method should only be called if the Relationship Element is not empty"); @@ -548,14 +548,14 @@ private Uri GetResolvedTargetUri(Uri target, TargetMode targetMode) } //Throws an exception if the relationship part does not have the correct content type - private void ThrowIfIncorrectContentType(ContentType contentType) + private static void ThrowIfIncorrectContentType(ContentType contentType) { if (!contentType.AreTypeAndSubTypeEqual(PackagingUtilities.RelationshipPartContentType)) throw new FileFormatException(SR.RelationshipPartIncorrectContentType); } //Throws an exception if the xml:base attribute is present in the Relationships XML - private void ThrowIfXmlBaseAttributeIsPresent(XmlCompatibilityReader reader) + private static void ThrowIfXmlBaseAttributeIsPresent(XmlCompatibilityReader reader) { string? xmlBaseAttributeValue = reader.GetAttribute(XmlBaseAttributeName); @@ -564,7 +564,7 @@ private void ThrowIfXmlBaseAttributeIsPresent(XmlCompatibilityReader reader) } //Throws an XML exception if the attribute value is invalid - private void ThrowForInvalidAttributeValue(XmlCompatibilityReader reader, string attributeName, Exception ex) + private static void ThrowForInvalidAttributeValue(XmlCompatibilityReader reader, string attributeName, Exception ex) { throw new XmlException(SR.Format(SR.InvalidValueForTheAttribute, attributeName), ex, reader.LineNumber, reader.LinePosition); } @@ -582,7 +582,7 @@ private string GenerateUniqueRelationshipId() // Build an ID string consisting of the letter 'R' followed by an 8-byte GUID timestamp. // Guid.ToString() outputs the bytes in the big-endian order (higher order byte first) - private string GenerateRelationshipId() + private static string GenerateRelationshipId() { // The timestamp consists of the first 8 hex octets of the GUID. return string.Concat("R", Guid.NewGuid().ToString("N").Substring(0, TimestampLength)); diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackagePart.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackagePart.cs index becc0278706ef..3739ceb57ddad 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackagePart.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PackagePart.cs @@ -776,7 +776,7 @@ private void CleanUpRequestedStreamsList() //return false. These properties do not throw ObjectDisposedException. //So we rely on the values of these properties to determine if a stream //has been closed. - private bool IsStreamClosed(Stream s) + private static bool IsStreamClosed(Stream s) { return !s.CanRead && !s.CanSeek && !s.CanWrite; } diff --git a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PartBasedPackageProperties.cs b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PartBasedPackageProperties.cs index 20e59798df147..3050e34cb6b38 100644 --- a/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PartBasedPackageProperties.cs +++ b/src/libraries/System.IO.Packaging/src/System/IO/Packaging/PartBasedPackageProperties.cs @@ -631,7 +631,7 @@ internal static void ValidateXsiType(XmlReader reader, object ns, string name) } // Expect to find text data and return its value. - private string GetStringData(XmlReader reader) + private static string GetStringData(XmlReader reader) { if (reader.IsEmptyElement) return string.Empty; @@ -651,7 +651,7 @@ private string GetStringData(XmlReader reader) } // Expect to find text data and return its value as DateTime. - private Nullable GetDateData(XmlReader reader) + private static DateTime GetDateData(XmlReader reader) { string data = GetStringData(reader); DateTime dateTime; @@ -723,7 +723,7 @@ private void CreatePropertyPart() CoreDocumentPropertiesRelationshipType); } - private Uri GeneratePropertyPartUri() + private static Uri GeneratePropertyPartUri() { string propertyPartName = DefaultPropertyPartNamePrefix + Guid.NewGuid().ToString(GuidStorageFormatString) 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 36938798542a4..d8b6a25a462b2 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 @@ -442,7 +442,7 @@ internal FileMode PackageFileMode //returns a boolean indicating if the underlying zip item is a valid metro part or piece // This mainly excludes the content type item, as well as entries with leading or trailing // slashes. - private bool IsZipItemValidOpcPartOrPiece(string zipItemName) + private static bool IsZipItemValidOpcPartOrPiece(string zipItemName) { Debug.Assert(zipItemName != null, "The parameter zipItemName should not be null"); @@ -671,7 +671,6 @@ internal void SaveToFile() // if the XML is shorter than the existing content part. var contentTypefullName = _contentTypeZipArchiveEntry!.FullName; var thisArchive = _contentTypeZipArchiveEntry.Archive; - _zipStreamManager.Close(_contentTypeZipArchiveEntry); _contentTypeZipArchiveEntry.Delete(); _contentTypeZipArchiveEntry = thisArchive.CreateEntry(contentTypefullName); } @@ -899,7 +898,7 @@ private void ProcessOverrideTagAttributes(XmlReader reader) } //If End element is present for Relationship then we process it - private void ProcessEndElement(XmlReader reader, string elementName) + private static void ProcessEndElement(XmlReader reader, string elementName) { Debug.Assert(!reader.IsEmptyElement, "This method should only be called it the Relationship Element is not empty"); @@ -939,7 +938,7 @@ private void AddDefaultElement(string extension, ContentType contentType) _dirty = true; } - private void WriteOverrideElement(XmlWriter xmlWriter, PackUriHelper.ValidatedPartUri partUri, ContentType contentType) + private static void WriteOverrideElement(XmlWriter xmlWriter, PackUriHelper.ValidatedPartUri partUri, ContentType contentType) { xmlWriter.WriteStartElement(OverrideTagName); xmlWriter.WriteAttributeString(PartNameAttributeName, @@ -948,7 +947,7 @@ private void WriteOverrideElement(XmlWriter xmlWriter, PackUriHelper.ValidatedPa xmlWriter.WriteEndElement(); } - private void WriteDefaultElement(XmlWriter xmlWriter, string extension, ContentType contentType) + private static void WriteDefaultElement(XmlWriter xmlWriter, string extension, ContentType contentType) { xmlWriter.WriteStartElement(DefaultTagName); xmlWriter.WriteAttributeString(ExtensionAttributeName, extension); @@ -957,7 +956,7 @@ private void WriteDefaultElement(XmlWriter xmlWriter, string extension, ContentT } //Validate if the required XML attribute is present and not an empty string - private void ValidateXmlAttribute(string attributeName, string? attributeValue, string tagName, XmlReader reader) + private static void ValidateXmlAttribute(string attributeName, string? attributeValue, string tagName, XmlReader reader) { ThrowIfXmlAttributeMissing(attributeName, attributeValue, tagName, reader); @@ -969,7 +968,7 @@ private void ValidateXmlAttribute(string attributeName, string? attributeValue, //Validate if the required Content type XML attribute is present //Content type of a part can be empty - private void ThrowIfXmlAttributeMissing(string attributeName, string? attributeValue, string tagName, XmlReader reader) + private static void ThrowIfXmlAttributeMissing(string attributeName, string? attributeValue, string tagName, XmlReader reader) { if (attributeValue == null) throw new XmlException(SR.Format(SR.RequiredAttributeMissing, tagName, attributeName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); 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 387819ece7a53..0859e321a0342 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 @@ -86,10 +86,6 @@ public Stream Open(ZipArchiveEntry zipArchiveEntry, FileMode streamFileMode, Fil return new ZipWrappingStream(zipArchiveEntry, ns, _packageFileMode, _packageFileAccess, canRead, canWrite); } - public void Close(ZipArchiveEntry zipArchiveEntry) - { - } - // // IDisposable interface // 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 f4f0caca1c562..cefced3080152 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 @@ -226,6 +226,7 @@ internal static string GetPipePath(string serverName, string pipeName) return s_pipePrefix + pipeName; } +#pragma warning disable CA1822 /// Throws an exception if the supplied handle does not represent a valid pipe. /// The handle to validate. internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle) @@ -241,11 +242,11 @@ internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle) } } } +#pragma warning restore CA1822 /// Initializes the handle to be used asynchronously. /// The handle. - private void InitializeAsyncHandle(SafePipeHandle handle) - { } + partial void InitializeAsyncHandle(SafePipeHandle handle); internal virtual void DisposeCore(bool disposing) { @@ -455,7 +456,7 @@ internal static unsafe void CreateAnonymousPipe(out SafePipeHandle reader, out S writer.SetHandle(new IntPtr(fds[Interop.Sys.WriteEndOfPipe])); } - internal int CheckPipeCall(int result) + private int CheckPipeCall(int result) { if (result == -1) { diff --git a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs index 1a1134c7f1503..c4e404da1e7cf 100644 --- a/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs +++ b/src/libraries/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs @@ -242,7 +242,7 @@ internal static string GetPipePath(string serverName, string pipeName) /// Throws an exception if the supplied handle does not represent a valid pipe. /// The handle to validate. - internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle) + private protected static void ValidateHandleIsPipe(SafePipeHandle safePipeHandle) { // Check that this handle is infact a handle to a pipe. if (Interop.Kernel32.GetFileType(safePipeHandle) != Interop.Kernel32.FileTypes.FILE_TYPE_PIPE) 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 fd0a9b9c29bb4..651410fb8396f 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 @@ -335,6 +335,7 @@ internal StopBits StopBits } } +#pragma warning disable CA1822 internal bool DiscardNull { set @@ -350,6 +351,7 @@ internal byte ParityReplace // Ignore. } } +#pragma warning restore CA1822 internal void DiscardInBuffer() { @@ -553,7 +555,7 @@ public override IAsyncResult BeginWrite(byte[] array, int offset, int count, Asy public override void EndWrite(IAsyncResult asyncResult) => EndReadWrite(asyncResult); - private int EndReadWrite(IAsyncResult asyncResult) + private static int EndReadWrite(IAsyncResult asyncResult) { try { diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Win32.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Win32.cs index a659c0320df3e..fb91c0796e620 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Win32.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.Win32.cs @@ -8,7 +8,7 @@ namespace System.IO.Ports { internal sealed partial class SerialStream { - public SafeFileHandle OpenPort(uint portNumber) + private static SafeFileHandle OpenPort(uint portNumber) { return Interop.Kernel32.CreateFile( @"\\?\COM" + portNumber.ToString(CultureInfo.InvariantCulture), diff --git a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.cs b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.cs index c197c3c8a52b5..2a33673b59a05 100644 --- a/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.cs +++ b/src/libraries/System.IO.Ports/src/System/IO/Ports/SerialStream.cs @@ -88,7 +88,7 @@ public override void Write(byte[] array, int offset, int count) Dispose(false); } - private void CheckArrayArguments(byte[] array!!, int offset, int count) + private static void CheckArrayArguments(byte[] array!!, int offset, int count) { if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNumRequired); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs index 505b29844da4b..073071af4edf2 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs @@ -929,11 +929,6 @@ private void EmitNewArrayExpression(Expression expr) } } - private void EmitDebugInfoExpression(Expression expr) - { - return; - } - #region ListInit, MemberInit private void EmitListInitExpression(Expression expr) diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Generated.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Generated.cs index 6d476f9003771..e19756eab4db4 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Generated.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Generated.cs @@ -134,7 +134,7 @@ private void EmitExpression(Expression node, CompilationFlags flags) EmitBlockExpression(node, flags); break; case ExpressionType.DebugInfo: - EmitDebugInfoExpression(node); + // nop break; case ExpressionType.Dynamic: EmitDynamicExpression(node); diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs index cf1f973204a36..7122ddd021ea8 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InstructionList.cs @@ -226,6 +226,7 @@ public void UnEmit() _currentStackDepth += instruction.ConsumedStack; } +#pragma warning disable CA1822 /// /// Attaches a cookie to the last emitted instruction. /// @@ -239,6 +240,7 @@ public void SetDebugCookie(object? cookie) _debugCookies.Add(new KeyValuePair(Count - 1, cookie)); #endif } +#pragma warning restore CA1822 public int Count => _instructions.Count; public int CurrentStackDepth => _currentStackDepth; @@ -887,7 +889,7 @@ public void EmitLoadField(FieldInfo field) Emit(GetLoadField(field)); } - private Instruction GetLoadField(FieldInfo field) + private static Instruction GetLoadField(FieldInfo field) { lock (s_loadFields) { diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InterpretedFrame.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InterpretedFrame.cs index a8d9ccac62b5b..509d4ae8dcfe5 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InterpretedFrame.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/InterpretedFrame.cs @@ -177,7 +177,7 @@ internal string[] Trace return _parent = currentFrame; } - internal void Leave(InterpretedFrame? prevFrame) + internal static void Leave(InterpretedFrame? prevFrame) { s_currentFrame = prevFrame; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightCompiler.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightCompiler.cs index b5753f67732f1..2c9edb8c4a321 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightCompiler.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightCompiler.cs @@ -442,7 +442,7 @@ private void LoadLocalNoValueTypeCopy(ParameterExpression variable) } } - private bool MaybeMutableValueType(Type type) + private static bool MaybeMutableValueType(Type type) { return type.IsValueType && !type.IsEnum && !type.IsPrimitive; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs index 77b399b366d8d..6ab7d0b7541a0 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/LightLambda.cs @@ -422,7 +422,7 @@ internal void RunVoidRef2(ref T0 arg0, ref T1 arg1) arguments[i] = frame.Data[i]; } - frame.Leave(currentFrame); + InterpretedFrame.Leave(currentFrame); } return frame.Pop(); } @@ -446,7 +446,7 @@ internal void RunVoidRef2(ref T0 arg0, ref T1 arg1) arguments[i] = frame.Data[i]; } - frame.Leave(currentFrame); + InterpretedFrame.Leave(currentFrame); } return null; } diff --git a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSite.cs b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSite.cs index e89265ab73334..b080df42bc45e 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSite.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSite.cs @@ -171,7 +171,7 @@ private CallSite() { } - internal CallSite CreateMatchMaker() + internal static CallSite CreateMatchMaker() { return new CallSite(); } diff --git a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSiteOps.cs b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSiteOps.cs index 43a68a9325fc1..4b3fd28ffdebe 100644 --- a/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSiteOps.cs +++ b/src/libraries/System.Linq.Expressions/src/System/Runtime/CompilerServices/CallSiteOps.cs @@ -23,7 +23,7 @@ public static class CallSiteOps [Obsolete("CallSiteOps has been deprecated and is not supported.", error: true), EditorBrowsable(EditorBrowsableState.Never)] public static CallSite CreateMatchmaker(CallSite site) where T : class { - var mm = site.CreateMatchMaker(); + var mm = CallSite.CreateMatchMaker(); // CallSiteOps.ClearMatch(mm); mm._match = true; return mm; diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Channels/SynchronousChannel.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Channels/SynchronousChannel.cs index c0aed64cbeeee..a72f92dc706ae 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Channels/SynchronousChannel.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/Channels/SynchronousChannel.cs @@ -97,6 +97,7 @@ internal T Dequeue() // Signals that a producer will no longer be enqueueing items. // +#pragma warning disable CA1822 internal void SetDone() { #if DEBUG @@ -105,6 +106,7 @@ internal void SetDone() _done = true; #endif } +#pragma warning restore CA1822 //----------------------------------------------------------------------------------- // Copies the internal contents of this channel to an array. diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Binary/GroupJoinQueryOperator.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Binary/GroupJoinQueryOperator.cs index 7c07b51b24e2d..f2323f2d7ea78 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Binary/GroupJoinQueryOperator.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Binary/GroupJoinQueryOperator.cs @@ -155,12 +155,12 @@ private void WrapPartitionedStreamHelper( } } - private IComparer> CreateComparer(IComparer comparer) + private static IComparer> CreateComparer(IComparer comparer) { return CreateComparer(Comparer.Default, comparer); } - private IComparer> CreateComparer(IComparer leftKeyComparer, IComparer rightKeyComparer) + private static IComparer> CreateComparer(IComparer leftKeyComparer, IComparer rightKeyComparer) { return new PairComparer(leftKeyComparer, rightKeyComparer); } @@ -398,7 +398,7 @@ protected override Pair, Pair> CreateValu return new Pair, Pair>(baseValue._grouping, Wrap(baseValue._orderKey)); } - private Pair Wrap(TOrderKey orderKey) + private static Pair Wrap(TOrderKey orderKey) { return new Pair(true, orderKey); } diff --git a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Binary/HashJoinQueryOperatorEnumerator.cs b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Binary/HashJoinQueryOperatorEnumerator.cs index fe1114e7ed766..1223785e995f8 100644 --- a/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Binary/HashJoinQueryOperatorEnumerator.cs +++ b/src/libraries/System.Linq.Parallel/src/System/Linq/Parallel/QueryOperators/Binary/HashJoinQueryOperatorEnumerator.cs @@ -233,7 +233,7 @@ internal abstract class HashLookupBuilder { public abstract HashJoinHashLookup BuildHashLookup(CancellationToken cancellationToken); - protected void BuildBaseHashLookup( + protected static void BuildBaseHashLookup( QueryOperatorEnumerator, TBaseOrderKey> dataSource, TBaseBuilder baseHashBuilder, CancellationToken cancellationToken) where TBaseBuilder : IBaseHashBuilder diff --git a/src/libraries/System.Linq/src/System/Linq/DebugView.cs b/src/libraries/System.Linq/src/System/Linq/DebugView.cs index 5820a57c989ee..22d86b62ef88d 100644 --- a/src/libraries/System.Linq/src/System/Linq/DebugView.cs +++ b/src/libraries/System.Linq/src/System/Linq/DebugView.cs @@ -52,7 +52,11 @@ public T[] Items internal sealed class SystemCore_EnumerableDebugViewEmptyException : Exception { +#pragma warning disable CA1822 + // This property value is used by the debugger EE as the message + // displayed when a dynamic object has no members. public string Empty => SR.EmptyEnumerable; +#pragma warning restore CA1822 } internal sealed class SystemCore_EnumerableDebugView diff --git a/src/libraries/System.Management/src/System.Management.csproj b/src/libraries/System.Management/src/System.Management.csproj index 7f530935c20b4..3395d2313ca43 100644 --- a/src/libraries/System.Management/src/System.Management.csproj +++ b/src/libraries/System.Management/src/System.Management.csproj @@ -4,7 +4,7 @@ $(NoWarn);0618 - $(NoWarn);CA1845;IDE0059 + $(NoWarn);CA1845;IDE0059;CA1822 annotations true $(NetCoreAppCurrent)-windows;$(NetCoreAppCurrent);$(NetCoreAppMinimum)-windows;$(NetCoreAppMinimum);netstandard2.0 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 78acec6ee3d10..507a1beabd954 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 @@ -1584,7 +1584,7 @@ private static void SetWinHttpOption( } } - private void HandleAsyncException(WinHttpRequestState state, Exception ex) + private static void HandleAsyncException(WinHttpRequestState state, Exception ex) { Debug.Assert(state.Tcs != null); if (state.CancellationToken.IsCancellationRequested) @@ -1703,7 +1703,7 @@ private RendezvousAwaitable InternalSendRequestAsync(WinHttpRequestState st return state.LifecycleAwaitable; } - private async Task InternalSendRequestBodyAsync(WinHttpRequestState state, WinHttpChunkMode chunkedModeForSend) + private static async Task InternalSendRequestBodyAsync(WinHttpRequestState state, WinHttpChunkMode chunkedModeForSend) { Debug.Assert(state.RequestMessage != null); Debug.Assert(state.RequestMessage.Content != null); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs index 1b4ac0fce8596..6097be39fee6c 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/BrowserHttpHandler/BrowserHttpHandler.cs @@ -48,6 +48,7 @@ private static bool GetIsStreamingSupported() return (bool)streamingSupported.Call(); } +#pragma warning disable CA1822 public bool UseCookies { get => throw new PlatformNotSupportedException(); @@ -96,16 +97,6 @@ public ICredentials? Credentials set => throw new PlatformNotSupportedException(); } - public bool AllowAutoRedirect - { - get => _allowAutoRedirect; - set - { - _allowAutoRedirect = value; - _isAllowAutoRedirectTouched = true; - } - } - public int MaxAutomaticRedirections { get => throw new PlatformNotSupportedException(); @@ -129,6 +120,17 @@ public SslClientAuthenticationOptions SslOptions get => throw new PlatformNotSupportedException(); set => throw new PlatformNotSupportedException(); } +#pragma warning restore CA1822 + + public bool AllowAutoRedirect + { + get => _allowAutoRedirect; + set + { + _allowAutoRedirect = value; + _isAllowAutoRedirectTouched = true; + } + } public const bool SupportsAutomaticDecompression = false; public const bool SupportsProxy = false; 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 406afd10a87a0..a5b2be615d821 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,6 +7,7 @@ namespace System.Net.Http { internal sealed partial class HttpTelemetry { +#pragma warning disable CA1822 public void Http11RequestLeftQueue(double timeOnQueueMilliseconds) { } @@ -14,6 +15,7 @@ public void Http11RequestLeftQueue(double timeOnQueueMilliseconds) public void Http20RequestLeftQueue(double timeOnQueueMilliseconds) { } +#pragma warning restore CA1822 protected override void OnEventCommand(EventCommandEventArgs command) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs index da053cab10ba5..fbeabc8fbe3fe 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/Headers/HttpHeaders.cs @@ -575,7 +575,7 @@ internal virtual void AddHeaders(HttpHeaders sourceHeaders) } } - private HeaderStoreItemInfo CloneHeaderInfo(HeaderDescriptor descriptor, HeaderStoreItemInfo sourceInfo) + private static HeaderStoreItemInfo CloneHeaderInfo(HeaderDescriptor descriptor, HeaderStoreItemInfo sourceInfo) { var destinationInfo = new HeaderStoreItemInfo { @@ -975,7 +975,7 @@ private void PrepareHeaderInfoForAdd(HeaderDescriptor descriptor, out HeaderStor } } - private void ParseAndAddValue(HeaderDescriptor descriptor, HeaderStoreItemInfo info, string? value) + private static void ParseAndAddValue(HeaderDescriptor descriptor, HeaderStoreItemInfo info, string? value) { Debug.Assert(info != null); @@ -1226,7 +1226,7 @@ private static void ReadStoreValues(Span values, object? storeValue, } } - private bool AreEqual(object value, object? storeValue, IEqualityComparer? comparer) + private static bool AreEqual(object value, object? storeValue, IEqualityComparer? comparer) { Debug.Assert(value != null); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs index 8954931226108..a01d94ca286ed 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs @@ -815,7 +815,7 @@ private void PrepareRequestMessage(HttpRequestMessage request) return (pendingRequestsCts, DisposeTokenSource: false, pendingRequestsCts); } - private Uri? CreateUri(string? uri) => + private static Uri? CreateUri(string? uri) => string.IsNullOrEmpty(uri) ? null : new Uri(uri, UriKind.RelativeOrAbsolute); private HttpRequestMessage CreateRequestMessage(HttpMethod method, Uri? uri) => diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.InvokeNativeHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.InvokeNativeHandler.cs index a1de275aef452..c11aa3a0c323f 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.InvokeNativeHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.AnyMobile.InvokeNativeHandler.cs @@ -146,7 +146,7 @@ public partial class HttpClientHandler : HttpMessageHandler [DynamicDependency("set_Credentials", NativeHandlerType, AssemblyName)] private void SetCredentials(ICredentials? value) => InvokeNativeHandlerMethod("set_Credentials", value); - private HttpMessageHandler CreateNativeHandler() + private static HttpMessageHandler CreateNativeHandler() { if (_nativeHandlerMethod == null) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs b/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs index b968a7f966620..4dc7a1f2d3b7b 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/HttpResponseMessage.cs @@ -207,7 +207,7 @@ public override string ToString() return sb.ToString(); } - private bool ContainsNewLineCharacter(string value) + private static bool ContainsNewLineCharacter(string value) { foreach (char character in value) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.Digest.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.Digest.cs index 1037ef80b5dc0..5e5a7c741aa73 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.Digest.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/AuthenticationHelper.Digest.cs @@ -263,7 +263,7 @@ private static bool MustValueBeQuoted(string key) key.Equals(Opaque, StringComparison.OrdinalIgnoreCase) || key.Equals(Qop, StringComparison.OrdinalIgnoreCase); } - private string? GetNextKey(string data, int currentIndex, out int parsedIndex) + private static string? GetNextKey(string data, int currentIndex, out int parsedIndex) { // Skip leading space or tab. while (currentIndex < data.Length && CharIsSpaceOrTab(data[currentIndex])) @@ -318,7 +318,7 @@ private static bool MustValueBeQuoted(string key) return data.Substring(start, length); } - private string? GetNextValue(string data, int currentIndex, bool expectQuotes, out int parsedIndex) + private static string? GetNextValue(string data, int currentIndex, bool expectQuotes, out int parsedIndex) { Debug.Assert(currentIndex < data.Length && !CharIsSpaceOrTab(data[currentIndex])); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Connection.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Connection.cs index a4e224bd5b9b3..85b3b94bb27d0 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Connection.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Connection.cs @@ -656,7 +656,7 @@ void IHttpStreamHeadersHandler.OnStaticIndexedHeader(int index, ReadOnlySpan name, ReadOnlySpan value) { } } - private ReadOnlySpan GetFrameData(ReadOnlySpan frameData, bool hasPad, bool hasPriority) + private static ReadOnlySpan GetFrameData(ReadOnlySpan frameData, bool hasPad, bool hasPriority) { if (hasPad) { diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/MacProxy.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/MacProxy.cs index d907b35227213..eef5f2d4c7964 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/MacProxy.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/MacProxy.cs @@ -30,7 +30,7 @@ private static Uri GetProxyUri(string scheme, CFProxy proxy) return uriBuilder.Uri; } - public Uri? ExecuteProxyAutoConfiguration(SafeCreateHandle cfurl, CFProxy proxy) + private static Uri? ExecuteProxyAutoConfiguration(SafeCreateHandle cfurl, CFProxy proxy) { Uri? result = null; CFRunLoopRef runLoop = CFRunLoopGetCurrent(); diff --git a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs index 9fc4bab05ff11..eb9e62b30b61d 100644 --- a/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs +++ b/src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs @@ -580,7 +580,7 @@ protected internal override Task SendAsync(HttpRequestMessa return handler.SendAsync(request, cancellationToken); } - private Exception? ValidateAndNormalizeRequest(HttpRequestMessage request) + private static Exception? ValidateAndNormalizeRequest(HttpRequestMessage request) { if (request.Version.Major == 0) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs index 58d9b2029bdf0..bab09a5fb3de9 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs @@ -84,7 +84,7 @@ public HttpConnection(Socket sock, HttpEndPointListener epl, bool secure, X509Ce else { #pragma warning disable CA5359 - _sslStream = epl.Listener.CreateSslStream(new NetworkStream(sock, false), false, (t, c, ch, e) => + _sslStream = HttpListener.CreateSslStream(new NetworkStream(sock, false), false, (t, c, ch, e) => { if (c == null) { @@ -472,7 +472,7 @@ private void Unbind() { if (_contextBound) { - _epl.UnbindContext(_context); + HttpEndPointListener.UnbindContext(_context); _contextBound = false; } } 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 f385c79a651a2..351ad0c881050 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 @@ -56,7 +56,7 @@ public HttpEndPointListener(HttpListener listener, IPAddress addr, int port, boo if (secure) { _secure = secure; - _cert = _listener.LoadCertificateAndKey (addr, port); + _cert = HttpListener.LoadCertificateAndKey (addr, port); } _endpoint = new IPEndPoint(addr, port); @@ -161,7 +161,7 @@ public bool BindContext(HttpListenerContext context) return true; } - public void UnbindContext(HttpListenerContext context) + public static void UnbindContext(HttpListenerContext context) { if (context == null || context.Request == null) return; @@ -227,7 +227,7 @@ public void UnbindContext(HttpListenerContext context) return null; } - private HttpListener? MatchFromList(string? host, string path, List? list, out ListenerPrefix? prefix) + private static HttpListener? MatchFromList(string? host, string path, List? list, out ListenerPrefix? prefix) { prefix = null; if (list == null) @@ -253,7 +253,7 @@ public void UnbindContext(HttpListenerContext context) return bestMatch; } - private void AddSpecial(List list, ListenerPrefix prefix) + private static void AddSpecial(List list, ListenerPrefix prefix) { if (list == null) return; @@ -266,7 +266,7 @@ private void AddSpecial(List list, ListenerPrefix prefix) list.Add(prefix); } - private bool RemoveSpecial(List list, ListenerPrefix prefix) + private static bool RemoveSpecial(List list, ListenerPrefix prefix) { if (list == null) return false; 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 48f0f551a8947..60bfff006e2e4 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 @@ -11,12 +11,12 @@ namespace System.Net { public partial class HttpListener { - internal SslStream CreateSslStream(Stream innerStream, bool ownsStream, RemoteCertificateValidationCallback callback) + internal static SslStream CreateSslStream(Stream innerStream, bool ownsStream, RemoteCertificateValidationCallback callback) { return new SslStream(innerStream, ownsStream, callback); } - internal X509Certificate? LoadCertificateAndKey(IPAddress addr, int port) + internal static X509Certificate? LoadCertificateAndKey(IPAddress addr, int port) { // TODO https://github.com/dotnet/runtime/issues/19752: Implement functionality to read SSL certificate. return null; 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 1edd250362c0b..7a3670847451c 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 @@ -45,7 +45,7 @@ internal void ParseAuthentication(AuthenticationSchemes expectedSchemes) } } - internal IPrincipal? ParseBasicAuthentication(string authData) => + internal static IPrincipal? ParseBasicAuthentication(string authData) => TryParseBasicAuth(authData, out _, out string? username, out string? password) ? new GenericPrincipal(new HttpListenerBasicIdentity(username, password), Array.Empty()) : null; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs index 79f5013d264a2..3a9129933d2be 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs @@ -413,7 +413,7 @@ private IAsyncResult BeginGetClientCertificateCore(AsyncCallback? requestCallbac public TransportContext TransportContext => new Context(); private Uri? RequestUri => _requestUri; - private bool SupportsWebSockets => true; + private static bool SupportsWebSockets => true; private sealed class GetClientCertificateAsyncResult : LazyAsyncResult { 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 8dda744104079..8289ed6200351 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 @@ -83,7 +83,7 @@ public TimeSpan RequestQueue } } - private void ValidateTimeout(TimeSpan value) + private static void ValidateTimeout(TimeSpan value) { long timeoutValue = Convert.ToInt64(value.TotalSeconds); if (timeoutValue < 0 || timeoutValue > ushort.MaxValue) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs b/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs index 5284f810fca36..39e1f425142d7 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs @@ -225,7 +225,7 @@ public void Clear() _serviceNameCollection = null; //invalidate (readonly) ServiceNameCollection } - private string? ExtractHostname(string uriPrefix, bool allowInvalidUriStrings) + private static string? ExtractHostname(string uriPrefix, bool allowInvalidUriStrings) { if (Uri.IsWellFormedUriString(uriPrefix, UriKind.Absolute)) { @@ -262,7 +262,7 @@ public void Clear() return null; } - public string? BuildSimpleServiceName(string uriPrefix) + public static string? BuildSimpleServiceName(string uriPrefix) { string? hostname = ExtractHostname(uriPrefix, false); @@ -276,7 +276,7 @@ public void Clear() } } - public string[] BuildServiceNames(string uriPrefix) + public static string[] BuildServiceNames(string uriPrefix) { string hostname = ExtractHostname(uriPrefix, true)!; 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 577afdbf02571..ebf2b1e6e9dad 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 @@ -1457,7 +1457,7 @@ private static bool ScenarioChecksChannelBinding(bool isSecureConnection, Protec return (isSecureConnection && scenario == ProtectionScenario.TransportSelected); } - private ContextFlagsPal GetContextFlags(ExtendedProtectionPolicy policy, bool isSecureConnection) + private static ContextFlagsPal GetContextFlags(ExtendedProtectionPolicy policy, bool isSecureConnection) { ContextFlagsPal result = ContextFlagsPal.Connection; if (policy.PolicyEnforcement != PolicyEnforcement.Never) @@ -1477,7 +1477,7 @@ private ContextFlagsPal GetContextFlags(ExtendedProtectionPolicy policy, bool is } // This only works for context-destroying errors. - private HttpStatusCode HttpStatusFromSecurityStatus(SecurityStatusPalErrorCode statusErrorCode) + private static HttpStatusCode HttpStatusFromSecurityStatus(SecurityStatusPalErrorCode statusErrorCode) { if (IsCredentialFailure(statusErrorCode)) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs index c48b34667ce52..146dddd69af97 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs @@ -547,6 +547,6 @@ internal void CheckDisposed() ObjectDisposedException.ThrowIf(_isDisposed, this); } - private bool SupportsWebSockets => WebSocketProtocolComponent.IsSupported; + private static bool SupportsWebSockets => WebSocketProtocolComponent.IsSupported; } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs index 35c4adde7144c..f4767d96e5bf0 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs @@ -572,7 +572,7 @@ internal void ComputeCoreHeaders() return pinnedHeaders; } - private void FreePinnedHeaders(List? pinnedHeaders) + private static void FreePinnedHeaders(List? pinnedHeaders) { if (pinnedHeaders != null) { 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 dc95b2f0751e2..38ee04e41be35 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 @@ -875,7 +875,7 @@ public override void Dispose() } } - private void ResetFlagAndTakeLock(object lockObject, ref bool thisLockTaken) + private static void ResetFlagAndTakeLock(object lockObject, ref bool thisLockTaken) { Debug.Assert(lockObject != null, "'lockObject' MUST NOT be NULL."); thisLockTaken = false; @@ -1458,13 +1458,13 @@ protected virtual void ProcessAction_IndicateReceiveComplete( { // If an exception is thrown we know that the locks have been released, // because we enforce IWebSocketStream.CloseNetworkConnectionAsync to yield - _webSocket.ResetFlagAndTakeLock(_webSocket._thisLock, ref thisLockTaken); + ResetFlagAndTakeLock(_webSocket._thisLock, ref thisLockTaken); throw; } if (callCompleteOnCloseCompleted) { - _webSocket.ResetFlagAndTakeLock(_webSocket._thisLock, ref thisLockTaken); + ResetFlagAndTakeLock(_webSocket._thisLock, ref thisLockTaken); _webSocket.FinishOnCloseCompleted(); } } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailAddress.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailAddress.cs index ae8940ef25f92..beb6d5208fa39 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/MailAddress.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/MailAddress.cs @@ -276,8 +276,6 @@ public override int GetHashCode() return StringComparer.InvariantCultureIgnoreCase.GetHashCode(ToString()); } - private static readonly EncodedStreamFactory s_encoderFactory = new EncodedStreamFactory(); - // Encodes the full email address, folding as needed internal string Encode(int charsConsumed, bool allowUnicode) { @@ -300,7 +298,7 @@ internal string Encode(int charsConsumed, bool allowUnicode) else { //encode the displayname since it's non-ascii - encoder = s_encoderFactory.GetEncoderForHeader(_displayNameEncoding, false, charsConsumed); + encoder = EncodedStreamFactory.GetEncoderForHeader(_displayNameEncoding, false, charsConsumed); encoder.EncodeString(_displayName, _displayNameEncoding); encodedAddress = encoder.GetEncodedString(); } 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 89544c98ebfd8..0a47725f7f8dc 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 @@ -252,7 +252,7 @@ internal void EmptySendCallback(IAsyncResult result) EmptySendContext context = (EmptySendContext)result.AsyncState!; try { - context._writer.EndGetContentStream(result).Close(); + BaseWriter.EndGetContentStream(result).Close(); } catch (Exception ex) { @@ -289,7 +289,7 @@ internal IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, bool allow IAsyncResult newResult = writer.BeginGetContentStream(EmptySendCallback, new EmptySendContext(writer, result)); if (newResult.CompletedSynchronously) { - writer.EndGetContentStream(newResult).Close(); + BaseWriter.EndGetContentStream(newResult).Close(); result.InvokeCallback(); } return result; diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.Browser.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.Browser.cs index 153dbb41ddc36..0266f161b4546 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.Browser.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.Browser.cs @@ -48,7 +48,7 @@ public SmtpClient(string? host, int port) Initialize(); } - private void Initialize() + private static void Initialize() { throw new PlatformNotSupportedException(); } @@ -127,7 +127,7 @@ public string? TargetName set => throw new PlatformNotSupportedException(); } - private bool ServerSupportsEai => throw new PlatformNotSupportedException(); + private static bool ServerSupportsEai => throw new PlatformNotSupportedException(); public void Send(string from, string recipients, string? subject, string? body) => throw new PlatformNotSupportedException(); 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 769d973d39781..423896e0b82ab 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 @@ -677,7 +677,7 @@ e is AuthenticationException || } } - private bool IsSystemNetworkCredentialInCache(CredentialCache cache) + private static bool IsSystemNetworkCredentialInCache(CredentialCache cache) { // Check if SystemNetworkCredential is in given cache. foreach (NetworkCredential credential in cache) @@ -904,7 +904,7 @@ private void SendMailCallback(IAsyncResult result) { try { - _writer = _transport.EndSendMail(result); + _writer = SmtpTransport.EndSendMail(result); // If some recipients failed but not others, send the e-mail anyway, but then return the // "Non-fatal" exception reporting the failures. The sync code path does it this way. // Fatal exceptions would have thrown above at transport.EndSendMail(...) @@ -940,7 +940,7 @@ private void ConnectCallback(IAsyncResult result) { try { - _transport.EndGetConnection(result); + SmtpTransport.EndGetConnection(result); if (_cancelled) { Complete(null, result); @@ -964,7 +964,7 @@ private void ConnectCallback(IAsyncResult result) // After we've estabilished a connection and initilized ServerSupportsEai, // check all the addresses for one that contains unicode in the username/localpart. // The localpart is the only thing we cannot succesfully downgrade. - private void ValidateUnicodeRequirement(MailMessage message, MailAddressCollection recipients, bool allowUnicode) + private static void ValidateUnicodeRequirement(MailMessage message, MailAddressCollection recipients, bool allowUnicode) { // Check all recipients, to, from, sender, bcc, cc, etc... // GetSmtpAddress will throw if !allowUnicode and the username contains non-ascii diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpCommands.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpCommands.cs index 84e7d5a2fda53..e4b513d54dac1 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpCommands.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpCommands.cs @@ -33,7 +33,7 @@ internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback? callb IAsyncResult result = reader.BeginReadLine(s_onReadLine, multiResult); if (result.CompletedSynchronously) { - LineInfo info = reader.EndReadLine(result); + LineInfo info = SmtpReplyReader.EndReadLine(result); if (!(multiResult.Result is Exception)) multiResult.Result = info; multiResult.Leave(); @@ -64,7 +64,7 @@ private static void OnReadLine(IAsyncResult result) try { SmtpConnection conn = (SmtpConnection)multiResult.Context; - LineInfo info = conn.Reader!.CurrentReader!.EndReadLine(result); + LineInfo info = SmtpReplyReader.EndReadLine(result); if (!(multiResult.Result is Exception)) multiResult.Result = info; multiResult.Leave(); @@ -125,7 +125,7 @@ internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback? callb IAsyncResult readLinesResult = reader.BeginReadLines(s_onReadLines, multiResult); if (readLinesResult.CompletedSynchronously) { - LineInfo[] lines = conn.Reader.CurrentReader!.EndReadLines(readLinesResult); + LineInfo[] lines = SmtpReplyReader.EndReadLines(readLinesResult); if (!(multiResult.Result is Exception)) multiResult.Result = lines; multiResult.Leave(); @@ -152,7 +152,7 @@ private static void OnReadLines(IAsyncResult result) try { SmtpConnection conn = (SmtpConnection)multiResult.Context; - LineInfo[] lines = conn.Reader!.CurrentReader!.EndReadLines(result); + LineInfo[] lines = SmtpReplyReader.EndReadLines(result); if (!(multiResult.Result is Exception)) multiResult.Result = lines; multiResult.Leave(); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpConnection.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpConnection.cs index e883bfe897701..349c1b102d9f1 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpConnection.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpConnection.cs @@ -355,7 +355,7 @@ internal AuthenticateCallbackContext(SmtpConnection thisPtr, ISmtpAuthentication internal Authorization? _result; } - internal void EndGetConnection(IAsyncResult result) + internal static void EndGetConnection(IAsyncResult result) { ConnectAndHandshakeAsyncResult.End(result); } @@ -469,7 +469,7 @@ private void Handshake() return; } - LineInfo info = reader.EndReadLine(result); + LineInfo info = SmtpReplyReader.EndReadLine(result); if (info.StatusCode != SmtpStatusCode.ServiceReady) { @@ -500,7 +500,7 @@ private static void HandshakeCallback(IAsyncResult result) { try { - LineInfo info = thisPtr._connection.Reader!.CurrentReader!.EndReadLine(result); + LineInfo info = SmtpReplyReader.EndReadLine(result); if (info.StatusCode != SmtpStatusCode.ServiceReady) { thisPtr.InvokeCallback(new SmtpException(info.StatusCode, info.Line, true)); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpNegotiateAuthenticationModule.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpNegotiateAuthenticationModule.cs index eff8686eae236..79e4a705acd84 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpNegotiateAuthenticationModule.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpNegotiateAuthenticationModule.cs @@ -109,7 +109,7 @@ public void CloseContext(object sessionCookie) // // Returns null for failure, Base64 encoded string on // success. - private string? GetSecurityLayerOutgoingBlob(string? challenge, NTAuthentication clientContext) + private static string? GetSecurityLayerOutgoingBlob(string? challenge, NTAuthentication clientContext) { // must have a security layer challenge diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReader.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReader.cs index e82db3d7e9ebc..7887ac3c6d7f8 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReader.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReader.cs @@ -31,14 +31,14 @@ public void Close() _reader.Close(this); } - internal LineInfo[] EndReadLines(IAsyncResult result) + internal static LineInfo[] EndReadLines(IAsyncResult result) { - return _reader.EndReadLines(result); + return SmtpReplyReaderFactory.EndReadLines(result); } - internal LineInfo EndReadLine(IAsyncResult result) + internal static LineInfo EndReadLine(IAsyncResult result) { - return _reader.EndReadLine(result); + return SmtpReplyReaderFactory.EndReadLine(result); } internal LineInfo[] ReadLines() diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReaderFactory.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReaderFactory.cs index 46c08fe0f8ca4..fc44d0195bb6a 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReaderFactory.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReaderFactory.cs @@ -85,12 +85,12 @@ internal void Close(SmtpReplyReader caller) } } - internal LineInfo[] EndReadLines(IAsyncResult result) + internal static LineInfo[] EndReadLines(IAsyncResult result) { return ReadLinesAsyncResult.End(result); } - internal LineInfo EndReadLine(IAsyncResult result) + internal static LineInfo EndReadLine(IAsyncResult result) { LineInfo[] info = ReadLinesAsyncResult.End(result); if (info != null && info.Length > 0) diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs index 529a385e2a7b0..d906af286f355 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs @@ -139,9 +139,9 @@ internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCa return result; } - internal void EndGetConnection(IAsyncResult result) + internal static void EndGetConnection(IAsyncResult result) { - _connection!.EndGetConnection(result); + SmtpConnection.EndGetConnection(result); } internal IAsyncResult BeginSendMail(MailAddress sender!!, MailAddressCollection recipients!!, @@ -174,7 +174,7 @@ internal void Abort() } } - internal MailWriter EndSendMail(IAsyncResult result) + internal static MailWriter EndSendMail(IAsyncResult result) { try { diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/BaseWriter.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/BaseWriter.cs index 04193f45d7c6e..2998c9ff4226b 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/BaseWriter.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/BaseWriter.cs @@ -130,7 +130,7 @@ internal IAsyncResult BeginGetContentStream(AsyncCallback? callback, object? sta return multiResult; } - internal Stream EndGetContentStream(IAsyncResult result) + internal static Stream EndGetContentStream(IAsyncResult result) { object o = MultiAsyncResult.End(result)!; if (o is Exception e) diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/ByteEncoder.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/ByteEncoder.cs index 8c5b68e250e93..0e7f6d964c281 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/ByteEncoder.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/ByteEncoder.cs @@ -125,17 +125,17 @@ private void AppendEncodedCodepoint(byte[] bytes, int count) } } - protected bool IsSurrogatePair(string value, int i) + protected static bool IsSurrogatePair(string value, int i) { return char.IsSurrogate(value[i]) && i + 1 < value.Length && char.IsSurrogatePair(value[i], value[i + 1]); } - protected bool IsCRLF(byte[] bytes, int count) + protected static bool IsCRLF(byte[] bytes, int count) { return count == 2 && IsCRLF(bytes, 0, count); } - private bool IsCRLF(byte[] buffer, int i, int bufferSize) + private static bool IsCRLF(byte[] buffer, int i, int bufferSize) { return buffer[i] == '\r' && i + 1 < bufferSize && buffer[i + 1] == '\n'; } diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/EncodedStreamFactory.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/EncodedStreamFactory.cs index a82d3676f5ddf..5b1001c6a9ad0 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/EncodedStreamFactory.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/EncodedStreamFactory.cs @@ -5,7 +5,7 @@ namespace System.Net.Mime { - internal sealed class EncodedStreamFactory + internal static class EncodedStreamFactory { //RFC 2822: no encoded-word line should be longer than 76 characters not including the soft CRLF //since the header length is unknown (if there even is one) we're going to be slightly more conservative @@ -17,7 +17,7 @@ internal sealed class EncodedStreamFactory private const int InitialBufferSize = 1024; //use for encoding headers - internal IEncodableStream GetEncoderForHeader(Encoding encoding, bool useBase64Encoding, int headerTextLength) + internal static IEncodableStream GetEncoderForHeader(Encoding encoding, bool useBase64Encoding, int headerTextLength) { byte[] header = CreateHeader(encoding, useBase64Encoding); byte[] footer = s_footer; @@ -36,7 +36,7 @@ internal IEncodableStream GetEncoderForHeader(Encoding encoding, bool useBase64E //Create the header for what type of byte encoding is going to be used //based on the encoding type and if base64 encoding should be forced //sample header: =?utf-8?B? - private byte[] CreateHeader(Encoding encoding, bool useBase64Encoding) => + private static byte[] CreateHeader(Encoding encoding, bool useBase64Encoding) => Encoding.ASCII.GetBytes("=?" + encoding.HeaderName + "?" + (useBase64Encoding ? "B?" : "Q?")); //The footer that marks the end of a quoted string of some sort diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeBasePart.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeBasePart.cs index e3c1c36c4d6b3..627777531c1aa 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeBasePart.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeBasePart.cs @@ -36,8 +36,7 @@ internal static string EncodeHeaderValue(string value, Encoding? encoding, bool encoding ??= Encoding.GetEncoding(DefaultCharSet); - EncodedStreamFactory factory = new EncodedStreamFactory(); - IEncodableStream stream = factory.GetEncoderForHeader(encoding, base64Encoding, headerLength); + IEncodableStream stream = EncodedStreamFactory.GetEncoderForHeader(encoding, base64Encoding, headerLength); stream.EncodeString(value, encoding); return stream.GetEncodedString(); @@ -77,8 +76,7 @@ internal static string DecodeHeaderValue(string? value) byte[] buffer = Encoding.ASCII.GetBytes(subStrings[3]); int newLength; - EncodedStreamFactory encoderFactory = new EncodedStreamFactory(); - IEncodableStream s = encoderFactory.GetEncoderForHeader(Encoding.GetEncoding(charSet), base64Encoding, 0); + IEncodableStream s = EncodedStreamFactory.GetEncoderForHeader(Encoding.GetEncoding(charSet), base64Encoding, 0); newLength = s.DecodeBytes(buffer, 0, buffer.Length); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs index 4365cee08cb91..59e630cd19dc0 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs @@ -52,7 +52,7 @@ internal Collection Parts } } - internal void Complete(IAsyncResult result, Exception? e) + internal static void Complete(IAsyncResult result, Exception? e) { //if we already completed and we got called again, //it mean's that there was an exception in the callback and we @@ -99,7 +99,7 @@ internal void MimeWriterCloseCallback(IAsyncResult result) } } - private void MimeWriterCloseCallbackHandler(IAsyncResult result) + private static void MimeWriterCloseCallbackHandler(IAsyncResult result) { MimePartContext context = (MimePartContext)result.AsyncState!; ((MimeWriter)context._writer).EndClose(result); @@ -173,7 +173,7 @@ internal void ContentStreamCallback(IAsyncResult result) private void ContentStreamCallbackHandler(IAsyncResult result) { MimePartContext context = (MimePartContext)result.AsyncState!; - context._outputStream = context._writer.EndGetContentStream(result); + context._outputStream = BaseWriter.EndGetContentStream(result); context._writer = new MimeWriter(context._outputStream!, ContentType.Boundary!); if (context._partsEnumerator.MoveNext()) { @@ -246,7 +246,7 @@ internal override void Send(BaseWriter writer, bool allowUnicode) outputStream.Close(); } - internal string GetNextBoundary() + internal static string GetNextBoundary() { int b = Interlocked.Increment(ref s_boundary) - 1; return $"--boundary_{(uint)b}_{Guid.NewGuid()}"; diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs index 81de252473224..0c8095a03f8a5 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs @@ -133,7 +133,7 @@ internal void SetContent(Stream stream!!, ContentType? contentType) SetContent(stream); } - internal void Complete(IAsyncResult result, Exception? e) + internal static void Complete(IAsyncResult result, Exception? e) { //if we already completed and we got called again, //it mean's that there was an exception in the callback and we @@ -254,7 +254,7 @@ internal Stream GetEncodedStream(Stream stream) internal void ContentStreamCallbackHandler(IAsyncResult result) { MimePartContext context = (MimePartContext)result.AsyncState!; - Stream outputStream = context._writer.EndGetContentStream(result); + Stream outputStream = BaseWriter.EndGetContentStream(result); context._outputStream = GetEncodedStream(outputStream); _readCallback = new AsyncCallback(ReadCallback); diff --git a/src/libraries/System.Net.Mail/src/System/Net/Mime/SmtpDateTime.cs b/src/libraries/System.Net.Mail/src/System/Net/Mime/SmtpDateTime.cs index 106fc5540a63c..6df3c9f9fb4a6 100644 --- a/src/libraries/System.Net.Mail/src/System/Net/Mime/SmtpDateTime.cs +++ b/src/libraries/System.Net.Mail/src/System/Net/Mime/SmtpDateTime.cs @@ -184,7 +184,7 @@ public override string ToString() => // returns true if the offset is of the form [+|-]dddd and // within the range 0000 to 9959 - internal void ValidateAndGetTimeZoneOffsetValues(string offset, out bool positive, out int hours, out int minutes) + internal static void ValidateAndGetTimeZoneOffsetValues(string offset, out bool positive, out int hours, out int minutes) { Debug.Assert(!string.IsNullOrEmpty(offset), "violation of precondition: offset must not be null or empty"); Debug.Assert(offset != UnknownTimeZoneDefaultOffset, "Violation of precondition: do not pass an unknown offset"); @@ -219,7 +219,7 @@ internal void ValidateAndGetTimeZoneOffsetValues(string offset, out bool positiv } // returns true if the time zone short hand is all alphabetical characters - internal void ValidateTimeZoneShortHandValue(string value) + internal static void ValidateTimeZoneShortHandValue(string value) { // time zones can't be empty Debug.Assert(!string.IsNullOrEmpty(value), "violation of precondition: offset must not be null or empty"); @@ -235,14 +235,14 @@ internal void ValidateTimeZoneShortHandValue(string value) } // formats a date only. Does not include time zone - internal string FormatDate(DateTime value) => value.ToString("ddd, dd MMM yyyy HH:mm:ss", CultureInfo.InvariantCulture); + internal static string FormatDate(DateTime value) => value.ToString("ddd, dd MMM yyyy HH:mm:ss", CultureInfo.InvariantCulture); // parses the date and time zone // postconditions: // return value is valid DateTime representation of the Date portion of data // timeZone is the portion of data which should contain the time zone data // timeZone is NOT evaluated by ParseValue - internal DateTime ParseValue(string data, out string timeZone) + internal static DateTime ParseValue(string data, out string timeZone) { // check that there is something to parse if (string.IsNullOrEmpty(data)) @@ -309,7 +309,7 @@ internal DateTime ParseValue(string data, out string timeZone) // if this returns true, timeZone is the correct TimeSpan representation of the input // if it returns false then the time zone is unknown and so timeZone must be ignored - internal bool TryParseTimeZoneString(string timeZoneString, out TimeSpan timeZone) + internal static bool TryParseTimeZoneString(string timeZoneString, out TimeSpan timeZone) { // see if the zone is the special unspecified case, a numeric offset, or a shorthand string if (timeZoneString == UnknownTimeZoneDefaultOffset) @@ -352,7 +352,7 @@ internal bool TryParseTimeZoneString(string timeZoneString, out TimeSpan timeZon } } - internal TimeSpan ValidateAndGetSanitizedTimeSpan(TimeSpan span) + internal static TimeSpan ValidateAndGetSanitizedTimeSpan(TimeSpan span) { // sanitize the time span by removing the seconds and milliseconds. Days are not handled here TimeSpan sanitizedTimeSpan = new TimeSpan(span.Days, span.Hours, span.Minutes, 0, 0); @@ -367,7 +367,7 @@ internal TimeSpan ValidateAndGetSanitizedTimeSpan(TimeSpan span) } // precondition: span must be sanitized and within a valid range - internal string TimeSpanToOffset(TimeSpan span) + internal static string TimeSpanToOffset(TimeSpan span) { Debug.Assert(span.Seconds == 0, "Span had seconds value"); Debug.Assert(span.Milliseconds == 0, "Span had milliseconds value"); diff --git a/src/libraries/System.Net.Mail/tests/Unit/ByteEncodingTest.cs b/src/libraries/System.Net.Mail/tests/Unit/ByteEncodingTest.cs index 3486fbfe526d2..3bfef81500b4e 100644 --- a/src/libraries/System.Net.Mail/tests/Unit/ByteEncodingTest.cs +++ b/src/libraries/System.Net.Mail/tests/Unit/ByteEncodingTest.cs @@ -114,9 +114,8 @@ public void EncodeHeader_QEncoding_ShouldSplitBetweenCodepoints() [InlineData(true, "Emoji subject : 🕐🕑🕒🕓🕔🕕\r\n11")] public void EncodeString_IsSameAsEncodeBytes_IfOneByteCodepointOnLineWrap(bool useBase64Encoding, string value) { - var factory = new EncodedStreamFactory(); - IEncodableStream streamForEncodeString = factory.GetEncoderForHeader(Encoding.UTF8, useBase64Encoding, 0); - IEncodableStream streamForEncodeBytes = factory.GetEncoderForHeader(Encoding.UTF8, useBase64Encoding, 0); + IEncodableStream streamForEncodeString = EncodedStreamFactory.GetEncoderForHeader(Encoding.UTF8, useBase64Encoding, 0); + IEncodableStream streamForEncodeBytes = EncodedStreamFactory.GetEncoderForHeader(Encoding.UTF8, useBase64Encoding, 0); streamForEncodeString.EncodeString(value, Encoding.UTF8); string encodeStringResult = streamForEncodeString.GetEncodedString(); diff --git a/src/libraries/System.Net.Mail/tests/Unit/EncodedStreamFactoryTest.cs b/src/libraries/System.Net.Mail/tests/Unit/EncodedStreamFactoryTest.cs index 7c5ca50538e4f..3a9d0491a729c 100644 --- a/src/libraries/System.Net.Mail/tests/Unit/EncodedStreamFactoryTest.cs +++ b/src/libraries/System.Net.Mail/tests/Unit/EncodedStreamFactoryTest.cs @@ -11,8 +11,7 @@ public class EncodedStreamFactoryTests [Fact] public void EncodedStreamFactory_WhenAskedForEncodedStreamForHeader_WithBase64_ShouldReturnBase64Stream() { - var esf = new EncodedStreamFactory(); - IEncodableStream test = esf.GetEncoderForHeader(Encoding.UTF8, true, 5); + IEncodableStream test = EncodedStreamFactory.GetEncoderForHeader(Encoding.UTF8, true, 5); Assert.True(test is Base64Stream); } } diff --git a/src/libraries/System.Net.Mail/tests/Unit/SmtpDateTimeTest.cs b/src/libraries/System.Net.Mail/tests/Unit/SmtpDateTimeTest.cs index 66eea5dac265a..29058ce0a34be 100644 --- a/src/libraries/System.Net.Mail/tests/Unit/SmtpDateTimeTest.cs +++ b/src/libraries/System.Net.Mail/tests/Unit/SmtpDateTimeTest.cs @@ -30,9 +30,8 @@ public class SmtpDateTimeTest [Fact] public void SmtpDateTime_WithInvalidTimeZone_ShouldParseDateCorrectly() { - var smtpDt = new SmtpDateTime(DateTime.Now); string timeZoneOffset; - DateTime result = smtpDt.ParseValue(InvalidDateStringWithInvalidTimeZone, out timeZoneOffset); + DateTime result = SmtpDateTime.ParseValue(InvalidDateStringWithInvalidTimeZone, out timeZoneOffset); Assert.Equal("7M-Gte", timeZoneOffset); Assert.Equal(new DateTime(2009, 5, 17, 15, 34, 07), result); @@ -48,11 +47,10 @@ public void SmtpDateTime_WithInvalidTimeZone_ShouldParseDateCorrectly() [InlineData(InvalidDateStringWithBadDayOfWeek)] public void SmtpDateTime_InvalidInput_ShouldThrowException(string input) { - var smtpDt = new SmtpDateTime(DateTime.Now); Assert.Throws(() => { string timeZoneOffset; - DateTime results = smtpDt.ParseValue(input, out timeZoneOffset); + DateTime results = SmtpDateTime.ParseValue(input, out timeZoneOffset); }); } @@ -88,9 +86,7 @@ public void SmtpDateTime_CreatedFromDateTimeString_ShouldParseCorrectly( string expectedTimeZoneOffset, DateTimeKind expectedKind) { - var smtpDt = new SmtpDateTime(DateTime.Now); - - DateTime result = smtpDt.ParseValue(input, out string timeZoneOffset); + DateTime result = SmtpDateTime.ParseValue(input, out string timeZoneOffset); Assert.Equal(expectedYear, result.Year); Assert.Equal(expectedMonth, result.Month); @@ -112,35 +108,31 @@ public void SmtpDate_ToString_ShouldOutputCorrectDateString() [Fact] public void SmtpDate_ValidateTimeZoneShortHandValue_WithValidShortHand_ShouldReturnTrue() { - var smtpDt = new SmtpDateTime(DateTime.Now); - smtpDt.ValidateTimeZoneShortHandValue("GMT"); + SmtpDateTime.ValidateTimeZoneShortHandValue("GMT"); } [Fact] public void SmtpDate_ValidateTimeZoneShortHandValue_WithInvalidShortHand_ShouldReturnFalse() { - var smtpDt = new SmtpDateTime(DateTime.Now); - Assert.Throws(() => smtpDt.ValidateTimeZoneShortHandValue("7M-GTE")); + Assert.Throws(() => SmtpDateTime.ValidateTimeZoneShortHandValue("7M-GTE")); } [Fact] public void SmtpDate_ValidateTimeZoneOffsetValue_WithValidAndInvalidOffsets_ShouldReturnCorrectly() { - var smtpDt = new SmtpDateTime(DateTime.Now); - bool positive; int hours; int minutes; - smtpDt.ValidateAndGetTimeZoneOffsetValues("+0000", out positive, out hours, out minutes); - smtpDt.ValidateAndGetTimeZoneOffsetValues("+9959", out positive, out hours, out minutes); - smtpDt.ValidateAndGetTimeZoneOffsetValues("-9959", out positive, out hours, out minutes); - smtpDt.ValidateAndGetTimeZoneOffsetValues("+0900", out positive, out hours, out minutes); + SmtpDateTime.ValidateAndGetTimeZoneOffsetValues("+0000", out positive, out hours, out minutes); + SmtpDateTime.ValidateAndGetTimeZoneOffsetValues("+9959", out positive, out hours, out minutes); + SmtpDateTime.ValidateAndGetTimeZoneOffsetValues("-9959", out positive, out hours, out minutes); + SmtpDateTime.ValidateAndGetTimeZoneOffsetValues("+0900", out positive, out hours, out minutes); - Assert.Throws(() => smtpDt.ValidateAndGetTimeZoneOffsetValues("+0080", out positive, out hours, out minutes)); - Assert.Throws(() => smtpDt.ValidateAndGetTimeZoneOffsetValues("+-0045", out positive, out hours, out minutes)); - Assert.Throws(() => smtpDt.ValidateAndGetTimeZoneOffsetValues("+10000", out positive, out hours, out minutes)); - Assert.Throws(() => smtpDt.ValidateAndGetTimeZoneOffsetValues("-A000", out positive, out hours, out minutes)); + Assert.Throws(() => SmtpDateTime.ValidateAndGetTimeZoneOffsetValues("+0080", out positive, out hours, out minutes)); + Assert.Throws(() => SmtpDateTime.ValidateAndGetTimeZoneOffsetValues("+-0045", out positive, out hours, out minutes)); + Assert.Throws(() => SmtpDateTime.ValidateAndGetTimeZoneOffsetValues("+10000", out positive, out hours, out minutes)); + Assert.Throws(() => SmtpDateTime.ValidateAndGetTimeZoneOffsetValues("-A000", out positive, out hours, out minutes)); } [Fact] @@ -152,46 +144,41 @@ public void SmtpDate_WithCompletelyInvalidDateString_ShouldThrowException() [Fact] public void SmtpDate_TimeSpanToOffset_ShouldConvertCorrectly() { - var smtpDt = new SmtpDateTime(DateTime.Now); TimeSpan timeZone = TimeZoneInfo.Utc.GetUtcOffset(DateTime.Now); string timeZoneToString = timeZone.ToString(); - string result = smtpDt.TimeSpanToOffset(timeZone); + string result = SmtpDateTime.TimeSpanToOffset(timeZone); Assert.Equal("+0000", result); } [Fact] public void SmtpDate_TimeSpanToOffset_WithNonGmtOffset_ShouldConvertCorrectly() { - var smtpDt = new SmtpDateTime(DateTime.Now); - Assert.Equal("-0800", smtpDt.TimeSpanToOffset(new TimeSpan(-8, 0, 0))); - Assert.Equal("-1000", smtpDt.TimeSpanToOffset(new TimeSpan(-10, 0, 0))); - Assert.Equal("+1000", smtpDt.TimeSpanToOffset(new TimeSpan(10, 0, 0))); - Assert.Equal("+0400", smtpDt.TimeSpanToOffset(new TimeSpan(4, 0, 0))); + Assert.Equal("-0800", SmtpDateTime.TimeSpanToOffset(new TimeSpan(-8, 0, 0))); + Assert.Equal("-1000", SmtpDateTime.TimeSpanToOffset(new TimeSpan(-10, 0, 0))); + Assert.Equal("+1000", SmtpDateTime.TimeSpanToOffset(new TimeSpan(10, 0, 0))); + Assert.Equal("+0400", SmtpDateTime.TimeSpanToOffset(new TimeSpan(4, 0, 0))); } [Fact] public void SmtpDate_TryParseTimeZoneString_WithValidShortHand_ShouldReturnCorrectOffset() { - var smtpDt = new SmtpDateTime(DateTime.Now); TimeSpan span; - Assert.True(smtpDt.TryParseTimeZoneString("GMT", out span)); + Assert.True(SmtpDateTime.TryParseTimeZoneString("GMT", out span)); Assert.Equal(TimeSpan.Zero, span); } [Fact] public void SmtpDate_TryParseTimeZoneString_WithUnknownShortHand_ShouldReturnFalse() { - var smtpDt = new SmtpDateTime(DateTime.Now); TimeSpan span; - Assert.False(smtpDt.TryParseTimeZoneString("ABCD", out span)); + Assert.False(SmtpDateTime.TryParseTimeZoneString("ABCD", out span)); } [Fact] public void SmtpDate_TryParseTimeZoneString_WithInvalidShortHand_ShouldThrowException() { - var smtpDt = new SmtpDateTime(DateTime.Now); TimeSpan span; - Assert.Throws(() => smtpDt.TryParseTimeZoneString("7mGTE", out span)); + Assert.Throws(() => SmtpDateTime.TryParseTimeZoneString("7mGTE", out span)); } } } diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/LinuxIPInterfaceProperties.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/LinuxIPInterfaceProperties.cs index 330bc59c806ec..0e18a9b87842a 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/LinuxIPInterfaceProperties.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/LinuxIPInterfaceProperties.cs @@ -81,7 +81,7 @@ private IPAddressCollection GetDhcpServerAddresses() return new InternalIPAddressCollection(internalCollection); } - private IPAddressCollection GetWinsServerAddresses() + private static IPAddressCollection GetWinsServerAddresses() { List internalCollection = StringParsingHelpers.ParseWinsServerAddressesFromSmbConfFile(NetworkFiles.SmbConfFile); diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemIPGlobalProperties.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemIPGlobalProperties.cs index 2af54c4938ca4..17213967c7f41 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemIPGlobalProperties.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemIPGlobalProperties.cs @@ -102,7 +102,7 @@ public override IPEndPoint[] GetActiveTcpListeners() /// /// Gets the active TCP connections. Uses the native GetTcpTable API. - private unsafe List GetAllTcpConnections() + private static unsafe List GetAllTcpConnections() { uint size = 0; uint result; diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.OSX.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.OSX.cs index 2281d9804fa18..98d561df06e1b 100644 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.OSX.cs +++ b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.OSX.cs @@ -19,7 +19,7 @@ public partial class Ping private static bool NeedsConnect => false; private static bool SupportsDualMode => false; - private PingReply SendPingCore(IPAddress address, byte[] buffer, int timeout, PingOptions? options) + private static PingReply SendPingCore(IPAddress address, byte[] buffer, int timeout, PingOptions? options) => SendIcmpEchoRequestOverRawSocket(address, buffer, timeout, options); private async Task SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions? options) diff --git a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.RawSocket.cs b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.RawSocket.cs index 010b17ad08fa0..2e1b213bf7e95 100644 --- a/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.RawSocket.cs +++ b/src/libraries/System.Net.Ping/src/System/Net/NetworkInformation/Ping.RawSocket.cs @@ -21,7 +21,7 @@ public partial class Ping private const int IpV6HeaderLengthInBytes = 40; private static ushort DontFragment = OperatingSystem.IsFreeBSD() ? (ushort)IPAddress.HostToNetworkOrder((short)0x4000) : (ushort)0x4000; - private unsafe SocketConfig GetSocketConfig(IPAddress address, byte[] buffer, int timeout, PingOptions? options) + private static unsafe SocketConfig GetSocketConfig(IPAddress address, byte[] buffer, int timeout, PingOptions? options) { // Use a random value as the identifier. This doesn't need to be perfectly random // or very unpredictable, rather just good enough to avoid unexpected conflicts. @@ -58,7 +58,7 @@ private unsafe SocketConfig GetSocketConfig(IPAddress address, byte[] buffer, in }, buffer, totalLength)); } - private Socket GetRawSocket(SocketConfig socketConfig) + private static Socket GetRawSocket(SocketConfig socketConfig) { IPEndPoint ep = (IPEndPoint)socketConfig.EndPoint; AddressFamily addrFamily = ep.Address.AddressFamily; @@ -108,7 +108,7 @@ private Socket GetRawSocket(SocketConfig socketConfig) return socket; } - private bool TryGetPingReply( + private static bool TryGetPingReply( SocketConfig socketConfig, byte[] receiveBuffer, int bytesReceived, long startingTimestamp, ref int ipHeaderLength, [NotNullWhen(true)] out PingReply? reply) { @@ -232,7 +232,7 @@ private bool TryGetPingReply( return true; } - private PingReply SendIcmpEchoRequestOverRawSocket(IPAddress address, byte[] buffer, int timeout, PingOptions? options) + private static PingReply SendIcmpEchoRequestOverRawSocket(IPAddress address, byte[] buffer, int timeout, PingOptions? options) { SocketConfig socketConfig = GetSocketConfig(address, buffer, timeout, options); using (Socket socket = GetRawSocket(socketConfig)) @@ -276,7 +276,7 @@ private PingReply SendIcmpEchoRequestOverRawSocket(IPAddress address, byte[] buf } } - private async Task SendIcmpEchoRequestOverRawSocketAsync(IPAddress address, byte[] buffer, int timeout, PingOptions? options) + private static async Task SendIcmpEchoRequestOverRawSocketAsync(IPAddress address, byte[] buffer, int timeout, PingOptions? options) { SocketConfig socketConfig = GetSocketConfig(address, buffer, timeout, options); using (Socket socket = GetRawSocket(socketConfig)) 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 125f793c98c96..5c6447a0fe9f6 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 @@ -412,7 +412,7 @@ private async Task GetAddressAndSendAsync(string hostNameOrAddress, i } // Tests if the current machine supports the given ip protocol family. - private void TestIsIpSupported(IPAddress ip) + private static void TestIsIpSupported(IPAddress ip) { if (ip.AddressFamily == AddressFamily.InterNetwork && !SocketProtocolSupportPal.OSSupportsIPv4) { diff --git a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs index 1a3c86649d574..324b5bf28b131 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs @@ -554,7 +554,7 @@ private void DomainTableCleanup() } // Return number of cookies removed from the collection. - private int ExpireCollection(CookieCollection cc) + private static int ExpireCollection(CookieCollection cc) { lock (cc) { diff --git a/src/libraries/System.Net.Primitives/src/System/Net/NetworkCredential.cs b/src/libraries/System.Net.Primitives/src/System/Net/NetworkCredential.cs index da5cb26e81662..511ce703eff9e 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/NetworkCredential.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/NetworkCredential.cs @@ -151,7 +151,7 @@ public NetworkCredential GetCredential(string? host, int port, string? authentic return this; } - private string MarshalToString(SecureString sstr) + private static string MarshalToString(SecureString sstr) { if (sstr == null || sstr.Length == 0) { diff --git a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/Mock/MockStream.cs b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/Mock/MockStream.cs index fbace756f2fbd..094abba3ff48e 100644 --- a/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/Mock/MockStream.cs +++ b/src/libraries/System.Net.Quic/src/System/Net/Quic/Implementations/Mock/MockStream.cs @@ -26,7 +26,7 @@ internal MockStream(MockConnection connection, StreamState streamState, bool isI _isInitiator = isInitiator; } - private ValueTask ConnectAsync(CancellationToken cancellationToken = default) + private static ValueTask ConnectAsync(CancellationToken cancellationToken = default) { return ValueTask.CompletedTask; } diff --git a/src/libraries/System.Net.Requests/src/System/Net/CommandStream.cs b/src/libraries/System.Net.Requests/src/System/Net/CommandStream.cs index 41f22087d5a8a..cdeb99d32d603 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/CommandStream.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/CommandStream.cs @@ -130,7 +130,7 @@ protected virtual void ClearState() return null; } - protected Exception GenerateException(string message, WebExceptionStatus status, Exception? innerException) + protected static Exception GenerateException(string message, WebExceptionStatus status, Exception? innerException) { return new WebException( message, @@ -139,7 +139,7 @@ protected Exception GenerateException(string message, WebExceptionStatus status, null /* no response */ ); } - protected Exception GenerateException(FtpStatusCode code, string? statusDescription, Exception? innerException) + protected static Exception GenerateException(FtpStatusCode code, string? statusDescription, Exception? innerException) { return new WebException(SR.Format(SR.net_ftp_servererror, NetRes.GetWebStatusCodeString(code, statusDescription)), innerException, WebExceptionStatus.ProtocolError, null); 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 eb608a0456794..23ab994725ceb 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpControlStream.cs @@ -782,7 +782,7 @@ private static void GetPathInfo(GetPathOption pathOption, /// /// Formats an IP address (contained in a UInt32) to a FTP style command string /// - private string FormatAddress(IPAddress address, int Port) + private static string FormatAddress(IPAddress address, int Port) { byte[] localAddressInBytes = address.GetAddressBytes(); @@ -805,7 +805,7 @@ private string FormatAddress(IPAddress address, int Port) /// Looks something in this form: |2|1080::8:800:200C:417A|5282| /// |2|4567::0123:5678:0123:5678|0123| /// - private string FormatAddressV6(IPAddress address, int port) + private static string FormatAddressV6(IPAddress address, int port) { return "|2|" + @@ -875,7 +875,7 @@ internal string? ExitMessage /// /// Parses a response string for content length /// - private long GetContentLengthFrom213Response(string responseString) + private static long GetContentLengthFrom213Response(string responseString) { string[] parsedList = responseString.Split(' '); if (parsedList.Length < 2) @@ -1007,7 +1007,7 @@ private void TryUpdateContentLength(string str) /// /// Parses a response string for our login dir in " " /// - private string GetLoginDirectory(string str) + private static string GetLoginDirectory(string str) { int firstQuote = str.IndexOf('"'); int lastQuote = str.LastIndexOf('"'); @@ -1024,7 +1024,7 @@ private string GetLoginDirectory(string str) /// /// Parses a response string for a port number /// - private int GetPortV4(string responseString) + private static int GetPortV4(string responseString) { string[] parsedList = responseString.Split(new char[] { ' ', '(', ',', ')' }); @@ -1049,7 +1049,7 @@ private int GetPortV4(string responseString) /// /// Parses a response string for a port number /// - private int GetPortV6(string responseString) + private static int GetPortV6(string responseString) { int pos1 = responseString.LastIndexOf('('); int pos2 = responseString.LastIndexOf(')'); @@ -1118,7 +1118,7 @@ private string GetPortCommandLine(FtpWebRequest request) /// /// Formats a simple FTP command + parameter in correct pre-wire format /// - private string FormatFtpCommand(string command, string? parameter) + private static string FormatFtpCommand(string command, string? parameter) { return string.IsNullOrEmpty(parameter) ? command + "\r\n" : @@ -1130,7 +1130,7 @@ private string FormatFtpCommand(string command, string? parameter) /// This will handle either connecting to a port or listening for one /// /// - private Socket CreateFtpDataSocket(FtpWebRequest request, Socket templateSocket) + private static Socket CreateFtpDataSocket(FtpWebRequest request, 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 dbc99ae0a295c..8bbb1340665d0 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/FtpWebRequest.cs @@ -935,7 +935,7 @@ ioEx.InnerException is SocketException sEx && } } - private Exception TranslateConnectException(Exception e) + private static Exception TranslateConnectException(Exception e) { if (e is SocketException se) { diff --git a/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs b/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs index 9c140d9756930..f2306722da3c1 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/HttpWebRequest.cs @@ -1521,7 +1521,7 @@ private void CheckAbort() HttpKnownHeaderNames.LastModified }; - private bool IsWellKnownContentHeader(string header) + private static bool IsWellKnownContentHeader(string header) { foreach (string contentHeaderName in s_wellKnownContentHeaders) { diff --git a/src/libraries/System.Net.Requests/src/System/Net/HttpWebResponse.cs b/src/libraries/System.Net.Requests/src/System/Net/HttpWebResponse.cs index 824cd2ba09d28..73d7b923f2f2a 100644 --- a/src/libraries/System.Net.Requests/src/System/Net/HttpWebResponse.cs +++ b/src/libraries/System.Net.Requests/src/System/Net/HttpWebResponse.cs @@ -373,6 +373,6 @@ private void CheckDisposed() } } - private string GetHeaderValueAsString(IEnumerable values) => string.Join(", ", values); + private static string GetHeaderValueAsString(IEnumerable values) => string.Join(", ", values); } } 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 899637c97c2fb..f809cec0c696d 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 @@ -12,6 +12,8 @@ internal CipherSuitesPolicyPal(IEnumerable allowedCipherSuites) throw new PlatformNotSupportedException(SR.net_ssl_ciphersuites_policy_not_supported); } +#pragma warning disable CA1822 internal IEnumerable GetCipherSuites() => null!; +#pragma warning restore CA1822 } } diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/SafeChannelBindingHandle.cs b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/SafeChannelBindingHandle.cs index e65b0aacde225..e92ecaf3edb82 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/SafeChannelBindingHandle.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/Pal.Managed/SafeChannelBindingHandle.cs @@ -32,7 +32,7 @@ internal void SetCertHash(byte[] certHashBytes) SetCertHashLength(length); } - private byte[] GetPrefixBytes(ChannelBindingKind kind) + private static byte[] GetPrefixBytes(ChannelBindingKind kind) { Debug.Assert(kind == ChannelBindingKind.Endpoint || kind == ChannelBindingKind.Unique); return kind == ChannelBindingKind.Endpoint diff --git a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.cs b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.cs index 4c785a02bb1fa..80062232fdacc 100644 --- a/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.cs +++ b/src/libraries/System.Net.Security/src/System/Net/Security/SslStream.cs @@ -377,7 +377,7 @@ private IAsyncResult BeginAuthenticateAsServer(SslServerAuthenticationOptions ss internal IAsyncResult BeginShutdown(AsyncCallback? asyncCallback, object? asyncState) => TaskToApm.Begin(ShutdownAsync(), asyncCallback, asyncState); - internal void EndShutdown(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); + internal static void EndShutdown(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); public TransportContext TransportContext => new SslStreamContext(this); 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 ad59c2e65dbc2..776eface1d779 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 @@ -12,7 +12,9 @@ public partial class SafeSocketHandle private ThreadPoolBoundHandle? _iocpBoundHandle; private bool _skipCompletionPortOnSuccess; +#pragma warning disable CA1822 internal void SetExposed() { /* nop */ } +#pragma warning restore CA1822 internal ThreadPoolBoundHandle? IOCPBoundHandle { diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs index 4b8dd5d73e623..f688288d8dde0 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Tasks.cs @@ -1441,9 +1441,9 @@ SocketReceiveMessageFromResult IValueTaskSource. return new SocketReceiveMessageFromResult() { ReceivedBytes = bytes, RemoteEndPoint = remoteEndPoint, SocketFlags = socketFlags, PacketInformation = packetInformation }; } - private void ThrowIncorrectTokenException() => throw new InvalidOperationException(SR.InvalidOperation_IncorrectToken); + private static void ThrowIncorrectTokenException() => throw new InvalidOperationException(SR.InvalidOperation_IncorrectToken); - private void ThrowMultipleContinuationsException() => throw new InvalidOperationException(SR.InvalidOperation_MultipleContinuations); + private static void ThrowMultipleContinuationsException() => throw new InvalidOperationException(SR.InvalidOperation_MultipleContinuations); private void ThrowException(SocketError error, CancellationToken cancellationToken) { 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 a57b275a58d03..e8ecb6e499bb8 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 @@ -165,6 +165,7 @@ private static void ThrowMultiConnectNotSupported() throw new PlatformNotSupportedException(SR.net_sockets_connect_multiconnect_notsupported); } +#pragma warning disable CA1822 private Socket? GetOrCreateAcceptSocket(Socket? acceptSocket, bool unused, string propertyName, out SafeSocketHandle? handle) { // AcceptSocket is not supported on Unix. @@ -176,6 +177,7 @@ private static void ThrowMultiConnectNotSupported() handle = null; return null; } +#pragma warning restore CA1822 private static void CheckTransmitFileOptions(TransmitFileOptions flags) { diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Windows.cs index a6b58ff563c56..11a560701cf50 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.Windows.cs @@ -19,7 +19,9 @@ public partial class Socket private static CachedSerializedEndPoint? s_cachedMappedAnyV6EndPoint; private DynamicWinsockMethods? _dynamicWinsockMethods; +#pragma warning disable CA1822 internal void ReplaceHandleIfNecessaryAfterFailedConnect() { /* nop on Windows */ } +#pragma warning restore CA1822 private sealed class CachedSerializedEndPoint { 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 ea137810083a8..d03327f06293f 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 @@ -3559,7 +3559,7 @@ private void UpdateLocalEndPointOnConnect() } } - private bool IsWildcardEndPoint(EndPoint? endPoint) + private static bool IsWildcardEndPoint(EndPoint? endPoint) { if (endPoint == null) { 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 6463e0ebd562e..d4d549fe5d044 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 @@ -15,27 +15,13 @@ public partial class SocketAsyncEventArgs : EventArgs, IDisposable private SocketFlags _receivedFlags; private Action? _transferCompletionCallback; - private void InitializeInternals() - { - // No-op for *nix. - } + partial void InitializeInternals(); - private void FreeInternals() - { - // No-op for *nix. - } + partial void FreeInternals(); - private void SetupSingleBuffer() - { - // No-op for *nix. - } + partial void SetupMultipleBuffers(); - private void SetupMultipleBuffers() - { - // No-op for *nix. - } - - private void CompleteCore() { } + partial void CompleteCore(); private void AcceptCompletionCallback(IntPtr acceptedFileDescriptor, byte[] socketAddress, int socketAddressSize, SocketError socketError) { @@ -355,7 +341,7 @@ private SocketError FinishOperationAccept(Internals.SocketAddress remoteSocketAd return SocketError.Success; } - private SocketError FinishOperationConnect() + private static SocketError FinishOperationConnect() { // No-op for *nix. return SocketError.Success; @@ -366,15 +352,9 @@ private unsafe int GetSocketAddressSize() return _socketAddressSize; } - private unsafe void FinishOperationReceiveMessageFrom() - { - // No-op for *nix. - } + partial void FinishOperationReceiveMessageFrom(); - private void FinishOperationSendPackets() - { - // No-op for *nix. - } + partial void FinishOperationSendPackets(); private void CompletionCallback(int bytesTransferred, SocketFlags flags, SocketError socketError) { diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs index b4a6c31422b54..747f72752516a 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs @@ -265,7 +265,7 @@ private void CheckForBroadcast(IPAddress ipAddress) } } - private bool IsBroadcast(IPAddress address) + private static bool IsBroadcast(IPAddress address) { if (address.AddressFamily == AddressFamily.InterNetworkV6) { diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.Windows.cs index 9305d527721d3..455c17d2d2440 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.Windows.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/UnixDomainSocketEndPoint.Windows.cs @@ -12,7 +12,7 @@ public sealed partial class UnixDomainSocketEndPoint : EndPoint private static readonly int s_nativeAddressSize = s_nativePathOffset + s_nativePathLength; // sizeof(sockaddr_un) #pragma warning restore CA1802 - private SocketAddress CreateSocketAddressForSerialize() => + private static SocketAddress CreateSocketAddressForSerialize() => new SocketAddress(AddressFamily.Unix, s_nativeAddressSize); // from afunix.h: diff --git a/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.Browser.cs b/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.Browser.cs index 38fb0d0250be7..a2756eb648739 100644 --- a/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.Browser.cs +++ b/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.Browser.cs @@ -7,7 +7,7 @@ namespace System.Net { public partial class WebProxy : IWebProxy, ISerializable { - private bool IsLocal(Uri host) + private static bool IsLocal(Uri host) { if (host.IsLoopback) { diff --git a/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.NonBrowser.cs b/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.NonBrowser.cs index 33894f9145d48..8716439eac8e2 100644 --- a/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.NonBrowser.cs +++ b/src/libraries/System.Net.WebProxy/src/System/Net/WebProxy.NonBrowser.cs @@ -13,7 +13,7 @@ public partial class WebProxy : IWebProxy, ISerializable private static volatile IPAddress[]? s_localAddresses; private static int s_networkChangeRegistered; - private bool IsLocal(Uri host) + private static bool IsLocal(Uri host) { if (host.IsLoopback) { diff --git a/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/ManagedWebSocket.cs b/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/ManagedWebSocket.cs index 8d4d53134a5e1..1598778f21108 100644 --- a/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/ManagedWebSocket.cs +++ b/src/libraries/System.Net.WebSockets/src/System/Net/WebSockets/ManagedWebSocket.cs @@ -1521,7 +1521,7 @@ private void ThrowIfOperationInProgress(bool operationCompleted, [CallerMemberNa } } - private void ThrowOperationInProgress(string? methodName) => throw new InvalidOperationException(SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, methodName)); + private static void ThrowOperationInProgress(string? methodName) => throw new InvalidOperationException(SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, methodName)); /// Creates an OperationCanceledException instance, using a default message and the specified inner exception and token. private static Exception CreateOperationCanceledException(Exception innerException, CancellationToken cancellationToken = default(CancellationToken)) diff --git a/src/libraries/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs b/src/libraries/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs index a40d4cc6c73f5..73f4c3014a33b 100644 --- a/src/libraries/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs @@ -53,6 +53,7 @@ internal bool SupportsRandomAccess } } +#pragma warning disable CA1822 internal ThreadPoolBoundHandle? ThreadPoolBinding => null; internal void EnsureThreadPoolBindingInitialized() { /* nop */ } @@ -62,6 +63,7 @@ internal bool TryGetCachedLength(out long cachedLength) cachedLength = -1; return false; } +#pragma warning restore CA1822 private static SafeFileHandle Open(string path, Interop.Sys.OpenFlags flags, int mode, Func? createOpenException) diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.cs index 360b851d66271..201f52af7f853 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/ArraySortHelper.cs @@ -6,6 +6,8 @@ using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +#pragma warning disable CA1822 + namespace System.Collections.Generic { #region ArraySortHelper for single arrays diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventProvider.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventProvider.cs index ee456befca94d..b294ba0303c24 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventProvider.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventProvider.cs @@ -454,7 +454,11 @@ private static void GetSessionInfoCallback(int etwSessionId, long matchAllKeywor /// for the current process ID, calling 'action' for each session, and passing it the /// ETW session and the 'AllKeywords' the session enabled for the current provider. /// - private unsafe void GetSessionInfo(SessionInfoCallback action, ref List? sessionList) + private +#if !TARGET_WINDOWS + static +#endif + unsafe void GetSessionInfo(SessionInfoCallback action, ref List? sessionList) { // We wish the EventSource package to be legal for Windows Store applications. // Currently EnumerateTraceGuidsEx is not an allowed API, so we avoid its use here diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Windows.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Windows.cs index 969f0a40529e5..408615dedddee 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Windows.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CalendarData.Windows.cs @@ -64,7 +64,7 @@ private bool LoadCalendarDataFromSystemCore(string localeName, CalendarId calend return result; } - private void InsertOrSwapOverride(string? value, ref string[] destination) + private static void InsertOrSwapOverride(string? value, ref string[] destination) { if (value == null) return; diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/FileStatus.SetTimes.OSX.cs b/src/libraries/System.Private.CoreLib/src/System/IO/FileStatus.SetTimes.OSX.cs index 40a887e7210be..5535ea1063f40 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/FileStatus.SetTimes.OSX.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/FileStatus.SetTimes.OSX.cs @@ -35,7 +35,7 @@ internal void SetCreationTime(string path, DateTimeOffset time, bool asDirectory } } - private unsafe Interop.Error SetCreationTimeCore(string path, long seconds, long nanoseconds) + private static unsafe Interop.Error SetCreationTimeCore(string path, long seconds, long nanoseconds) { Interop.Sys.TimeSpec timeSpec = default; 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 85b01fde17d7c..7f7ba95dc3964 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 @@ -14,7 +14,7 @@ private void SetAccessOrWriteTime(string path, DateTimeOffset time, bool isAcces SetAccessOrWriteTimeCore(path, time, isAccessTime, checkCreationTime: false, asDirectory); // This is not used on these platforms, but is needed for source compat - private Interop.Error SetCreationTimeCore(string path, long seconds, long nanoseconds) => + private static Interop.Error SetCreationTimeCore(string path, long seconds, long nanoseconds) => throw new InvalidOperationException(); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/FileStatus.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/IO/FileStatus.Unix.cs index 91e67d1b9f74c..e90408a7481e2 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/FileStatus.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/FileStatus.Unix.cs @@ -312,7 +312,7 @@ internal DateTimeOffset GetLastWriteTime(ReadOnlySpan path, bool continueO internal void SetLastWriteTime(string path, DateTimeOffset time, bool asDirectory) => SetAccessOrWriteTime(path, time, isAccessTime: false, asDirectory); - private DateTimeOffset UnixTimeToDateTimeOffset(long seconds, long nanoseconds) + private static DateTimeOffset UnixTimeToDateTimeOffset(long seconds, long nanoseconds) { return DateTimeOffset.FromUnixTimeSeconds(seconds).AddTicks(nanoseconds / NanosecondsPerTick); } diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs index ffec657b3312d..53f5920b96703 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs @@ -333,9 +333,9 @@ static async ValueTask FinishReadAsync(Task readTask, byte[] localBuff } #if CORERT // TODO: https://github.com/dotnet/corert/issues/3251 - private bool HasOverriddenBeginEndRead() => true; + private static bool HasOverriddenBeginEndRead() => true; - private bool HasOverriddenBeginEndWrite() => true; + private static bool HasOverriddenBeginEndWrite() => true; #else [MethodImpl(MethodImplOptions.InternalCall)] private extern bool HasOverriddenBeginEndRead(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Number.NumberBuffer.cs b/src/libraries/System.Private.CoreLib/src/System/Number.NumberBuffer.cs index 2323f0301949c..dd7829e188a60 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Number.NumberBuffer.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Number.NumberBuffer.cs @@ -48,6 +48,7 @@ public NumberBuffer(NumberBufferKind kind, byte* digits, int digitsLength) CheckConsistency(); } +#pragma warning disable CA1822 [Conditional("DEBUG")] public void CheckConsistency() { @@ -73,6 +74,7 @@ public void CheckConsistency() #endif // DEBUG } +#pragma warning restore CA1822 public byte* GetDigitsPointer() { diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyNameParser.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyNameParser.cs index ab3be2c8f06d2..e80755dd8d382 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyNameParser.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/AssemblyNameParser.cs @@ -213,7 +213,7 @@ private Version ParseVersion(string attributeValue) return new Version(versionNumbers[0], versionNumbers[1], versionNumbers[2], versionNumbers[3]); } - private string ParseCulture(string attributeValue) + private static string ParseCulture(string attributeValue) { if (attributeValue.Equals("Neutral", StringComparison.OrdinalIgnoreCase)) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs b/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs index 8721461f4e42b..6e71fcf4e8b60 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs @@ -123,7 +123,7 @@ private static MethodInfo GetMethodMetadataDefinition(MethodInfo method) return (MethodInfo)GetMemberMetadataDefinition(method); } - private void CheckNullabilityAttributes(NullabilityInfo nullability, IList attributes) + private static void CheckNullabilityAttributes(NullabilityInfo nullability, IList attributes) { var codeAnalysisReadState = NullabilityState.Unknown; var codeAnalysisWriteState = NullabilityState.Unknown; @@ -292,7 +292,7 @@ private bool IsPublicOnly(bool isPrivate, bool isFamilyAndAssembly, bool isAssem return false; } - private NotAnnotatedStatus PopulateAnnotationInfo(IList customAttributes) + private static NotAnnotatedStatus PopulateAnnotationInfo(IList customAttributes) { foreach (CustomAttributeData attribute in customAttributes) { 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 e726194c0c0e7..9db94c31ba242 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 @@ -13,6 +13,6 @@ private PosixSignalRegistration() { } private static PosixSignalRegistration Register(PosixSignal signal, Action handler) => throw new PlatformNotSupportedException(); - private void Unregister() { } + partial void Unregister(); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelLock.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelLock.cs index 4fb1fd7700611..b0c6f57521b57 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelLock.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelLock.cs @@ -74,6 +74,7 @@ public void VerifyIsLocked() Debug.Assert((_state & LockedMask) != 0); } +#pragma warning disable CA1822 [Conditional("DEBUG")] public void VerifyIsNotLocked() { @@ -89,6 +90,7 @@ private void VerifyIsNotLockedByAnyThread() Debug.Assert(_ownerThread == null); #endif } +#pragma warning restore CA1822 [Conditional("DEBUG")] private void ResetOwnerThread() diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelMonitor.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelMonitor.cs index c9139eabd3613..3553ab9e707dd 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelMonitor.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/LowLevelMonitor.cs @@ -28,6 +28,7 @@ public void Dispose() public bool IsLocked => _ownerThread == Thread.CurrentThread; #endif +#pragma warning disable CA1822 [Conditional("DEBUG")] public void VerifyIsLocked() { @@ -51,6 +52,7 @@ private void VerifyIsNotLockedByAnyThread() Debug.Assert(_ownerThread == null); #endif } +#pragma warning restore CA1822 [Conditional("DEBUG")] private void ResetOwnerThread() diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/NativeRuntimeEventSource.PortableThreadPool.NativeSinks.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/NativeRuntimeEventSource.PortableThreadPool.NativeSinks.cs index 011f3dc45a4dd..acb1fabb885a1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/NativeRuntimeEventSource.PortableThreadPool.NativeSinks.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/NativeRuntimeEventSource.PortableThreadPool.NativeSinks.cs @@ -149,7 +149,7 @@ public unsafe void ThreadPoolWorkerThreadAdjustmentStats( } [Event(63, Level = EventLevel.Verbose, Message = Messages.IOEnqueue, Task = Tasks.ThreadPool, Opcode = Opcodes.IOEnqueue, Version = 0, Keywords = Keywords.ThreadingKeyword | Keywords.ThreadTransferKeyword)] - private unsafe void ThreadPoolIOEnqueue( + private static unsafe void ThreadPoolIOEnqueue( IntPtr NativeOverlapped, IntPtr Overlapped, bool MultiDequeues, @@ -184,7 +184,7 @@ public void ThreadPoolIOEnqueue(RegisteredWaitHandle registeredWaitHandle) } [Event(64, Level = EventLevel.Verbose, Message = Messages.IO, Task = Tasks.ThreadPool, Opcode = Opcodes.IODequeue, Version = 0, Keywords = Keywords.ThreadingKeyword | Keywords.ThreadTransferKeyword)] - private unsafe void ThreadPoolIODequeue( + private static unsafe void ThreadPoolIODequeue( IntPtr NativeOverlapped, IntPtr Overlapped, ushort ClrInstanceID = DefaultClrInstanceId) diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs index df1e7a541fbec..35c8e0376da41 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs @@ -470,6 +470,7 @@ public bool TrySetApartmentState(ApartmentState state) return SetApartmentState(state, throwOnError:false); } +#pragma warning disable CA1822 // SetApartmentStateUnchecked should pass `this` private bool SetApartmentState(ApartmentState state, bool throwOnError) { switch (state) @@ -485,6 +486,7 @@ private bool SetApartmentState(ApartmentState state, bool throwOnError) return SetApartmentStateUnchecked(state, throwOnError); } +#pragma warning disable CA1822 [Obsolete(Obsoletions.CodeAccessSecurityMessage, DiagnosticId = Obsoletions.CodeAccessSecurityDiagId, UrlFormat = Obsoletions.SharedUrlFormat)] public CompressedStack GetCompressedStack() diff --git a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.Android.cs b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.Android.cs index 9040d3ca65ce2..5853a0718b6fb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.Android.cs +++ b/src/libraries/System.Private.CoreLib/src/System/TimeZoneInfo.Unix.Android.cs @@ -265,7 +265,7 @@ public AndroidTzData() // // Once the timezone cache is populated with the IDs, we reference tzlookup id tags // to determine if an id is backwards and label it as such if they are. - private void FilterBackwardIDs(string tzFileDir, out HashSet tzLookupIDs) + private static void FilterBackwardIDs(string tzFileDir, out HashSet tzLookupIDs) { tzLookupIDs = new HashSet(); try @@ -331,7 +331,7 @@ private void LoadTzFile(string tzFileDir, Stream fs) ReadIndex(tzFileDir, fs, indexOffset, dataOffset); } - private void LoadHeader(Span buffer, out int indexOffset, out int dataOffset) + private static void LoadHeader(Span buffer, out int indexOffset, out int dataOffset) { // tzdata files are expected to start with the form of "tzdata2012f\0" depending on the year of the tzdata used which is 2012 in this example // since we're not differentiating on year, check for tzdata and the ending \0 diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs index 02de592b855fa..ef799d5265e58 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs @@ -1107,7 +1107,7 @@ private static bool CanSerializeMember(FieldInfo? field) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private bool SetIfGetOnlyCollection(DataMember memberContract) + private static bool SetIfGetOnlyCollection(DataMember memberContract) { //OK to call IsCollection here since the use of surrogated collection types is not supported in get-only scenarios if (CollectionDataContract.IsCollection(memberContract.MemberType, false /*isConstructorRequired*/) && !memberContract.MemberType.IsValueType) 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 697f9e3fcd4b3..9902146707a27 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 @@ -192,7 +192,7 @@ internal ArgBuilder GetArg(int index) return (ArgBuilder)_argList[index]; } - internal Type GetVariableType(object var) + internal static Type GetVariableType(object var) { if (var is ArgBuilder) return ((ArgBuilder)var).ArgType; @@ -367,7 +367,7 @@ internal void IfNot() InternalIf(true); } - private OpCode GetBranchCode(Cmp cmp) + private static OpCode GetBranchCode(Cmp cmp) { switch (cmp) { @@ -436,7 +436,7 @@ internal void EndIf() MarkLabel(ifState.EndIf); } - internal void VerifyParameterCount(MethodInfo methodInfo, int expectedCount) + internal static void VerifyParameterCount(MethodInfo methodInfo, int expectedCount) { if (methodInfo.GetParameters().Length != expectedCount) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ParameterCountMismatch, methodInfo.Name, methodInfo.GetParameters().Length, expectedCount))); @@ -807,7 +807,7 @@ internal void Unbox(Type type) _ilGen.Emit(OpCodes.Unbox, type); } - private OpCode GetLdindOpCode(TypeCode typeCode) => + private static OpCode GetLdindOpCode(TypeCode typeCode) => typeCode switch { TypeCode.Boolean => OpCodes.Ldind_I1, // TypeCode.Boolean: @@ -1074,7 +1074,7 @@ internal void Ldlen() _ilGen.Emit(OpCodes.Conv_I4); } - private OpCode GetLdelemOpCode(TypeCode typeCode) => + private static OpCode GetLdelemOpCode(TypeCode typeCode) => typeCode switch { TypeCode.Object => OpCodes.Ldelem_Ref, // TypeCode.Object: @@ -1121,7 +1121,7 @@ internal void Ldelema(Type arrayElementType) EmitStackTop(arrayElementType); } - private OpCode GetStelemOpCode(TypeCode typeCode) => + private static OpCode GetStelemOpCode(TypeCode typeCode) => typeCode switch { TypeCode.Object => OpCodes.Stelem_Ref, // TypeCode.Object: @@ -1282,7 +1282,7 @@ private void InternalIf(bool negate) _blockStack.Push(ifState); } - private OpCode GetConvOpCode(TypeCode typeCode) => + private static OpCode GetConvOpCode(TypeCode typeCode) => typeCode switch { TypeCode.Boolean => OpCodes.Conv_I1, // TypeCode.Boolean: @@ -1358,21 +1358,21 @@ private IfState PopIfState() } [DoesNotReturn] - private void ThrowMismatchException(object expected) + private static void ThrowMismatchException(object expected) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExpectingEnd, expected.ToString()))); } - internal void EmitSourceInstruction(string line) + internal static void EmitSourceInstruction(string line) { } - internal void EmitSourceLabel(string line) + internal static void EmitSourceLabel(string line) { } - internal void EmitSourceComment(string comment) + internal static void EmitSourceComment(string comment) { } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs index 3715ea0835569..cbeddf1ba5e53 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs @@ -854,7 +854,7 @@ internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2060:MakeGenericMethod", Justification = "The call to MakeGenericMethod is safe due to the fact that CollectionDataContractCriticalHelper.BuildIncrementCollectionCountDelegate is not annotated.")] - private MethodInfo GetBuildIncrementCollectionCountGenericDelegate(Type type) => BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(type); + private static MethodInfo GetBuildIncrementCollectionCountGenericDelegate(Type type) => BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(type); private static MethodInfo? s_buildIncrementCollectionCountDelegateMethod; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs index 99e0a48dbe916..600377f74eb81 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs @@ -220,7 +220,7 @@ private void AddKnownDataContracts(DataContractDictionary? knownDataContracts) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - internal DataContract GetDataContract(Type clrType) + internal static DataContract GetDataContract(Type clrType) { #if SUPPORT_SURROGATE if (_dataContractSurrogate == null) @@ -250,7 +250,7 @@ internal DataContract GetDataContract(Type clrType) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - internal DataContract GetMemberTypeDataContract(DataMember dataMember) + internal static DataContract GetMemberTypeDataContract(DataMember dataMember) { Type dataMemberType = dataMember.MemberType; if (dataMember.IsGetOnlyCollection) @@ -275,7 +275,7 @@ internal DataContract GetMemberTypeDataContract(DataMember dataMember) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - internal DataContract GetItemTypeDataContract(CollectionDataContract collectionContract) + internal static DataContract GetItemTypeDataContract(CollectionDataContract collectionContract) { if (collectionContract.ItemType != null) return GetDataContract(collectionContract.ItemType); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataObject.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataObject.cs index 0429b5f724603..be5723fb3b09a 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataObject.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataObject.cs @@ -168,7 +168,7 @@ public virtual void Clear() _clrTypeName = _clrAssemblyName = null; } - internal void AddQualifiedNameAttribute(ElementData element, string elementPrefix, string elementName, string elementNs, string valueName, string? valueNs) + internal static void AddQualifiedNameAttribute(ElementData element, string elementPrefix, string elementName, string elementNs, string valueName, string? valueNs) { string prefix = ExtensionDataReader.GetPrefix(valueNs); element.AddAttribute(elementPrefix, elementNs, elementName, prefix + ":" + valueName); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs index 58be047a9dd09..bb9f446bfd3d7 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs @@ -243,7 +243,7 @@ public override void Skip() } } - private bool IsElementNode(ExtensionDataNodeType nodeType) + private static bool IsElementNode(ExtensionDataNodeType nodeType) { return (nodeType == ExtensionDataNodeType.Element || nodeType == ExtensionDataNodeType.ReferencedElement || @@ -427,7 +427,7 @@ public override bool ReadAttributeValue() return false; } - private void MoveNext(IDataNode? dataNode) + private static void MoveNext(IDataNode? dataNode) { throw NotImplemented.ByDesign; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ByteArrayHelperWithString.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ByteArrayHelperWithString.cs index 06fce438e58b6..627aab205423f 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ByteArrayHelperWithString.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ByteArrayHelperWithString.cs @@ -12,7 +12,7 @@ internal sealed class ByteArrayHelperWithString : ArrayHelper { public static readonly ByteArrayHelperWithString Instance = new ByteArrayHelperWithString(); - internal void WriteArray(XmlWriter writer, byte[] array, int offset, int count) + internal static void WriteArray(XmlWriter writer, byte[] array, int offset, int count) { XmlJsonReader.CheckArray(array, offset, count); writer.WriteAttributeString(string.Empty, JsonGlobals.typeString, string.Empty, JsonGlobals.arrayString); @@ -42,12 +42,12 @@ protected override void WriteArray(XmlDictionaryWriter writer, string prefix, st WriteArray(writer, array, offset, count); } - private void ThrowConversionException(string value, string type) + private static void ThrowConversionException(string value, string type) { throw new XmlException(SR.Format(SR.XmlInvalidConversion, value, type)); } - private byte ToByte(int value) + private static byte ToByte(int value) { if (value < byte.MinValue || value > byte.MaxValue) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonCollectionDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonCollectionDataContract.cs index 0ed183e05624d..9d0a40cc5d1c9 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonCollectionDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonCollectionDataContract.cs @@ -101,7 +101,7 @@ internal JsonFormatCollectionWriterDelegate JsonFormatWriterDelegate JsonFormatCollectionWriterDelegate tempDelegate; if (DataContractSerializer.Option == SerializationOption.ReflectionOnly) { - tempDelegate = new ReflectionJsonFormatWriter().ReflectionWriteCollection; + tempDelegate = ReflectionJsonFormatWriter.ReflectionWriteCollection; } else { 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 453d2acc37ead..a824b58750e36 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 @@ -175,7 +175,7 @@ private CodeGenerator GenerateCollectionReaderHelper(CollectionDataContract coll return _ilg; } - private void BeginMethod(CodeGenerator ilg, string methodName, Type delegateType, bool allowPrivateMemberAccess) + private static void BeginMethod(CodeGenerator ilg, string methodName, Type delegateType, bool allowPrivateMemberAccess) { MethodInfo signature = JsonFormatWriterGenerator.GetInvokeMethod(delegateType); ParameterInfo[] parameters = signature.GetParameters(); @@ -257,7 +257,7 @@ private void InvokeOnDeserialized(ClassDataContract classContract) } } - private bool HasFactoryMethod(ClassDataContract classContract) + private static bool HasFactoryMethod(ClassDataContract classContract) { return Globals.TypeOfIObjectReference.IsAssignableFrom(classContract.UnderlyingType); } @@ -431,7 +431,7 @@ private int SetRequiredElements(ClassDataContract contract, byte[] requiredEleme return memberCount; } - private void SetExpectedElements(BitFlagsGenerator expectedElements, int startIndex) + private static void SetExpectedElements(BitFlagsGenerator expectedElements, int startIndex) { int memberCount = expectedElements.GetBitCount(); for (int i = startIndex; i < memberCount; i++) @@ -440,7 +440,7 @@ private void SetExpectedElements(BitFlagsGenerator expectedElements, int startIn } } - private void ResetExpectedElements(BitFlagsGenerator expectedElements, int index) + private static void ResetExpectedElements(BitFlagsGenerator expectedElements, int index) { expectedElements.Store(index, false); } 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 9e7a3d9ffcd3c..8b2f232608acb 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 @@ -115,7 +115,7 @@ internal JsonFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionD return (JsonFormatCollectionWriterDelegate)_ilg.EndMethod(); } - private void BeginMethod(CodeGenerator ilg, string methodName, Type delegateType, bool allowPrivateMemberAccess) + private static void BeginMethod(CodeGenerator ilg, string methodName, Type delegateType, bool allowPrivateMemberAccess) { MethodInfo signature = GetInvokeMethod(delegateType); ParameterInfo[] parameters = signature.GetParameters(); @@ -317,7 +317,6 @@ private LocalBuilder LoadMemberValue(DataMember member) private void WriteCollection(CollectionDataContract collectionContract) { LocalBuilder itemName = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemName"); - _ilg.Load(_contextArg); _ilg.LoadMember(JsonFormatGeneratorStatics.CollectionItemNameProperty); _ilg.Store(itemName); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonWriterDelegator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonWriterDelegator.cs index eab7d2e6c28e6..d14a3847c3ffe 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonWriterDelegator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonWriterDelegator.cs @@ -33,7 +33,7 @@ internal override void WriteBase64(byte[]? bytes) return; } - ByteArrayHelperWithString.Instance.WriteArray(Writer, bytes, 0, bytes.Length); + ByteArrayHelperWithString.WriteArray(Writer, bytes, 0, bytes.Length); } internal override void WriteQName(XmlQualifiedName value) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonXmlDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonXmlDataContract.cs index ecf614876b9a2..ccb4323c3f6aa 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonXmlDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonXmlDataContract.cs @@ -56,7 +56,7 @@ public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object ob jsonWriter.WriteString(serialized); } - private List GetKnownTypesFromContext(XmlObjectSerializerContext? context, IList? serializerKnownTypeList) + private static List GetKnownTypesFromContext(XmlObjectSerializerContext? context, IList? serializerKnownTypeList) { List knownTypesList = new List(); if (context != null) 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 f4c03527b97ce..a65a474052d72 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 @@ -25,7 +25,7 @@ public void ReflectionWriteClass(XmlWriterDelegator xmlWriter, object obj, XmlOb } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract collectionContract) + public static void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract collectionContract) { JsonWriterDelegator? jsonWriter = xmlWriter as JsonWriterDelegator; if (jsonWriter == null) @@ -33,7 +33,7 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, throw new ArgumentException(nameof(xmlWriter)); } - XmlDictionaryString itemName = context.CollectionItemName; + XmlDictionaryString itemName = XmlObjectSerializerWriteContextComplexJson.CollectionItemName; if (collectionContract.Kind == CollectionKind.Array) { @@ -47,9 +47,9 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); for (int i = 0; i < array.Length; ++i) { - _reflectionClassWriter.ReflectionWriteStartElement(jsonWriter, itemName); - _reflectionClassWriter.ReflectionWriteValue(jsonWriter, context, itemType, array.GetValue(i), false, primitiveContract); - _reflectionClassWriter.ReflectionWriteEndElement(jsonWriter); + ReflectionJsonClassWriter.ReflectionWriteStartElement(jsonWriter, itemName); + ReflectionJsonClassWriter.ReflectionWriteValue(jsonWriter, context, itemType, array.GetValue(i), false, primitiveContract); + ReflectionJsonClassWriter.ReflectionWriteEndElement(jsonWriter); } } } @@ -75,9 +75,9 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, object current = enumerator.Current; object key = ((IKeyValue)current).Key!; object value = ((IKeyValue)current).Value!; - _reflectionClassWriter.ReflectionWriteStartElement(jsonWriter, key.ToString()!); - _reflectionClassWriter.ReflectionWriteValue(jsonWriter, context, dictionaryValueType ?? value.GetType(), value, false, primitiveContractForParamType: null); - _reflectionClassWriter.ReflectionWriteEndElement(jsonWriter); + ReflectionJsonClassWriter.ReflectionWriteStartElement(jsonWriter, key.ToString()!); + ReflectionJsonClassWriter.ReflectionWriteValue(jsonWriter, context, dictionaryValueType ?? value.GetType(), value, false, primitiveContractForParamType: null); + ReflectionJsonClassWriter.ReflectionWriteEndElement(jsonWriter); } } else @@ -111,24 +111,24 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, { object current = enumerator.Current; context.IncrementItemCount(1); - _reflectionClassWriter.ReflectionWriteStartElement(jsonWriter, itemName); + ReflectionJsonClassWriter.ReflectionWriteStartElement(jsonWriter, itemName); if (isDictionary) { jsonDataContract!.WriteJsonValue(jsonWriter, current, context, collectionContract.ItemType.TypeHandle); } else { - _reflectionClassWriter.ReflectionWriteValue(jsonWriter, context, elementType, current, false, primitiveContractForParamType: null); + ReflectionJsonClassWriter.ReflectionWriteValue(jsonWriter, context, elementType, current, false, primitiveContractForParamType: null); } - _reflectionClassWriter.ReflectionWriteEndElement(jsonWriter); + ReflectionJsonClassWriter.ReflectionWriteEndElement(jsonWriter); } } } } } - private void ReflectionWriteObjectAttribute(XmlWriterDelegator xmlWriter) + private static void ReflectionWriteObjectAttribute(XmlWriterDelegator xmlWriter) { xmlWriter.WriteAttributeString( prefix: null, @@ -138,7 +138,7 @@ private void ReflectionWriteObjectAttribute(XmlWriterDelegator xmlWriter) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private bool ReflectionTryWritePrimitiveArray(JsonWriterDelegator jsonWriter, object obj, Type underlyingType, Type itemType, XmlDictionaryString collectionItemName) + private static bool ReflectionTryWritePrimitiveArray(JsonWriterDelegator jsonWriter, object obj, Type underlyingType, Type itemType, XmlDictionaryString collectionItemName) { PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) @@ -182,7 +182,7 @@ private bool ReflectionTryWritePrimitiveArray(JsonWriterDelegator jsonWriter, ob return true; } - private void ReflectionWriteArrayAttribute(XmlWriterDelegator xmlWriter) + private static void ReflectionWriteArrayAttribute(XmlWriterDelegator xmlWriter) { xmlWriter.WriteAttributeString( prefix: null, @@ -272,17 +272,17 @@ protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, obje return memberCount; } - public void ReflectionWriteStartElement(XmlWriterDelegator xmlWriter, XmlDictionaryString name) + public static void ReflectionWriteStartElement(XmlWriterDelegator xmlWriter, XmlDictionaryString name) { xmlWriter.WriteStartElement(name, null); } - public void ReflectionWriteStartElement(XmlWriterDelegator xmlWriter, string name) + public static void ReflectionWriteStartElement(XmlWriterDelegator xmlWriter, string name) { xmlWriter.WriteStartElement(name, null); } - public void ReflectionWriteEndElement(XmlWriterDelegator xmlWriter) + public static void ReflectionWriteEndElement(XmlWriterDelegator xmlWriter) { xmlWriter.WriteEndElement(); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs index a43cb274d4cda..fe7ad57494eb4 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs @@ -112,7 +112,7 @@ protected override IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator return dataNode; } - private IDataNode ReadNumericalPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader) + private static IDataNode ReadNumericalPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader) { TypeCode type; object numericalValue = JsonObjectDataContract.ParseJsonNumber(xmlReader.ReadContentAsString(), out type); @@ -186,7 +186,7 @@ internal override void ReadAttributes(XmlReaderDelegator xmlReader) xmlReader.MoveToElement(); } - internal string TrimNamespace(string serverTypeNamespace) + internal static string TrimNamespace(string serverTypeNamespace) { if (!string.IsNullOrEmpty(serverTypeNamespace)) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerWriteContextComplexJson.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerWriteContextComplexJson.cs index f107c5b7c56d3..117f37afdcb96 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerWriteContextComplexJson.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerWriteContextComplexJson.cs @@ -136,7 +136,7 @@ private static bool RequiresJsonTypeInfo(DataContract contract) return (contract is ClassDataContract); } - private void WriteTypeInfo(XmlWriterDelegator writer, string typeInformation) + private static void WriteTypeInfo(XmlWriterDelegator writer, string typeInformation) { writer.WriteAttributeString(null, JsonGlobals.serverTypeString, null, typeInformation); } @@ -158,7 +158,7 @@ protected override void WriteNull(XmlWriterDelegator xmlWriter) DataContractJsonSerializer.WriteJsonNull(xmlWriter); } - internal XmlDictionaryString CollectionItemName + internal static XmlDictionaryString CollectionItemName { get { return JsonGlobals.itemDictionaryString; } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/MemoryStreamAdapter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/MemoryStreamAdapter.cs index 812f59e72834a..6970b81acba6a 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/MemoryStreamAdapter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/MemoryStreamAdapter.cs @@ -9,9 +9,11 @@ namespace System.Runtime.Serialization [DataContract(Name = nameof(MarshalByRefObject), Namespace = Globals.DataContractXsdBaseNamespace + "System")] internal abstract class MarshalByRefObjectAdapter { +#pragma warning disable CA1822 // never used, but must be first in the hierarchy in order to maintain NetFX compat [DataMember(Name = "__identity", Order = 0)] public object? Identity { get { return null; } set { } } +#pragma warning restore CA1822 } /// diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs index f7513edfd6720..f255598035af0 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs @@ -104,13 +104,13 @@ public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, Xml xmlWriter.WriteAnyType(obj); } - protected object HandleReadValue(object obj, XmlObjectSerializerReadContext context) + protected static object HandleReadValue(object obj, XmlObjectSerializerReadContext context) { context.AddNewObject(obj); return obj; } - protected bool TryReadNullAtTopLevel(XmlReaderDelegator reader) + protected static bool TryReadNullAtTopLevel(XmlReaderDelegator reader) { Attributes attributes = new Attributes(); attributes.Read(reader); @@ -847,7 +847,7 @@ public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObj public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { object obj; - if (reader.IsEmptyElement) + if (XmlReaderDelegator.IsEmptyElement) { reader.Skip(); obj = new object(); 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 c52ee9c696991..3cc3c97a7261e 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 @@ -40,7 +40,7 @@ public void ReflectionWriteClass(XmlWriterDelegator xmlWriter, object obj, XmlOb } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public void ReflectionWriteValue(XmlWriterDelegator xmlWriter, XmlObjectSerializerWriteContext context, Type type, object? value, bool writeXsiType, PrimitiveDataContract? primitiveContractForParamType) + public static void ReflectionWriteValue(XmlWriterDelegator xmlWriter, XmlObjectSerializerWriteContext context, Type type, object? value, bool writeXsiType, PrimitiveDataContract? primitiveContractForParamType) { Type memberType = type; object? memberValue = value; @@ -106,13 +106,13 @@ public void ReflectionWriteValue(XmlWriterDelegator xmlWriter, XmlObjectSerializ [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] protected abstract int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, ClassDataContract derivedMostClassContract, int childElementIndex, XmlDictionaryString[]? memberNames); - protected object? ReflectionGetMemberValue(object obj, DataMember dataMember) + protected static object? ReflectionGetMemberValue(object obj, DataMember dataMember) { return dataMember.Getter(obj); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - protected bool ReflectionTryWritePrimitive(XmlWriterDelegator xmlWriter, XmlObjectSerializerWriteContext context, Type type, object? value, XmlDictionaryString name, XmlDictionaryString? ns, PrimitiveDataContract? primitiveContract) + protected static bool ReflectionTryWritePrimitive(XmlWriterDelegator xmlWriter, XmlObjectSerializerWriteContext context, Type type, object? value, XmlDictionaryString name, XmlDictionaryString? ns, PrimitiveDataContract? primitiveContract) { if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject) return false; @@ -144,7 +144,7 @@ private void InvokeOnSerialized(object obj, XmlObjectSerializerWriteContext cont } } - private object ResolveAdapterType(object obj, ClassDataContract classContract) + private static object ResolveAdapterType(object obj, ClassDataContract classContract) { Type type = obj.GetType(); if (type == Globals.TypeOfDateTimeOffset) @@ -164,7 +164,7 @@ private object ResolveAdapterType(object obj, ClassDataContract classContract) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private void ReflectionInternalSerialize(XmlWriterDelegator xmlWriter, XmlObjectSerializerWriteContext context, object obj, bool isDeclaredType, bool writeXsiType, Type memberType, bool isNullableOfT = false) + private static void ReflectionInternalSerialize(XmlWriterDelegator xmlWriter, XmlObjectSerializerWriteContext context, object obj, bool isDeclaredType, bool writeXsiType, Type memberType, bool isNullableOfT = false) { if (isNullableOfT) { 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 95b868eda105d..dcffdbcb31383 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 @@ -32,7 +32,7 @@ private static MethodInfo CollectionSetItemDelegateMethod { if (s_getCollectionSetItemDelegateMethod == null) { - s_getCollectionSetItemDelegateMethod = typeof(ReflectionReader).GetMethod(nameof(GetCollectionSetItemDelegate), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)!; + s_getCollectionSetItemDelegateMethod = typeof(ReflectionReader).GetMethod(nameof(GetCollectionSetItemDelegate), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!; } return s_getCollectionSetItemDelegateMethod!; } @@ -152,7 +152,7 @@ private object ReadCollectionItems(XmlReaderDelegator xmlReader, XmlObjectSerial Type itemType = collectionContract.ItemType; CollectionReadItemDelegate collectionReadItemDelegate = GetCollectionReadItemDelegate(collectionContract); MethodInfo getCollectionSetItemDelegateMethod = CollectionSetItemDelegateMethod.MakeGenericMethod(itemType); - CollectionSetItemDelegate collectionSetItemDelegate = (CollectionSetItemDelegate)getCollectionSetItemDelegateMethod.Invoke(this, new object[] { collectionContract, resultCollection, isReadOnlyCollection })!; + CollectionSetItemDelegate collectionSetItemDelegate = (CollectionSetItemDelegate)getCollectionSetItemDelegateMethod.Invoke(null, new object[] { collectionContract, resultCollection, isReadOnlyCollection })!; int index = 0; while (true) @@ -359,12 +359,12 @@ private CollectionReadItemDelegate GetReflectionReadValueDelegate(Type type) }; } - private object? ReflectionGetMemberValue(object obj, DataMember dataMember) + private static object? ReflectionGetMemberValue(object obj, DataMember dataMember) { return dataMember.Getter(obj); } - private void ReflectionSetMemberValue(ref object obj, object? memberValue, DataMember dataMember) + private static void ReflectionSetMemberValue(ref object obj, object? memberValue, DataMember dataMember) { dataMember.Setter(ref obj, memberValue); } @@ -406,7 +406,7 @@ private void InvokeOnDeserialized(XmlObjectSerializerReadContext context, ClassD } } - private void InvokeDeserializationCallback(object obj) + private static void InvokeDeserializationCallback(object obj) { var deserializationCallbackObject = obj as IDeserializationCallback; deserializationCallbackObject?.OnDeserialization(null); @@ -443,7 +443,7 @@ private static object ResolveAdapterObject(object obj, ClassDataContract classCo return obj; } - private bool IsArrayLikeInterface(CollectionDataContract collectionContract) + private static bool IsArrayLikeInterface(CollectionDataContract collectionContract) { if (collectionContract.UnderlyingType.IsInterface) { @@ -461,13 +461,13 @@ private bool IsArrayLikeInterface(CollectionDataContract collectionContract) return false; } - private bool IsArrayLikeCollection(CollectionDataContract collectionContract) + private static bool IsArrayLikeCollection(CollectionDataContract collectionContract) { return collectionContract.Kind == CollectionKind.Array || IsArrayLikeInterface(collectionContract); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private object ReflectionCreateCollection(CollectionDataContract collectionContract) + private static object ReflectionCreateCollection(CollectionDataContract collectionContract) { if (IsArrayLikeCollection(collectionContract)) { @@ -514,7 +514,7 @@ private object ReflectionCreateCollection(CollectionDataContract collectionContr return ((KeyValue)o).Value; } - private CollectionSetItemDelegate GetCollectionSetItemDelegate(CollectionDataContract collectionContract, object resultCollectionObject, bool isReadOnlyCollection) + private static CollectionSetItemDelegate GetCollectionSetItemDelegate(CollectionDataContract collectionContract, object resultCollectionObject, bool isReadOnlyCollection) { if (isReadOnlyCollection && collectionContract.Kind == CollectionKind.Array) { @@ -613,7 +613,7 @@ private CollectionSetItemDelegate GetCollectionSetItemDelegate(CollectionData } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private 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 type, 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 db84e5793c4d2..6350fc0c4db34 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 @@ -22,7 +22,7 @@ public void ReflectionWriteClass(XmlWriterDelegator xmlWriter, object obj, XmlOb } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract collectionDataContract) + public static void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract collectionDataContract) { XmlDictionaryString ns = collectionDataContract.Namespace; XmlDictionaryString itemName = collectionDataContract.CollectionItemName; @@ -42,9 +42,9 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); for (int i = 0; i < array.Length; ++i) { - _reflectionClassWriter.ReflectionWriteStartElement(xmlWriter, itemType, ns, ns.Value, itemName.Value, 0); - _reflectionClassWriter.ReflectionWriteValue(xmlWriter, context, itemType, array.GetValue(i), false, primitiveContract); - _reflectionClassWriter.ReflectionWriteEndElement(xmlWriter); + ReflectionXmlClassWriter.ReflectionWriteStartElement(xmlWriter, itemType, ns, ns.Value, itemName.Value, 0); + ReflectionXmlClassWriter.ReflectionWriteValue(xmlWriter, context, itemType, array.GetValue(i), false, primitiveContract); + ReflectionXmlClassWriter.ReflectionWriteEndElement(xmlWriter); } } } @@ -72,24 +72,24 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, { object current = enumerator.Current; context.IncrementItemCount(1); - _reflectionClassWriter.ReflectionWriteStartElement(xmlWriter, elementType, ns, ns.Value, itemName.Value, 0); + ReflectionXmlClassWriter.ReflectionWriteStartElement(xmlWriter, elementType, ns, ns.Value, itemName.Value, 0); if (isDictionary) { collectionDataContract.ItemContract.WriteXmlValue(xmlWriter, current, context); } else { - _reflectionClassWriter.ReflectionWriteValue(xmlWriter, context, elementType, current, false, primitiveContractForParamType: null); + ReflectionXmlClassWriter.ReflectionWriteValue(xmlWriter, context, elementType, current, false, primitiveContractForParamType: null); } - _reflectionClassWriter.ReflectionWriteEndElement(xmlWriter); + ReflectionXmlClassWriter.ReflectionWriteEndElement(xmlWriter); } } } } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private bool ReflectionTryWritePrimitiveArray(XmlWriterDelegator xmlWriter, object obj, Type type, Type itemType, XmlDictionaryString collectionItemName, XmlDictionaryString itemNamespace) + private static bool ReflectionTryWritePrimitiveArray(XmlWriterDelegator xmlWriter, object obj, Type type, Type itemType, XmlDictionaryString collectionItemName, XmlDictionaryString itemNamespace) { PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) @@ -201,7 +201,7 @@ protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, obje return memberCount; } - public 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, int nameIndex) { bool needsPrefix = NeedsPrefix(type, ns); @@ -215,17 +215,17 @@ public void ReflectionWriteStartElement(XmlWriterDelegator xmlWriter, Type type, } } - public void ReflectionWriteEndElement(XmlWriterDelegator xmlWriter) + public static void ReflectionWriteEndElement(XmlWriterDelegator xmlWriter) { xmlWriter.WriteEndElement(); } - private bool NeedsPrefix(Type type, XmlDictionaryString? ns) + private static bool NeedsPrefix(Type type, XmlDictionaryString? ns) { return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0); } - private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract) + private static bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract) { // Check for conflict with base type members if (CheckIfConflictingMembersHaveDifferentTypes(member)) @@ -252,7 +252,7 @@ private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract class return false; } - private bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member) + private static bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member) { while (member.ConflictingMember != null) { 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 47c2ee4241fa5..3b44b607be609 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 @@ -138,7 +138,7 @@ private void ExportClassDataContract(ClassDataContract classDataContract, XmlSch XmlSchemaElement element = new XmlSchemaElement(); element.Name = dataMember.Name; XmlElement? actualTypeElement = null; - DataContract memberTypeContract = _dataContractSet.GetMemberTypeDataContract(dataMember); + DataContract memberTypeContract = DataContractSet.GetMemberTypeDataContract(dataMember); if (CheckIfMemberHasConflict(dataMember)) { element.SchemaTypeName = AnytypeQualifiedName; @@ -178,7 +178,7 @@ private void ExportClassDataContract(ClassDataContract classDataContract, XmlSch type.Annotation = GetSchemaAnnotation(genericInfoElement, ExportSurrogateData(classDataContract), isValueTypeElement); } - private void AddReferenceAttributes(XmlSchemaObjectCollection attributes, XmlSchema schema) + private static void AddReferenceAttributes(XmlSchemaObjectCollection attributes, XmlSchema schema) { SchemaHelper.AddSchemaImport(Globals.SerializationNamespace, schema); schema.Namespaces.Add(Globals.SerPrefixForSchema, Globals.SerializationNamespace); @@ -186,7 +186,7 @@ private void AddReferenceAttributes(XmlSchemaObjectCollection attributes, XmlSch attributes.Add(RefAttribute); } - private void SetElementType(XmlSchemaElement element, DataContract dataContract, XmlSchema schema) + private static void SetElementType(XmlSchemaElement element, DataContract dataContract, XmlSchema schema) { XmlDataContract? xmlDataContract = dataContract as XmlDataContract; if (xmlDataContract != null && xmlDataContract.IsAnonymous) @@ -204,7 +204,7 @@ private void SetElementType(XmlSchemaElement element, DataContract dataContract, } } - private bool CheckIfMemberHasConflict(DataMember dataMember) + private static bool CheckIfMemberHasConflict(DataMember dataMember) { if (dataMember.HasConflictingNameAndType) return true; @@ -338,7 +338,7 @@ private XmlElement ExportGenericInfo(Type clrType, string elementName, string el return typeElement; } - private XmlElement? ExportSurrogateData(object key) + private static XmlElement? ExportSurrogateData(object key) { // IDataContractSurrogate is not available on NetCore. return null; @@ -372,7 +372,7 @@ private void ExportCollectionDataContract(CollectionDataContract collectionDataC { XmlSchemaElement keyValueElement = new XmlSchemaElement(); keyValueElement.Name = dataMember.Name; - SetElementType(keyValueElement, _dataContractSet.GetMemberTypeDataContract(dataMember), schema); + SetElementType(keyValueElement, DataContractSet.GetMemberTypeDataContract(dataMember), schema); SchemaHelper.AddElementForm(keyValueElement, schema); if (dataMember.IsNullable) keyValueElement.IsNillable = true; @@ -386,7 +386,7 @@ private void ExportCollectionDataContract(CollectionDataContract collectionDataC { if (collectionDataContract.IsItemTypeNullable) element.IsNillable = true; - DataContract itemContract = _dataContractSet.GetItemTypeDataContract(collectionDataContract); + DataContract itemContract = DataContractSet.GetItemTypeDataContract(collectionDataContract); SetElementType(element, itemContract, schema); } SchemaHelper.AddElementForm(element, schema); @@ -474,7 +474,7 @@ private void ExportISerializableDataContract(ClassDataContract dataContract, Xml type.Annotation = GetSchemaAnnotation(genericInfoElement, ExportSurrogateData(dataContract), isValueTypeElement); } - private XmlSchemaComplexContentExtension CreateTypeContent(XmlSchemaComplexType type, XmlQualifiedName baseTypeName, XmlSchema schema) + private static XmlSchemaComplexContentExtension CreateTypeContent(XmlSchemaComplexType type, XmlQualifiedName baseTypeName, XmlSchema schema) { SchemaHelper.AddSchemaImport(baseTypeName.Namespace, schema); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs index 6ed9cbfe99ea7..cfda1922155de 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs @@ -48,7 +48,7 @@ public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, Xml } [MethodImpl(MethodImplOptions.NoInlining)] - private object GetUninitializedObject( + private static object GetUninitializedObject( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type objType) { 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 c6f0149d31f79..50ed91a7377f4 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 @@ -65,7 +65,7 @@ private sealed class CriticalHelper private ArgBuilder? _collectionContractArg; [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private XmlFormatClassReaderDelegate CreateReflectionXmlClassReader(ClassDataContract classContract) + private static XmlFormatClassReaderDelegate CreateReflectionXmlClassReader(ClassDataContract classContract) { return new ReflectionXmlClassReader(classContract).ReflectionReadClass; } @@ -161,7 +161,7 @@ public XmlFormatClassReaderDelegate GenerateClassReader(ClassDataContract classC } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private XmlFormatCollectionReaderDelegate CreateReflectionXmlCollectionReader() + private static XmlFormatCollectionReaderDelegate CreateReflectionXmlCollectionReader() { return new ReflectionXmlCollectionReader().ReflectionReadCollection; } @@ -184,7 +184,7 @@ public XmlFormatCollectionReaderDelegate GenerateCollectionReader(CollectionData } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private XmlFormatGetOnlyCollectionReaderDelegate CreateReflectionReadGetOnlyCollectionReader() + private static XmlFormatGetOnlyCollectionReaderDelegate CreateReflectionReadGetOnlyCollectionReader() { return new ReflectionXmlCollectionReader().ReflectionReadGetOnlyCollection; } @@ -316,7 +316,7 @@ private void InvokeOnDeserialized(ClassDataContract classContract) } } - private bool HasFactoryMethod(ClassDataContract classContract) + private static bool HasFactoryMethod(ClassDataContract classContract) { return Globals.TypeOfIObjectReference.IsAssignableFrom(classContract.UnderlyingType); } 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 c0793409e7bd8..165e0abc780e5 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 @@ -60,7 +60,7 @@ private sealed class CriticalHelper private int _childElementIndex; [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private XmlFormatClassWriterDelegate CreateReflectionXmlFormatClassWriterDelegate() + private static XmlFormatClassWriterDelegate CreateReflectionXmlFormatClassWriterDelegate() { return new ReflectionXmlFormatWriter().ReflectionWriteClass; } @@ -98,9 +98,9 @@ internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract clas } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private XmlFormatCollectionWriterDelegate CreateReflectionXmlFormatCollectionWriterDelegate() + private static XmlFormatCollectionWriterDelegate CreateReflectionXmlFormatCollectionWriterDelegate() { - return new ReflectionXmlFormatWriter().ReflectionWriteCollection; + return ReflectionXmlFormatWriter.ReflectionWriteCollection; } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] @@ -713,7 +713,7 @@ private LocalBuilder UnwrapNullableObject(LocalBuilder memberValue)// Leaves !Ha return memberValue; } - private bool NeedsPrefix(Type type, XmlDictionaryString ns) + private static bool NeedsPrefix(Type type, XmlDictionaryString ns) { return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0); } @@ -743,7 +743,7 @@ private void WriteEndElement() _ilg.Call(_xmlWriterArg, XmlFormatGeneratorStatics.WriteEndElementMethod); } - private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract) + private static bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract) { // Check for conflict with base type members if (CheckIfConflictingMembersHaveDifferentTypes(member)) @@ -770,7 +770,7 @@ private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract class return false; } - private bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member) + private static bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member) { while (member.ConflictingMember != null) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs index 499d1044f80b2..1398b7d136815 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs @@ -179,7 +179,7 @@ internal void WriteEndObjectHandleExceptions(XmlWriterDelegator writer!!) } } - internal void WriteRootElement(XmlWriterDelegator writer, DataContract contract, XmlDictionaryString? name, XmlDictionaryString? ns, bool needsContractNsAtRoot) + internal static void WriteRootElement(XmlWriterDelegator writer, DataContract contract, XmlDictionaryString? name, XmlDictionaryString? ns, bool needsContractNsAtRoot) { if (name == null) // root name not set explicitly { @@ -197,7 +197,7 @@ internal void WriteRootElement(XmlWriterDelegator writer, DataContract contract, } } - internal bool CheckIfNeedsContractNsAtRoot(XmlDictionaryString? name, XmlDictionaryString? ns, DataContract contract) + internal static bool CheckIfNeedsContractNsAtRoot(XmlDictionaryString? name, XmlDictionaryString? ns, DataContract contract) { if (name == null) return false; @@ -320,18 +320,18 @@ internal bool IsStartObjectHandleExceptions(XmlReaderDelegator reader!!) } } - internal bool IsRootXmlAny(XmlDictionaryString? rootName, DataContract contract) + internal static bool IsRootXmlAny(XmlDictionaryString? rootName, DataContract contract) { return (rootName == null) && !contract.HasRoot; } - internal bool IsStartElement(XmlReaderDelegator reader) + internal static bool IsStartElement(XmlReaderDelegator reader) { return (reader.MoveToElement() || reader.IsStartElement()); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - internal bool IsRootElement(XmlReaderDelegator reader, DataContract contract, XmlDictionaryString? name, XmlDictionaryString? ns) + internal static bool IsRootElement(XmlReaderDelegator reader, DataContract contract, XmlDictionaryString? name, XmlDictionaryString? ns) { reader.MoveToElement(); if (name != null) // root name set explicitly 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 59e475d9e0164..f4998ac25bdb2 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 @@ -983,7 +983,7 @@ private IDataNode ReadAndResolveUnknownXmlData(XmlReaderDelegator xmlReader, IDi } } - private bool IsContentNode(XmlNodeType nodeType) + private static bool IsContentNode(XmlNodeType nodeType) { switch (nodeType) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContextComplex.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContextComplex.cs index 1dd59e61baed3..53f4021549ec1 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContextComplex.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContextComplex.cs @@ -141,7 +141,7 @@ internal override SerializationMode Mode return obj; } - private Type ResolveDataContractTypeInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly) + private static Type ResolveDataContractTypeInSharedTypeMode(string assemblyName, string typeName, out Assembly assembly) { // The method is used only when _mode == SerializationMode.SharedType. // _mode is set to SerializationMode.SharedType only when the context is for NetDataContractSerializer. diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs index 5c333f6e3e8af..437aea1d441fd 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs @@ -501,7 +501,7 @@ private static void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object o } [MethodImpl(MethodImplOptions.NoInlining)] - internal void GetObjectData(ISerializable obj, SerializationInfo serInfo, StreamingContext context) + internal static void GetObjectData(ISerializable obj, SerializationInfo serInfo, StreamingContext context) { obj.GetObjectData(serInfo, context); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs index c5649a3ea09c3..54d9cd0fa2d56 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs @@ -53,7 +53,7 @@ internal string GetAttribute(int i) return reader.GetAttribute(i); } - internal bool IsEmptyElement + internal static bool IsEmptyElement { get { return false; } } @@ -202,7 +202,7 @@ internal void ReadEndElement() reader.ReadEndElement(); } - private Exception CreateInvalidPrimitiveTypeException(Type type) + private static Exception CreateInvalidPrimitiveTypeException(Type type) { return new InvalidDataContractException(SR.Format( type.IsInterface ? SR.InterfaceTypeCannotBeCreated : SR.InvalidPrimitiveType_Serialization, @@ -335,7 +335,7 @@ private void ThrowConversionException(string value, string type) } [DoesNotReturn] - private void ThrowNotAtElement() + private static void ThrowNotAtElement() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.XmlStartElementExpected, "EndElement"))); } @@ -467,7 +467,7 @@ public virtual byte[] ReadContentAsBase64() } [return: NotNullIfNotNull("str")] - internal byte[]? ReadContentAsBase64(string? str) + internal static byte[]? ReadContentAsBase64(string? str) { if (str == null) return null; @@ -776,17 +776,17 @@ private XmlQualifiedName ParseQualifiedName(string str) return new XmlQualifiedName(name, ns); } - private void CheckExpectedArrayLength(XmlObjectSerializerReadContext context, int arrayLength) + private static void CheckExpectedArrayLength(XmlObjectSerializerReadContext context, int arrayLength) { context.IncrementItemCount(arrayLength); } - protected int GetArrayLengthQuota(XmlObjectSerializerReadContext context) + protected static int GetArrayLengthQuota(XmlObjectSerializerReadContext context) { return Math.Min(context.RemainingItemCount, int.MaxValue); } - private void CheckActualArrayLength(int expectedLength, int actualLength, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) + private static void CheckActualArrayLength(int expectedLength, int actualLength, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { if (expectedLength != actualLength) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayExceededSizeAttribute, expectedLength, itemName.Value, itemNamespace.Value))); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs index 98a44843b6a4d..c18286bd6c5bc 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs @@ -266,7 +266,7 @@ internal void WriteNamespaceDecl(XmlDictionaryString ns) WriteXmlnsAttribute(ns); } - private Exception CreateInvalidPrimitiveTypeException(Type type) + private static Exception CreateInvalidPrimitiveTypeException(Type type) { return new InvalidDataContractException(SR.Format(SR.InvalidPrimitiveType_Serialization, DataContract.GetClrTypeFullName(type))); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs index 8e6837bbd28d3..cb5b347f35d96 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs @@ -50,7 +50,7 @@ private XmlSchemaSet GetSchemaSet() return _schemas; } - private DataContractSet DataContractSet + private static DataContractSet DataContractSet { get { @@ -61,23 +61,9 @@ private DataContractSet DataContractSet } } - private void TraceExportBegin() - { - } - - private void TraceExportEnd() - { - } - - private void TraceExportError(Exception exception) - { - } - [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public void Export(ICollection assemblies!!) { - TraceExportBegin(); - DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { @@ -93,20 +79,16 @@ public void Export(ICollection assemblies!!) Export(); } - catch (Exception ex) + catch { _dataContractSet = oldValue; - TraceExportError(ex); throw; } - TraceExportEnd(); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public void Export(ICollection types!!) { - TraceExportBegin(); - DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { @@ -119,33 +101,27 @@ public void Export(ICollection types!!) Export(); } - catch (Exception ex) + catch { _dataContractSet = oldValue; - TraceExportError(ex); throw; } - TraceExportEnd(); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] public void Export(Type type!!) { - TraceExportBegin(); - DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { AddType(type); Export(); } - catch (Exception ex) + catch { _dataContractSet = oldValue; - TraceExportError(ex); throw; } - TraceExportEnd(); } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] @@ -188,7 +164,7 @@ public XmlQualifiedName GetSchemaTypeName(Type type!!) } } - private Type GetSurrogatedType(Type type) + private static Type GetSurrogatedType(Type type) { #if SUPPORT_SURROGATE IDataContractSurrogate dataContractSurrogate; @@ -199,7 +175,7 @@ private Type GetSurrogatedType(Type type) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private void CheckAndAddType(Type type) + private static void CheckAndAddType(Type type) { type = GetSurrogatedType(type); if (!type.ContainsGenericParameters && DataContract.IsTypeSerializable(type)) @@ -207,7 +183,7 @@ private void CheckAndAddType(Type type) } [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] - private void AddType(Type type) + private static void AddType(Type type) { DataContractSet.Add(type); } @@ -263,10 +239,9 @@ public bool CanExport(ICollection assemblies!!) _dataContractSet = oldValue; return false; } - catch (Exception ex) + catch { _dataContractSet = oldValue; - TraceExportError(ex); throw; } } @@ -291,10 +266,9 @@ public bool CanExport(ICollection types!!) _dataContractSet = oldValue; return false; } - catch (Exception ex) + catch { _dataContractSet = oldValue; - TraceExportError(ex); throw; } } @@ -314,10 +288,9 @@ public bool CanExport(Type type!!) _dataContractSet = oldValue; return false; } - catch (Exception ex) + catch { _dataContractSet = oldValue; - TraceExportError(ex); throw; } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Text/Base64Encoding.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Text/Base64Encoding.cs index 33145ae8df9d5..8cac5e6aa2307 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Text/Base64Encoding.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Text/Base64Encoding.cs @@ -41,13 +41,13 @@ public override int GetMaxByteCount(int charCount) return charCount / 4 * 3; } - private bool IsValidLeadBytes(int v1, int v2, int v3, int v4) + private static bool IsValidLeadBytes(int v1, int v2, int v3, int v4) { // First two chars of a four char base64 sequence can't be ==, and must be valid return ((v1 | v2) < 64) && ((v3 | v4) != 0xFF); } - private bool IsValidTailBytes(int v3, int v4) + private static bool IsValidTailBytes(int v3, int v4) { // If the third char is = then the fourth char must be = return !(v3 == 64 && v4 != 64); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs index 065175d4e655c..aabb0c693ce9c 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs @@ -1902,7 +1902,7 @@ private void SignStartElement(XmlSigningNodeWriter writer) writer.WriteStartElement(prefixBuffer, prefixOffset, prefixLength, localNameBuffer, localNameOffset, localNameLength); } - private void SignAttribute(XmlSigningNodeWriter writer, XmlAttributeNode attributeNode) + private static void SignAttribute(XmlSigningNodeWriter writer, XmlAttributeNode attributeNode) { QNameType qnameType = attributeNode.QNameType; if (qnameType == QNameType.Normal) @@ -2676,7 +2676,7 @@ public int Compare(object? obj1, object? obj2) return i; } - public int CompareQNameType(QNameType type1, QNameType type2) + public static int CompareQNameType(QNameType type1, QNameType type2) { return (int)type1 - (int)type2; } @@ -2950,7 +2950,7 @@ public Namespace AddNamespace() return null; } - private bool TryGetShortPrefix(string s, out PrefixHandleType shortPrefix) + private static bool TryGetShortPrefix(string s, out PrefixHandleType shortPrefix) { int length = s.Length; if (length == 0) 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 f67c2c12c8c1f..4e29c32ed3f1e 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs @@ -110,7 +110,7 @@ protected bool IsClosed } [DoesNotReturn] - protected void ThrowClosed() + protected static void ThrowClosed() { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlWriterClosed)); } @@ -717,7 +717,7 @@ protected void StartComment() FlushElement(); } - protected void EndComment() + protected static void EndComment() { } @@ -756,32 +756,32 @@ protected void StartContent(char[] chars, int offset, int count) VerifyWhitespace(chars, offset, count); } - private void VerifyWhitespace(char ch) + private static void VerifyWhitespace(char ch) { if (!IsWhitespace(ch)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlIllegalOutsideRoot)); } - private void VerifyWhitespace(string s) + private static void VerifyWhitespace(string s) { for (int i = 0; i < s.Length; i++) if (!IsWhitespace(s[i])) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlIllegalOutsideRoot)); } - private void VerifyWhitespace(char[] chars, int offset, int count) + private static void VerifyWhitespace(char[] chars, int offset, int count) { for (int i = 0; i < count; i++) if (!IsWhitespace(chars[offset + i])) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlIllegalOutsideRoot)); } - private bool IsWhitespace(char ch) + private static bool IsWhitespace(char ch) { return (ch == ' ' || ch == '\n' || ch == '\r' || ch == 't'); } - protected void EndContent() + protected static void EndContent() { } @@ -1726,10 +1726,6 @@ protected void StartArray(int count) AutoComplete(WriteState.Content); } - protected void EndArray() - { - } - private string GeneratePrefix(string ns, XmlDictionaryString? xNs) { if (_writeState != WriteState.Element && _writeState != WriteState.Attribute) 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 271be9228623e..581bb07c8fde6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs @@ -1082,7 +1082,7 @@ private int ReadUInt31() return BufferReader.ReadUInt31(); } - private bool IsValidArrayType(XmlBinaryNodeType nodeType) + private static bool IsValidArrayType(XmlBinaryNodeType nodeType) { switch (nodeType) { @@ -1209,7 +1209,7 @@ private bool IsStartArray(XmlDictionaryString localName, XmlDictionaryString nam return IsStartElement(localName, namespaceUri) && _arrayState == ArrayState.Element && _arrayNodeType == nodeType && !Signing; } - private void CheckArray(Array array!!, int offset, int count) + private static void CheckArray(Array array!!, int offset, int count) { if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); 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 d955815ab184e..a6fb4a559ddb7 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs @@ -1186,17 +1186,12 @@ private void WriteStartArray(string? prefix, XmlDictionaryString localName, XmlD WriteEndElement(); } - private void WriteEndArray() - { - EndArray(); - } - private unsafe void UnsafeWriteArray(string? prefix, string localName, string? namespaceUri, XmlBinaryNodeType nodeType, int count, byte* array, byte* arrayMax) { WriteStartArray(prefix, localName, namespaceUri, count); _writer.UnsafeWriteArray(nodeType, count, array, arrayMax); - WriteEndArray(); + // WriteEndArray(); } private unsafe void UnsafeWriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, @@ -1204,10 +1199,10 @@ private unsafe void UnsafeWriteArray(string? prefix, XmlDictionaryString localNa { WriteStartArray(prefix, localName, namespaceUri, count); _writer.UnsafeWriteArray(nodeType, count, array, arrayMax); - WriteEndArray(); + // WriteEndArray(); } - private void CheckArray(Array array!!, int offset, int count) + private static void CheckArray(Array array!!, int offset, int count) { if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); @@ -1424,7 +1419,7 @@ public override void WriteArray(string? prefix, string localName, string? namesp { WriteStartArray(prefix, localName, namespaceUri, count); _writer.WriteDateTimeArray(array, offset, count); - WriteEndArray(); + // WriteEndArray(); } } } @@ -1437,7 +1432,7 @@ public override void WriteArray(string? prefix, XmlDictionaryString localName, X { WriteStartArray(prefix, localName, namespaceUri, count); _writer.WriteDateTimeArray(array, offset, count); - WriteEndArray(); + // WriteEndArray(); } } } @@ -1451,7 +1446,7 @@ public override void WriteArray(string? prefix, string localName, string? namesp { WriteStartArray(prefix, localName, namespaceUri, count); _writer.WriteGuidArray(array, offset, count); - WriteEndArray(); + // WriteEndArray(); } } } @@ -1464,7 +1459,7 @@ public override void WriteArray(string? prefix, XmlDictionaryString localName, X { WriteStartArray(prefix, localName, namespaceUri, count); _writer.WriteGuidArray(array, offset, count); - WriteEndArray(); + // WriteEndArray(); } } } @@ -1478,7 +1473,7 @@ public override void WriteArray(string? prefix, string localName, string? namesp { WriteStartArray(prefix, localName, namespaceUri, count); _writer.WriteTimeSpanArray(array, offset, count); - WriteEndArray(); + // WriteEndArray(); } } } @@ -1491,7 +1486,7 @@ public override void WriteArray(string? prefix, XmlDictionaryString localName, X { WriteStartArray(prefix, localName, namespaceUri, count); _writer.WriteTimeSpanArray(array, offset, count); - WriteEndArray(); + // WriteEndArray(); } } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs index 20a3623b3f17f..db06d82ade988 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs @@ -662,7 +662,7 @@ public int GetEscapedChars(int offset, int length, char[] chars) return charCount; } - private bool IsAttrChar(int ch) + private static bool IsAttrChar(int ch) { switch (ch) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs index b613acc5edcfb..f4b0d7b45dd27 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs @@ -137,7 +137,7 @@ public void Close() _inclusivePrefixes = null; } - public void WriteDeclaration() + public static void WriteDeclaration() { } @@ -833,7 +833,7 @@ private int Compare(ref Attribute attribute1, ref Attribute attribute2) return s; } - private int Compare(byte[] buffer, int offset1, int length1, int offset2, int length2) + private static int Compare(byte[] buffer, int offset1, int length1, int offset2, int length2) { if (offset1 == offset2) { @@ -843,7 +843,7 @@ private int Compare(byte[] buffer, int offset1, int length1, int offset2, int le return Compare(buffer, offset1, length1, buffer, offset2, length2); } - private int Compare(byte[] buffer1, int offset1, int length1, byte[] buffer2, int offset2, int length2) + private static int Compare(byte[] buffer1, int offset1, int length1, byte[] buffer2, int offset2, int length2) { // Console.WriteLine("Compare: \"{0}\", \"{1}\"", Encoding.UTF8.GetString(sourceBuffer, offset1, length1), Encoding.UTF8.GetString(sourceBuffer, offset2, length2)); @@ -863,7 +863,7 @@ private int Compare(byte[] buffer1, int offset1, int length1, byte[] buffer2, in return s; } - private bool Equals(byte[] buffer1, int offset1, int length1, byte[] buffer2, int offset2, int length2) + private static bool Equals(byte[] buffer1, int offset1, int length1, byte[] buffer2, int offset2, int length2) { // Console.WriteLine("Equals: \"{0}\", \"{1}\"", Encoding.UTF8.GetString(buffer1, offset1, length1), Encoding.UTF8.GetString(buffer2, offset2, length2)); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs index 49b24a4a436bc..8a8a5d123560d 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs @@ -980,7 +980,7 @@ public virtual bool TryGetValueAsDictionaryString([NotNullWhen(true)] out XmlDic return false; } - private void CheckArray(Array array!!, int offset, int count) + private static void CheckArray(Array array!!, int offset, int count) { if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs index ebf732732f1ec..1ba3975e8b9b6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs @@ -432,7 +432,7 @@ public virtual void WriteNode(XmlDictionaryReader reader!!, bool defattr) while (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement)); } - private void CheckArray(Array array!!, int offset, int count) + private static void CheckArray(Array array!!, int offset, int count) { if (offset < 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative)); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.cs index 5d25fcf4fb83f..a01ee61f3282f 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.cs @@ -65,7 +65,7 @@ public override void Close() public override void WriteDeclaration() { _writer.WriteDeclaration(); - _signingWriter.WriteDeclaration(); + XmlCanonicalWriter.WriteDeclaration(); } public override void WriteComment(string text) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs index 6bee5c067e180..2bcad0e51e3f3 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs @@ -752,7 +752,7 @@ private void ReadQualifiedName(PrefixHandle prefix, StringHandle localName) BufferReader.Advance(offset - prefixOffset); } - private int ReadAttributeText(byte[] buffer, int offset, int offsetMax) + private static int ReadAttributeText(byte[] buffer, int offset, int offsetMax) { byte[] charType = XmlUTF8TextReader.s_charType; int textOffset = offset; @@ -882,7 +882,7 @@ private void ReadAttributes() // NOTE: Call only if 0xEF has been seen in the stream AND there are three valid bytes to check (buffer[offset], buffer[offset + 1], buffer[offset + 2]). // 0xFFFE and 0xFFFF are not valid characters per Unicode specification. The first byte in the UTF8 representation is 0xEF. - private bool IsNextCharacterNonFFFE(byte[] buffer, int offset) + private static bool IsNextCharacterNonFFFE(byte[] buffer, int offset) { Fx.Assert(buffer[offset] == 0xEF, "buffer[offset] MUST be 0xEF."); @@ -1130,7 +1130,7 @@ private void ReadWhitespace() MoveToWhitespaceText().Value.SetValue(ValueHandleType.UTF8, offset, length); } - private int ReadWhitespace(byte[] buffer, int offset, int offsetMax) + private static int ReadWhitespace(byte[] buffer, int offset, int offsetMax) { byte[] charType = XmlUTF8TextReader.s_charType; int wsOffset = offset; @@ -1139,7 +1139,7 @@ private int ReadWhitespace(byte[] buffer, int offset, int offsetMax) return offset - wsOffset; } - private int ReadText(byte[] buffer, int offset, int offsetMax) + private static int ReadText(byte[] buffer, int offset, int offsetMax) { byte[] charType = XmlUTF8TextReader.s_charType; int textOffset = offset; @@ -1203,7 +1203,7 @@ private int ReadTextAndWatchForInvalidCharacters(byte[] buffer, int offset, int // 4 21 11110vvv 10vvvvvv 10vvvvvv 10vvvvvv // ----- ---- ----------------------------------- - private int BreakText(byte[] buffer, int offset, int length) + private static int BreakText(byte[] buffer, int offset, int length) { // See if we might be breaking a utf8 sequence if (length > 0 && (buffer[offset + length - 1] & 0x80) == 0x80) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs index c6c6cf1f867a7..484bfc0b07dbb 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs @@ -628,7 +628,7 @@ public override void WriteCharEntity(int ch) } } - private int ToBase16(byte[] chars, int offset, uint value) + private static int ToBase16(byte[] chars, int offset, uint value) { int count = 0; do diff --git a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/DataView.cs b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/DataView.cs index 8023e35c4fce2..c9605bf383853 100644 --- a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/DataView.cs +++ b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/DataView.cs @@ -218,7 +218,7 @@ internal DataView(IntPtr jsHandle) : base(jsHandle) /// Indicates whether the 32-bit float is stored in little- or big-endian format. If false, a big-endian value is read. public void SetUint8(int byteOffset, byte value, bool littleEndian = false) => Invoke("setUint8", byteOffset, value, littleEndian); - private U UnBoxValue(object jsValue) where U : struct + private static U UnBoxValue(object jsValue) where U : struct { if (jsValue == null) { diff --git a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/TypedArray.cs b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/TypedArray.cs index 6a45c28216ac5..35f1cdebad539 100644 --- a/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/TypedArray.cs +++ b/src/libraries/System.Private.Runtime.InteropServices.JavaScript/src/System/Runtime/InteropServices/JavaScript/TypedArray.cs @@ -153,7 +153,7 @@ public U? this[int i] } } - private U? UnBoxValue(object jsValue) + private static U? UnBoxValue(object jsValue) { if (jsValue == null) return null; diff --git a/src/libraries/System.Private.Uri/src/System/Uri.cs b/src/libraries/System.Private.Uri/src/System/Uri.cs index 84d74e9a43dc1..a1782eabc95a9 100644 --- a/src/libraries/System.Private.Uri/src/System/Uri.cs +++ b/src/libraries/System.Private.Uri/src/System/Uri.cs @@ -3055,7 +3055,7 @@ private string ReCreateParts(UriComponents parts, ushort nonCanonical, UriFormat } // Cut trailing spaces - private void GetLengthWithoutTrailingSpaces(string str, ref int length, int idx) + private static void GetLengthWithoutTrailingSpaces(string str, ref int length, int idx) { // to avoid dereferencing ref length parameter for every update int local = length; @@ -4207,7 +4207,7 @@ private unsafe int CheckAuthorityHelper(char* pString, int idx, int length, return end; } - private unsafe void CheckAuthorityHelperHandleDnsIri(char* pString, int start, int end, + private static unsafe void CheckAuthorityHelperHandleDnsIri(char* pString, int start, int end, bool hasUnicode, ref Flags flags, ref bool justNormalized, ref string? newHost, ref ParsingError err) { diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs index 1476e69449d0b..af2db78046103 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs @@ -863,9 +863,9 @@ private static bool HasNamespaceDeclarationInScope(XAttribute a, XElement e) } } - internal readonly struct XPathEvaluator + internal static class XPathEvaluator { - public object Evaluate(XNode node, string expression, IXmlNamespaceResolver? resolver) where T : class + public static object Evaluate(XNode node, string expression, IXmlNamespaceResolver? resolver) where T : class { XPathNavigator navigator = node.CreateNavigator(); object result = navigator.Evaluate(expression, resolver); @@ -878,7 +878,7 @@ public object Evaluate(XNode node, string expression, IXmlNamespaceResolver? return (T)result; } - private IEnumerable EvaluateIterator(XPathNodeIterator result) + private static IEnumerable EvaluateIterator(XPathNodeIterator result) { foreach (XPathNavigator navigator in result) { @@ -957,7 +957,7 @@ public static object XPathEvaluate(this XNode node, string expression) /// IEnumerable public static object XPathEvaluate(this XNode node!!, string expression, IXmlNamespaceResolver? resolver) { - return default(XPathEvaluator).Evaluate(node, expression, resolver); + return XPathEvaluator.Evaluate(node, expression, resolver); } /// @@ -1005,7 +1005,7 @@ public static IEnumerable XPathSelectElements(this XNode node, string /// An corresponding to the resulting set of elements public static IEnumerable XPathSelectElements(this XNode node!!, string expression, IXmlNamespaceResolver? resolver) { - return (IEnumerable)default(XPathEvaluator).Evaluate(node, expression, resolver); + return (IEnumerable)XPathEvaluator.Evaluate(node, expression, resolver); } private static XText CalibrateText(XText n) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs index 6a0361bd91977..2e0e70a96eae2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs @@ -3273,7 +3273,7 @@ private void CheckAllowContent() } } - private Type?[] GenerateTokenTypeMap() + private static Type?[] GenerateTokenTypeMap() { Type?[] map = new Type[256]; map[(int)BinXmlToken.XSD_BOOLEAN] = typeof(bool); @@ -3605,7 +3605,7 @@ private int GetXsdKatmaiTokenLength(BinXmlToken token) } } - private int XsdKatmaiTimeScaleToValueLength(byte scale) + private static int XsdKatmaiTimeScaleToValueLength(byte scale) { if (scale > 7) { @@ -4180,7 +4180,7 @@ private object ValueAsObject(BinXmlToken token, bool returnInternalTypes) } } - private XmlValueConverter GetValueConverter(XmlTypeCode typeCode) + private static XmlValueConverter GetValueConverter(XmlTypeCode typeCode) { XmlSchemaSimpleType xsst = DatatypeImplementation.GetSimpleTypeFromTypeCode(typeCode); return xsst.ValueConverter; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs index 355ffdabcc95c..c8708fa6d6dfb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs @@ -614,7 +614,7 @@ private void CheckWhitespace(string value) } } - private void ValidateQName(string name) + private static void ValidateQName(string name) { ValidateNames.ParseQNameThrow(name); } @@ -636,7 +636,7 @@ private void ValidateQName(string prefix, string localName) } } - private void CheckCharacters(string value) + private static void CheckCharacters(string value) { XmlConvert.VerifyCharData(value, ExceptionType.ArgumentException, ExceptionType.XmlException); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs index c3708a0805a5d..b0258cc26e4e7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs @@ -341,17 +341,17 @@ public override void WriteQualifiedName(string localName, string? ns) // // Private methods // - private void CheckCharacters(string str) + private static void CheckCharacters(string str) { XmlConvert.VerifyCharData(str, ExceptionType.ArgumentException); } - private void CheckCharacters(char[] data, int offset, int len) + private static void CheckCharacters(char[] data, int offset, int len) { XmlConvert.VerifyCharData(data, offset, len, ExceptionType.ArgumentException); } - private void ValidateNCName(string ncname) + private static void ValidateNCName(string ncname) { if (ncname.Length == 0) { @@ -364,7 +364,7 @@ private void ValidateNCName(string ncname) } } - private void ValidateQName(string name) + private static void ValidateQName(string name) { if (name.Length == 0) { @@ -551,7 +551,7 @@ private void ValidateQName(string name) // Interleave 2 adjacent invalid chars with a space. This is used for fixing invalid values of comments and PIs. // Any "--" in comment must be replaced with "- -" and any "-" at the end must be appended with " ". // Any "?>" in PI value must be replaced with "? >". - private string InterleaveInvalidChars(string text, char invChar1, char invChar2) + private static string InterleaveInvalidChars(string text, char invChar1, char invChar2) { StringBuilder? sb = null; int start = 0; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs index 0b52424d01f10..5218ec24c9d95 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs @@ -1838,7 +1838,7 @@ private void GrowTextContentMarks() return pDst + 3; } - protected void ValidateContentChars(string chars, string propertyName, bool allowOnlyWhitespace) + protected static void ValidateContentChars(string chars, string propertyName, bool allowOnlyWhitespace) { if (allowOnlyWhitespace) { @@ -2132,15 +2132,15 @@ private void Init(XmlWriterSettings settings) { if (_newLineOnAttributes) { - base.ValidateContentChars(_indentChars, "IndentChars", true); - base.ValidateContentChars(_newLineChars, "NewLineChars", true); + ValidateContentChars(_indentChars, "IndentChars", true); + ValidateContentChars(_newLineChars, "NewLineChars", true); } else { - base.ValidateContentChars(_indentChars, "IndentChars", false); + ValidateContentChars(_indentChars, "IndentChars", false); if (base._newLineHandling != NewLineHandling.Replace) { - base.ValidateContentChars(_newLineChars, "NewLineChars", false); + ValidateContentChars(_newLineChars, "NewLineChars", false); } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs index 61b8546dd703b..1dc9d28456131 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs @@ -1580,7 +1580,7 @@ private void FinishReadContentAsType() } } - private void CheckBuffer(Array buffer!!, int index, int count) + private static void CheckBuffer(Array buffer!!, int index, int count) { if (count < 0) { 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 e4b1c34537d25..2af3bb50325ba 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 @@ -5455,7 +5455,7 @@ private void ParseAttributeValueSlow(int curPos, char quoteChar, NodeData attr) _stringBuilder.Length = 0; } - private void AddAttributeChunkToList(NodeData attr, NodeData chunk, ref NodeData? lastChunk) + private static void AddAttributeChunkToList(NodeData attr, NodeData chunk, ref NodeData? lastChunk) { if (lastChunk == null) { @@ -9618,7 +9618,7 @@ private void InitBinHexDecoder() } // SxS: URIs are resolved only to be compared. No resource exposure. It's OK to suppress the SxS warning. - private bool UriEqual(Uri? uri1, string? uri1Str, string? uri2Str, XmlResolver? resolver) + private static bool UriEqual(Uri? uri1, string? uri1Str, string? uri2Str, XmlResolver? resolver) { if (resolver == null) { 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 fbbed2084b84d..a068979c9ab98 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 @@ -3560,7 +3560,7 @@ private enum ParseTextFunction return _parseText_dummyTask.Result; } - private (int, int, int, bool) ParseText_NoValue(int outOrChars, int pos) + private static (int, int, int, bool) ParseText_NoValue(int outOrChars, int pos) { return (pos, pos, outOrChars, true); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs index 731b661d70eeb..08ec978d67116 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs @@ -1783,7 +1783,7 @@ private void HandleSpecialAttribute() } - private void VerifyPrefixXml(string? prefix, string ns) + private static void VerifyPrefixXml(string? prefix, string ns) { if (prefix != null && prefix.Length == 3) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs index feda115e1bbc2..55bf84dc84682 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs @@ -613,7 +613,6 @@ public override void Close() try { FlushBuffer(); - FlushEncoder(); } finally { @@ -648,7 +647,6 @@ public override void Close() public override void Flush() { FlushBuffer(); - FlushEncoder(); if (_stream != null) { @@ -704,12 +702,6 @@ protected virtual void FlushBuffer() } } - private void FlushEncoder() - { - // intentionally empty - - } - // Serialize text that is part of an attribute value. The '&', '<', '>', and '"' characters // are entitized. protected unsafe void WriteAttributeTextBlock(char* pSrc, char* pSrcEnd) @@ -1711,7 +1703,7 @@ internal static unsafe void CharToUTF8(ref char* pSrc, char* pSrcEnd, ref byte* return pDst + 3; } - protected void ValidateContentChars(string chars, string propertyName, bool allowOnlyWhitespace) + protected static void ValidateContentChars(string chars, string propertyName, bool allowOnlyWhitespace) { if (allowOnlyWhitespace) { @@ -2000,15 +1992,15 @@ private void Init(XmlWriterSettings settings) { if (_newLineOnAttributes) { - base.ValidateContentChars(_indentChars, "IndentChars", true); - base.ValidateContentChars(_newLineChars, "NewLineChars", true); + ValidateContentChars(_indentChars, "IndentChars", true); + ValidateContentChars(_newLineChars, "NewLineChars", true); } else { - base.ValidateContentChars(_indentChars, "IndentChars", false); + ValidateContentChars(_indentChars, "IndentChars", false); if (base._newLineHandling != NewLineHandling.Replace) { - base.ValidateContentChars(_newLineChars, "NewLineChars", false); + ValidateContentChars(_newLineChars, "NewLineChars", false); } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs index 85eaf61b3702a..bc4fbf048d012 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs @@ -2113,7 +2113,7 @@ private string GeneratePrefix() return s; } - private void CheckNCName(string ncname) + private static void CheckNCName(string ncname) { Debug.Assert(ncname != null && ncname.Length > 0); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs index 13c2e36354c42..5b5e5089f888b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs @@ -658,7 +658,7 @@ private void CheckNodeSequenceCapacity(int currentIndex) return schemaInfoFound; } - private bool AncestorTypeHasWildcard(XmlSchemaObject? ancestorType) + private static bool AncestorTypeHasWildcard(XmlSchemaObject? ancestorType) { XmlSchemaComplexType? ancestorSchemaType = GetComplexType(ancestorType); if (ancestorType != null) @@ -669,7 +669,7 @@ private bool AncestorTypeHasWildcard(XmlSchemaObject? ancestorType) return false; } - private XmlSchemaComplexType? GetComplexType(XmlSchemaObject? schemaObject) + private static XmlSchemaComplexType? GetComplexType(XmlSchemaObject? schemaObject) { if (schemaObject == null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXPathNavigator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXPathNavigator.cs index eb9da0d5881ab..b6e9a6ef23350 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXPathNavigator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXPathNavigator.cs @@ -1300,7 +1300,7 @@ private static int GetDepth(XmlNode node) //Assuming that node1 and node2 are in the same level; Except when they are namespace nodes, they should have the same parent node //the returned value is node2's position corresponding to node1 - private XmlNodeOrder Compare(XmlNode node1, XmlNode node2) + private static XmlNodeOrder Compare(XmlNode node1, XmlNode node2) { Debug.Assert(node1 != null); Debug.Assert(node2 != null); @@ -1903,7 +1903,7 @@ private void CalibrateText() return ParentNodeTail(parent); } - private XmlNode? ParentNodeTail(XmlNode? parent) + private static XmlNode? ParentNodeTail(XmlNode? parent) { while (parent != null && parent.NodeType == XmlNodeType.EntityReference) @@ -1924,7 +1924,7 @@ private void CalibrateText() return FirstChildTail(child); } - private XmlNode? FirstChildTail(XmlNode? child) + private static XmlNode? FirstChildTail(XmlNode? child) { while (child != null && child.NodeType == XmlNodeType.EntityReference) @@ -1945,7 +1945,7 @@ private void CalibrateText() return NextSiblingTail(node, sibling); } - private XmlNode? NextSiblingTail(XmlNode node, XmlNode? sibling) + private static XmlNode? NextSiblingTail(XmlNode node, XmlNode? sibling) { XmlNode? current = node; while (sibling == null) @@ -1977,7 +1977,7 @@ private void CalibrateText() return PreviousSiblingTail(node, sibling); } - private XmlNode? PreviousSiblingTail(XmlNode node, XmlNode? sibling) + private static XmlNode? PreviousSiblingTail(XmlNode node, XmlNode? sibling) { XmlNode? current = node; while (sibling == null) @@ -2009,7 +2009,7 @@ private void CalibrateText() return PreviousTextTail(node, text); } - private XmlNode? PreviousTextTail(XmlNode node, XmlNode? text) + private static XmlNode? PreviousTextTail(XmlNode node, XmlNode? text) { if (text != null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XPathNodeList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XPathNodeList.cs index ab098fb8b771c..a3d95034df6df 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XPathNodeList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XPathNodeList.cs @@ -33,7 +33,7 @@ public override int Count } } - private XmlNode? GetNode(XPathNavigator n) + private static XmlNode? GetNode(XPathNavigator n) { IHasXmlNode iHasNode = (IHasXmlNode)n; return iHasNode.GetNode(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs index fa5ab070b2102..1457af1c6ef87 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs @@ -326,7 +326,7 @@ internal override XmlNode RemoveNodeAt(int i) return retNode; } - internal void Detach(XmlAttribute attr) + internal static void Detach(XmlAttribute attr) { attr.OwnerElement!.Attributes.Remove(attr); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCharacterData.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCharacterData.cs index 6e3ecb472011c..5fdeb53565687 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCharacterData.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCharacterData.cs @@ -185,7 +185,7 @@ public virtual void ReplaceData(int offset, int count, string? strData) AfterEvent(args); } - internal bool CheckOnData(string? data) + internal static bool CheckOnData(string? data) { return XmlCharType.IsOnlyWhitespace(data); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs index d2fc81cf554ed..55ff49e6ff232 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs @@ -174,7 +174,7 @@ public override void WriteContentTo(XmlWriter w) // Intentionally do nothing since the node doesn't have children. } - private bool IsValidXmlVersion(string ver) + private static bool IsValidXmlVersion(string ver) { return ver.Length >= 3 && ver[0] == '1' && ver[1] == '.' && XmlCharType.IsOnlyDigits(ver, 2, ver.Length - 2); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs index 6dddd2976ba49..9c87aaef82b38 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs @@ -284,7 +284,7 @@ internal bool AddIdInfo(XmlName eleName, XmlName attrName) return GetIDInfoByElement_(eleName); } - private WeakReference? GetElement(ArrayList elementList, XmlElement elem) + private static WeakReference? GetElement(ArrayList elementList, XmlElement elem) { ArrayList gcElemRefs = new ArrayList(); foreach (WeakReference elemRef in elementList) @@ -503,7 +503,7 @@ internal override bool IsValidChildType(XmlNodeType type) } // the function examines all the siblings before the refNode // if any of the nodes has type equals to "nt", return true; otherwise, return false; - private bool HasNodeTypeInPrevSiblings(XmlNodeType nt, XmlNode? refNode) + private static bool HasNodeTypeInPrevSiblings(XmlNodeType nt, XmlNode? refNode) { if (refNode == null) return false; @@ -524,7 +524,7 @@ private bool HasNodeTypeInPrevSiblings(XmlNodeType nt, XmlNode? refNode) // the function examines all the siblings after the refNode // if any of the nodes has the type equals to "nt", return true; otherwise, return false; - private bool HasNodeTypeInNextSiblings(XmlNodeType nt, XmlNode? refNode) + private static bool HasNodeTypeInNextSiblings(XmlNodeType nt, XmlNode? refNode) { XmlNode? node = refNode; while (node != null) @@ -858,7 +858,7 @@ internal static bool IsTextNode(XmlNodeType nt) } } - private XmlNode? NormalizeText(XmlNode node) + private static XmlNode? NormalizeText(XmlNode node) { XmlNode? retnode = null; XmlNode? n = node; @@ -1217,7 +1217,7 @@ public virtual XmlNode CreateNode(XmlNodeType type, string name, string? namespa return node; } - internal XmlNodeType ConvertToNodeType(string nodeTypeString) + internal static XmlNodeType ConvertToNodeType(string nodeTypeString) { if (nodeTypeString == "element") { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntityReference.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntityReference.cs index 7a00a61bee947..d4b0bb64cc79e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntityReference.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntityReference.cs @@ -179,7 +179,7 @@ public override string BaseURI } } - private string ConstructBaseURI(string baseURI, string systemId) + private static string ConstructBaseURI(string baseURI, string systemId) { if (baseURI == null) return systemId; 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 cbbb1f1e3f8e0..9fbb5e884dae6 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 @@ -863,7 +863,7 @@ private void RemoveDuplicateNamespace(XmlElement elem, XmlNamespaceManager mgr, mgr.PopScope(); } - private string EntitizeName(string name) + private static string EntitizeName(string name) { return $"&{name};"; } @@ -929,7 +929,7 @@ internal void ExpandEntityReference(XmlEntityReference eref) #pragma warning disable 618 // Creates a XmlValidatingReader suitable for parsing InnerXml strings - private XmlReader CreateInnerXmlReader(string xmlFragment, XmlNodeType nt, XmlParserContext context, XmlDocument doc) + private static XmlReader CreateInnerXmlReader(string xmlFragment, XmlNodeType nt, XmlParserContext context, XmlDocument doc) { XmlNodeType contentNT = nt; if (contentNT == XmlNodeType.Entity || contentNT == XmlNodeType.EntityReference) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs index 295950dab4b1f..53cea6f2094a5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs @@ -790,7 +790,7 @@ public virtual void Normalize() StringBuilderCache.Release(sb); } - private XmlNode? NormalizeWinner(XmlNode? firstNode, XmlNode secondNode) + private static XmlNode? NormalizeWinner(XmlNode? firstNode, XmlNode secondNode) { //first node has the priority if (firstNode == null) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs index e9e24dcc41fed..e46ee02a19614 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs @@ -167,7 +167,7 @@ internal bool CreatedOnAttribute } } - private bool IsLocalNameEmpty(XmlNodeType nt) + private static bool IsLocalNameEmpty(XmlNodeType nt) { switch (nt) { @@ -377,7 +377,7 @@ private void InitDecAttr() _nDeclarationAttrCount = i; } - public string? GetDeclarationAttr(XmlDeclaration decl, string name) + public static string? GetDeclarationAttr(XmlDeclaration decl, string name) { //PreCondition: curNode is pointing at Declaration node or one of its virtual attributes if (name == strVersion) @@ -437,7 +437,7 @@ private void InitDocTypeAttr() _nDocTypeAttrCount = i; } - public string? GetDocumentTypeAttr(XmlDocumentType docType, string name) + public static string? GetDocumentTypeAttr(XmlDocumentType docType, string name) { //PreCondition: nav is pointing at DocumentType node or one of its virtual attributes if (name == strPublicID) @@ -466,7 +466,7 @@ public int GetDocTypeAttrInd(string name) return -1; } - private string? GetAttributeFromElement(XmlElement elem, string name) + private static string? GetAttributeFromElement(XmlElement elem, string name) { XmlAttribute? attr = elem.GetAttributeNode(name); if (attr != null) @@ -489,7 +489,7 @@ public int GetDocTypeAttrInd(string name) }; } - private string? GetAttributeFromElement(XmlElement elem, string name, string? ns) + private static string? GetAttributeFromElement(XmlElement elem, string name, string? ns) { XmlAttribute? attr = elem.GetAttributeNode(name, ns); if (attr != null) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlSignificantWhiteSpace.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlSignificantWhiteSpace.cs index fb58b8f053761..ea5150a0bef52 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlSignificantWhiteSpace.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlSignificantWhiteSpace.cs @@ -11,7 +11,7 @@ public class XmlSignificantWhitespace : XmlCharacterData { protected internal XmlSignificantWhitespace(string? strData, XmlDocument doc) : base(strData, doc) { - if (!doc.IsLoading && !base.CheckOnData(strData)) + if (!doc.IsLoading && !CheckOnData(strData)) throw new ArgumentException(SR.Xdom_WS_Char); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlWhitespace.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlWhitespace.cs index 5113a488563f8..3aa9cd32353ab 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlWhitespace.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlWhitespace.cs @@ -12,7 +12,7 @@ public class XmlWhitespace : XmlCharacterData { protected internal XmlWhitespace(string? strData, XmlDocument doc) : base(strData, doc) { - if (!doc.IsLoading && !base.CheckOnData(strData)) + if (!doc.IsLoading && !CheckOnData(strData)) throw new ArgumentException(SR.Xdom_WS_Char); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Asttree.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Asttree.cs index e510b22373784..65acfb5264be0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Asttree.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Asttree.cs @@ -690,7 +690,7 @@ public void CompileXPath(string xPath, bool isField, XmlNamespaceManager nsmgr) // for (1) & (4) i will have URN set properly // for (2) the URN is null // for (3) the URN is empty - private void SetURN(Axis axis, XmlNamespaceManager nsmgr) + private static void SetURN(Axis axis, XmlNamespaceManager nsmgr) { if (axis.Prefix.Length != 0) { // (1) (4) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseProcessor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseProcessor.cs index 8f27d8d525a69..83b3ccac5e080 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseProcessor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseProcessor.cs @@ -163,7 +163,7 @@ protected void AddToTable(XmlSchemaObjectTable table, XmlQualifiedName qname, Xm } } - private bool IsValidAttributeGroupRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table) + private static bool IsValidAttributeGroupRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table) { XmlSchemaAttributeGroup attGroup = (item as XmlSchemaAttributeGroup)!; XmlSchemaAttributeGroup existingAttGroup = (existingObject as XmlSchemaAttributeGroup)!; @@ -182,7 +182,7 @@ private bool IsValidAttributeGroupRedefine(XmlSchemaObject existingObject, XmlSc return false; } - private bool IsValidGroupRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table) + private static bool IsValidGroupRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table) { XmlSchemaGroup group = (item as XmlSchemaGroup)!; XmlSchemaGroup existingGroup = (existingObject as XmlSchemaGroup)!; @@ -201,7 +201,7 @@ private bool IsValidGroupRedefine(XmlSchemaObject existingObject, XmlSchemaObjec return false; } - private bool IsValidTypeRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table) + private static bool IsValidTypeRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table) { XmlSchemaType schemaType = (item as XmlSchemaType)!; XmlSchemaType existingType = (existingObject as XmlSchemaType)!; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/BitSet.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/BitSet.cs index de7d324e3df3c..b0fdc21b91218 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/BitSet.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/BitSet.cs @@ -227,7 +227,7 @@ public bool Intersects(BitSet other) return false; } - private int Subscript(int bitIndex) + private static int Subscript(int bitIndex) { return bitIndex >> bitSlotShift; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs index 0aa55c25b10cc..0ce5a74e90ba4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs @@ -880,7 +880,7 @@ public int ParentIndex new SchemaDatatypeMap("unsignedShort", s_unsignedShort, 42), }; - protected int Compare(byte[] value1, byte[] value2) + protected static int Compare(byte[] value1, byte[] value2) { int length = value1.Length; if (length != value2.Length) @@ -2673,7 +2673,7 @@ internal override int Compare(object value1, object value2) Debug.Assert(uri != null); string stringValue = uri.OriginalString; - exception = ((StringFacetsChecker)stringFacetsChecker).CheckValueFacets(stringValue, this, false); + exception = StringFacetsChecker.CheckValueFacets(stringValue, this, false); if (exception != null) goto Error; typedValue = uri; @@ -3895,9 +3895,8 @@ public override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespa try { - Numeric10FacetsChecker facetsChecker = (this.FacetsChecker as Numeric10FacetsChecker)!; decimal value = XmlConvert.ToDecimal(s); - exception = facetsChecker.CheckTotalAndFractionDigits(value, 14 + 4, 4, true, true); + exception = Numeric10FacetsChecker.CheckTotalAndFractionDigits(value, 14 + 4, 4, true, true); if (exception != null) goto Error; return value; @@ -3924,8 +3923,7 @@ public override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespa exception = XmlConvert.TryToDecimal(s, out decimalValue); if (exception != null) goto Error; - Numeric10FacetsChecker facetsChecker = (this.FacetsChecker as Numeric10FacetsChecker)!; - exception = facetsChecker.CheckTotalAndFractionDigits(decimalValue, 14 + 4, 4, true, true); + exception = Numeric10FacetsChecker.CheckTotalAndFractionDigits(decimalValue, 14 + 4, 4, true, true); if (exception != null) goto Error; typedValue = decimalValue; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs index 14b87f912fb31..eabaf31d96ce8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs @@ -3430,7 +3430,7 @@ private void SendValidationEvent(XmlSeverityType severity, XmlSchemaException e) } } - private bool IsAttributeValueType(Token token) + private static bool IsAttributeValueType(Token token) { return (int)token >= (int)Token.CDATA && (int)token <= (int)Token.NOTATION; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs index 39480cb15400c..a29d4928dc8b0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs @@ -669,7 +669,7 @@ private void CopyFacetsFromBaseType() } } - private object ParseFacetValue(XmlSchemaDatatype datatype, XmlSchemaFacet facet, string code, IXmlNamespaceResolver? nsmgr, XmlNameTable? nameTable) + private static object ParseFacetValue(XmlSchemaDatatype datatype, XmlSchemaFacet facet, string code, IXmlNamespaceResolver? nsmgr, XmlNameTable? nameTable) { object? typedValue; Exception? ex = datatype.TryParseValue(facet.Value!, nameTable, nsmgr, out typedValue); @@ -838,7 +838,7 @@ private void SetFlag(RestrictionFlags flag) return null; } - internal void CheckWhitespaceFacets(ref string s, XmlSchemaDatatype datatype) + internal static void CheckWhitespaceFacets(ref string s, XmlSchemaDatatype datatype) { // before parsing, check whitespace facet RestrictionFacets? restriction = datatype.Restriction; @@ -875,7 +875,7 @@ internal void CheckWhitespaceFacets(ref string s, XmlSchemaDatatype datatype) break; } } - internal Exception? CheckPatternFacets(RestrictionFacets? restriction, string value) + internal static Exception? CheckPatternFacets(RestrictionFacets? restriction, string value) { if (restriction != null && (restriction.Flags & RestrictionFlags.Pattern) != 0) { @@ -1089,7 +1089,7 @@ internal override bool MatchEnumeration(object value, ArrayList enumeration, Xml return MatchEnumeration(datatype.ValueConverter.ToDecimal(value), enumeration, datatype.ValueConverter); } - internal bool MatchEnumeration(decimal value, ArrayList enumeration, XmlValueConverter valueConverter) + internal static bool MatchEnumeration(decimal value, ArrayList enumeration, XmlValueConverter valueConverter) { for (int i = 0; i < enumeration.Count; ++i) { @@ -1100,7 +1100,7 @@ internal bool MatchEnumeration(decimal value, ArrayList enumeration, XmlValueCon } return false; } - internal Exception? CheckTotalAndFractionDigits(decimal value, int totalDigits, int fractionDigits, bool checkTotal, bool checkFraction) + internal static Exception? CheckTotalAndFractionDigits(decimal value, int totalDigits, int fractionDigits, bool checkTotal, bool checkFraction) { decimal maxValue = FacetsChecker.Power(10, totalDigits) - 1; //(decimal)Math.Pow(10, totalDigits) - 1 ; int powerCnt = 0; @@ -1190,7 +1190,7 @@ internal override bool MatchEnumeration(object value, ArrayList enumeration, Xml { return MatchEnumeration(datatype.ValueConverter.ToDouble(value), enumeration, datatype.ValueConverter); } - private bool MatchEnumeration(double value, ArrayList enumeration, XmlValueConverter valueConverter) + private static bool MatchEnumeration(double value, ArrayList enumeration, XmlValueConverter valueConverter) { for (int i = 0; i < enumeration.Count; ++i) { @@ -1261,7 +1261,7 @@ internal override bool MatchEnumeration(object value, ArrayList enumeration, Xml return MatchEnumeration((TimeSpan)value, enumeration); } - private bool MatchEnumeration(TimeSpan value, ArrayList enumeration) + private static bool MatchEnumeration(TimeSpan value, ArrayList enumeration) { for (int i = 0; i < enumeration.Count; ++i) { @@ -1335,7 +1335,7 @@ internal override bool MatchEnumeration(object value, ArrayList enumeration, Xml return MatchEnumeration(datatype.ValueConverter.ToDateTime(value), enumeration, datatype); } - private bool MatchEnumeration(DateTime value, ArrayList enumeration, XmlSchemaDatatype datatype) + private static bool MatchEnumeration(DateTime value, ArrayList enumeration, XmlSchemaDatatype datatype) { for (int i = 0; i < enumeration.Count; ++i) { @@ -1365,7 +1365,7 @@ internal sealed partial class StringFacetsChecker : FacetsChecker return CheckValueFacets(value, datatype, true); } - internal Exception? CheckValueFacets(string value, XmlSchemaDatatype datatype, bool verifyUri) + internal static Exception? CheckValueFacets(string value, XmlSchemaDatatype datatype, bool verifyUri) { //Length, MinLength, MaxLength int length = value.Length; @@ -1415,7 +1415,7 @@ internal override bool MatchEnumeration(object value, ArrayList enumeration, Xml return MatchEnumeration(datatype.ValueConverter.ToString(value), enumeration, datatype); } - private bool MatchEnumeration(string value, ArrayList enumeration, XmlSchemaDatatype datatype) + private static bool MatchEnumeration(string value, ArrayList enumeration, XmlSchemaDatatype datatype) { if (datatype.TypeCode == XmlTypeCode.AnyUri) { @@ -1440,7 +1440,7 @@ private bool MatchEnumeration(string value, ArrayList enumeration, XmlSchemaData return false; } - private Exception? CheckBuiltInFacets(string s, XmlTypeCode typeCode, bool verifyUri) + private static Exception? CheckBuiltInFacets(string s, XmlTypeCode typeCode, bool verifyUri) { Exception? exception = null; @@ -1548,7 +1548,7 @@ internal override bool MatchEnumeration(object value, ArrayList enumeration, Xml return MatchEnumeration((XmlQualifiedName)datatype.ValueConverter.ChangeType(value, typeof(XmlQualifiedName)), enumeration); } - private bool MatchEnumeration(XmlQualifiedName value, ArrayList enumeration) + private static bool MatchEnumeration(XmlQualifiedName value, ArrayList enumeration) { for (int i = 0; i < enumeration.Count; ++i) { @@ -1617,7 +1617,7 @@ internal override bool MatchEnumeration(object value, ArrayList enumeration, Xml return MatchEnumeration((byte[])value, enumeration, datatype); } - private bool MatchEnumeration(byte[] value, ArrayList enumeration, XmlSchemaDatatype datatype) + private static bool MatchEnumeration(byte[] value, ArrayList enumeration, XmlSchemaDatatype datatype) { for (int i = 0; i < enumeration.Count; ++i) { 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 fdcdb6438cb4e..109af3017630d 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 @@ -980,7 +980,7 @@ internal void InferElement(XmlSchemaElement xse, bool bCreatingNewType, XmlSchem } } - private XmlSchemaSimpleContentExtension CheckSimpleContentExtension(XmlSchemaComplexType ct) + private static XmlSchemaSimpleContentExtension CheckSimpleContentExtension(XmlSchemaComplexType ct) { XmlSchemaSimpleContent? sc = ct.ContentModel as XmlSchemaSimpleContent; if (sc == null) @@ -1287,7 +1287,7 @@ internal void ProcessAttributes(ref XmlSchemaElement xse, XmlSchemaType? effecti } } - private void MoveAttributes(XmlSchemaSimpleContentExtension scExtension, XmlSchemaComplexType ct) + private static void MoveAttributes(XmlSchemaSimpleContentExtension scExtension, XmlSchemaComplexType ct) { //copy all attributes from the simple content to the complex type //This is ok since when we move from complex type to simple content extension we copy from AttributeUses property @@ -1297,7 +1297,7 @@ private void MoveAttributes(XmlSchemaSimpleContentExtension scExtension, XmlSche } } - private void MoveAttributes(XmlSchemaComplexType ct, XmlSchemaSimpleContentExtension simpleContentExtension, bool bCreatingNewType) + private static void MoveAttributes(XmlSchemaComplexType ct, XmlSchemaSimpleContentExtension simpleContentExtension, bool bCreatingNewType) { //copy all attributes from the complex type to the simple content @@ -1319,7 +1319,7 @@ private void MoveAttributes(XmlSchemaComplexType ct, XmlSchemaSimpleContentExten ct.Attributes.Clear(); //Clear from pre-compiled property, post compiled will be cleared on Re-process and Compile() } - internal XmlSchemaAttribute? FindAttribute(ICollection attributes, string attrName) + internal static XmlSchemaAttribute? FindAttribute(ICollection attributes, string attrName) { foreach (XmlSchemaObject? xsa in attributes) { @@ -1353,7 +1353,7 @@ private void MoveAttributes(XmlSchemaComplexType ct, XmlSchemaSimpleContentExten } - internal XmlSchemaElement? FindElement(XmlSchemaObjectCollection elements, string elementName) + internal static XmlSchemaElement? FindElement(XmlSchemaObjectCollection elements, string elementName) { for (int i = 0; i < elements.Count; ++i) { @@ -1370,7 +1370,7 @@ private void MoveAttributes(XmlSchemaComplexType ct, XmlSchemaSimpleContentExten return null; } - internal XmlSchemaAttribute? FindAttributeRef(ICollection attributes, string attributeName, string nsURI) + internal static XmlSchemaAttribute? FindAttributeRef(ICollection attributes, string attributeName, string nsURI) { foreach (XmlSchemaObject? xsa in attributes) { @@ -1387,7 +1387,7 @@ private void MoveAttributes(XmlSchemaComplexType ct, XmlSchemaSimpleContentExten return null; } - internal XmlSchemaElement? FindElementRef(XmlSchemaObjectCollection elements, string elementName, string nsURI) + internal static XmlSchemaElement? FindElementRef(XmlSchemaObjectCollection elements, string elementName, string nsURI) { for (int i = 0; i < elements.Count; ++i) { @@ -1404,7 +1404,7 @@ private void MoveAttributes(XmlSchemaComplexType ct, XmlSchemaSimpleContentExten return null; } - internal void MakeExistingAttributesOptional(XmlSchemaComplexType ct, XmlSchemaObjectCollection? attributesInInstance) + internal static void MakeExistingAttributesOptional(XmlSchemaComplexType ct, XmlSchemaObjectCollection? attributesInInstance) { if (ct == null) { @@ -1421,7 +1421,7 @@ internal void MakeExistingAttributesOptional(XmlSchemaComplexType ct, XmlSchemaO } } - private void SwitchUseToOptional(XmlSchemaObjectCollection attributes, XmlSchemaObjectCollection? attributesInInstance) + private static void SwitchUseToOptional(XmlSchemaObjectCollection attributes, XmlSchemaObjectCollection? attributesInInstance) { for (int i = 0; i < attributes.Count; ++i) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs index 764c4216ecfeb..482b596d915da 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs @@ -170,7 +170,7 @@ public bool Execute(XmlSchema schema, string? targetNamespace, bool loadExternal return !HasErrors; } - private void Cleanup(XmlSchema schema) + private static void Cleanup(XmlSchema schema) { if (schema == Preprocessor.GetBuildInSchema()) { @@ -188,7 +188,7 @@ private void Cleanup(XmlSchema schema) schema.IsCompiledBySet = false; } - private void CleanupRedefine(XmlSchemaExternal include) + private static void CleanupRedefine(XmlSchemaExternal include) { XmlSchemaRedefine rdef = (include as XmlSchemaRedefine)!; rdef.AttributeGroups.Clear(); @@ -2184,7 +2184,7 @@ private XmlSchema GetChameleonSchema(string targetNamespace, XmlSchema schema) return chameleonSchema; } - private void SetParent(XmlSchemaObject child, XmlSchemaObject parent) + private static void SetParent(XmlSchemaObject child, XmlSchemaObject parent) { child.Parent = parent; } 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 03597a53e8783..55900a6b3269c 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 @@ -1417,7 +1417,7 @@ private bool IsValidRestriction(XmlSchemaParticle derivedParticle, XmlSchemaPart return false; } - private bool IsElementFromElement(XmlSchemaElement derivedElement, XmlSchemaElement baseElement) + private static bool IsElementFromElement(XmlSchemaElement derivedElement, XmlSchemaElement baseElement) { return (derivedElement.QualifiedName == baseElement.QualifiedName) && (derivedElement.IsNillable == baseElement.IsNillable) && @@ -1428,13 +1428,13 @@ private bool IsElementFromElement(XmlSchemaElement derivedElement, XmlSchemaElem XmlSchemaType.IsDerivedFrom(derivedElement.ElementSchemaType, baseElement.ElementSchemaType, ~XmlSchemaDerivationMethod.Restriction); } - private bool IsElementFromAny(XmlSchemaElement derivedElement, XmlSchemaAny baseAny) + private static bool IsElementFromAny(XmlSchemaElement derivedElement, XmlSchemaAny baseAny) { return baseAny.Allows(derivedElement.QualifiedName) && IsValidOccurrenceRangeRestriction(derivedElement, baseAny); } - private bool IsAnyFromAny(XmlSchemaAny derivedAny, XmlSchemaAny baseAny) + private static bool IsAnyFromAny(XmlSchemaAny derivedAny, XmlSchemaAny baseAny) { return IsValidOccurrenceRangeRestriction(derivedAny, baseAny) && NamespaceList.IsSubset(derivedAny.NamespaceList!, baseAny.NamespaceList!); @@ -1572,7 +1572,7 @@ private bool IsSequenceFromChoice(XmlSchemaSequence derivedSequence, XmlSchemaCh return true; } - private void CalculateSequenceRange(XmlSchemaSequence sequence, out decimal minOccurs, out decimal maxOccurs) + private static void CalculateSequenceRange(XmlSchemaSequence sequence, out decimal minOccurs, out decimal maxOccurs) { minOccurs = decimal.Zero; maxOccurs = decimal.Zero; for (int i = 0; i < sequence.Items.Count; ++i) @@ -1596,12 +1596,12 @@ private void CalculateSequenceRange(XmlSchemaSequence sequence, out decimal minO } } - private bool IsValidOccurrenceRangeRestriction(XmlSchemaParticle derivedParticle, XmlSchemaParticle baseParticle) + private static bool IsValidOccurrenceRangeRestriction(XmlSchemaParticle derivedParticle, XmlSchemaParticle baseParticle) { return IsValidOccurrenceRangeRestriction(derivedParticle.MinOccurs, derivedParticle.MaxOccurs, baseParticle.MinOccurs, baseParticle.MaxOccurs); } - private bool IsValidOccurrenceRangeRestriction(decimal minOccurs, decimal maxOccurs, decimal baseMinOccurs, decimal baseMaxOccurs) + private static bool IsValidOccurrenceRangeRestriction(decimal minOccurs, decimal maxOccurs, decimal baseMinOccurs, decimal baseMaxOccurs) { return (baseMinOccurs <= minOccurs) && (maxOccurs <= baseMaxOccurs); } @@ -1705,7 +1705,7 @@ private void PushComplexType(XmlSchemaComplexType complexType) _complexTypeStack.Push(complexType); } - private XmlSchemaContentType GetSchemaContentType(XmlSchemaComplexType complexType, XmlSchemaComplexContent? complexContent, XmlSchemaParticle particle) + private static XmlSchemaContentType GetSchemaContentType(XmlSchemaComplexType complexType, XmlSchemaComplexContent? complexContent, XmlSchemaParticle particle) { if ((complexContent != null && complexContent.IsMixed) || (complexContent == null && complexType.IsMixed)) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs index e4a1d6c24c2f5..3dab0b2b2a913 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs @@ -1789,12 +1789,12 @@ private void ValidateQNameAttribute(XmlSchemaObject xso, string attributeName, X } } - private void SetParent(XmlSchemaObject child, XmlSchemaObject parent) + private static void SetParent(XmlSchemaObject child, XmlSchemaObject parent) { child.Parent = parent; } - private void PreprocessAnnotation(XmlSchemaObject schemaObject) + private static void PreprocessAnnotation(XmlSchemaObject schemaObject) { XmlSchemaAnnotated? annotated = schemaObject as XmlSchemaAnnotated; if (annotated != 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 76bcab42ffe22..9094f3939ebb7 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 @@ -1479,7 +1479,7 @@ private XmlSchemaParticle CannonicalizeSequence(XmlSchemaSequence sequence, bool } [return: NotNullIfNotNull("particle")] - private XmlSchemaParticle? CannonicalizePointlessRoot(XmlSchemaParticle particle) + private static XmlSchemaParticle? CannonicalizePointlessRoot(XmlSchemaParticle particle) { if (particle == null) { @@ -1966,12 +1966,12 @@ private bool IsSequenceFromChoice(XmlSchemaSequence derivedSequence, XmlSchemaCh return true; } - private bool IsValidOccurrenceRangeRestriction(XmlSchemaParticle derivedParticle, XmlSchemaParticle baseParticle) + private static bool IsValidOccurrenceRangeRestriction(XmlSchemaParticle derivedParticle, XmlSchemaParticle baseParticle) { return IsValidOccurrenceRangeRestriction(derivedParticle.MinOccurs, derivedParticle.MaxOccurs, baseParticle.MinOccurs, baseParticle.MaxOccurs); } - private bool IsValidOccurrenceRangeRestriction(decimal minOccurs, decimal maxOccurs, decimal baseMinOccurs, decimal baseMaxOccurs) + private static bool IsValidOccurrenceRangeRestriction(decimal minOccurs, decimal maxOccurs, decimal baseMinOccurs, decimal baseMaxOccurs) { return (baseMinOccurs <= minOccurs) && (maxOccurs <= baseMaxOccurs); } @@ -2076,7 +2076,7 @@ private void PushComplexType(XmlSchemaComplexType complexType) _complexTypeStack.Push(complexType); } - private XmlSchemaContentType GetSchemaContentType(XmlSchemaComplexType complexType, XmlSchemaComplexContent? complexContent, XmlSchemaParticle particle) + private static XmlSchemaContentType GetSchemaContentType(XmlSchemaComplexType complexType, XmlSchemaComplexContent? complexContent, XmlSchemaParticle particle) { if ((complexContent != null && complexContent.IsMixed) || (complexContent == null && complexType.IsMixed)) @@ -2384,7 +2384,7 @@ private void CheckAtrributeGroupRestriction(XmlSchemaAttributeGroup baseAttribut } } - private bool IsProcessContentsRestricted(XmlSchemaComplexType? baseType, XmlSchemaAnyAttribute derivedAttributeWildcard, XmlSchemaAnyAttribute baseAttributeWildcard) + private static bool IsProcessContentsRestricted(XmlSchemaComplexType? baseType, XmlSchemaAnyAttribute derivedAttributeWildcard, XmlSchemaAnyAttribute baseAttributeWildcard) { if (baseType == XmlSchemaComplexType.AnyType) { @@ -3108,7 +3108,7 @@ private void CompileComplexTypeElements(XmlSchemaComplexType complexType) } } - private void CopyPosition(XmlSchemaAnnotated to, XmlSchemaAnnotated from, bool copyParent) + private static void CopyPosition(XmlSchemaAnnotated to, XmlSchemaAnnotated from, bool copyParent) { to.SourceUri = from.SourceUri; to.LinePosition = from.LinePosition; @@ -3120,7 +3120,7 @@ private void CopyPosition(XmlSchemaAnnotated to, XmlSchemaAnnotated from, bool c } } - private bool IsFixedEqual(SchemaDeclBase baseDecl, SchemaDeclBase derivedDecl) + private static bool IsFixedEqual(SchemaDeclBase baseDecl, SchemaDeclBase derivedDecl) { if (baseDecl.Presence == SchemaDeclBase.Use.Fixed || baseDecl.Presence == SchemaDeclBase.Use.RequiredFixed) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs index dba37fa2395d2..3b323a3cab8bf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs @@ -1153,7 +1153,7 @@ private static void XDR_EndAttributeType(XdrBuilder builder) builder.CheckDefaultAttValue(builder._AttributeDef._AttDef); } - builder.SetAttributePresence(builder._AttributeDef._AttDef, builder._AttributeDef._Required); + XdrBuilder.SetAttributePresence(builder._AttributeDef._AttDef, builder._AttributeDef._Required); cleanup: if (code != null) @@ -1701,7 +1701,7 @@ private void XDR_CheckAttributeDefault(DeclBaseInfo decl, SchemaAttDef pAttdef) SetAttributePresence(pAttdef, 1 == decl._MinOccurs); } - private void SetAttributePresence(SchemaAttDef pAttdef, bool fRequired) + private static void SetAttributePresence(SchemaAttDef pAttdef, bool fRequired) { if (SchemaDeclBase.Use.Fixed != pAttdef.Presence) { @@ -1794,7 +1794,7 @@ private void CheckDefaultAttValue(SchemaAttDef attDef) XdrValidator.CheckDefaultValue(str, attDef, _SchemaInfo, _CurNsMgr, _NameTable, null, _validationEventHandler, _reader.BaseURI, _positionInfo.LineNumber, _positionInfo.LinePosition); } - private bool IsGlobal(int flags) + private static bool IsGlobal(int flags) { return flags == SchemaFlagsNs; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlAtomicValue.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlAtomicValue.cs index 0581ab222c648..7988c3fa2412b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlAtomicValue.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlAtomicValue.cs @@ -379,7 +379,7 @@ public override string ToString() return Value; } - private string? GetPrefixFromQName(string value) + private static string? GetPrefixFromQName(string value) { int colonOffset; int len = ValidateNames.ParseQName(value, 0, out colonOffset); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs index 0d09a2f099418..8ad704851686f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs @@ -109,7 +109,7 @@ internal string TypeCodeString } } - internal string TypeCodeToString(XmlTypeCode typeCode) => + internal static string TypeCodeToString(XmlTypeCode typeCode) => typeCode switch { XmlTypeCode.None => "None", diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs index 3e408b36555ac..f680e1d84570d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs @@ -1361,7 +1361,7 @@ internal bool GetSchemaByUri(Uri schemaUri, [NotNullWhen(true)] out XmlSchema? s return false; } - internal string GetTargetNamespace(XmlSchema schema) + internal static string GetTargetNamespace(XmlSchema schema) { return schema.TargetNamespace == null ? string.Empty : schema.TargetNamespace; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs index 537a8587c6438..4a618dfc983b2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs @@ -1478,7 +1478,7 @@ private void ProcessSchemaLocations(string? xsiSchemaLocation, string? xsiNoName return typedValue; } - private string GetTypeName(SchemaDeclBase decl) + private static string GetTypeName(SchemaDeclBase decl) { Debug.Assert(decl != null && decl.SchemaType != null); string typeName = decl.SchemaType.QualifiedName.ToString(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs index 2267accdafab1..f7189737c8cec 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs @@ -2339,7 +2339,7 @@ protected override object ChangeListType(object value, Type destinationType, IXm return base.ChangeListType(value, destinationType, nsResolver); } - private bool SupportsType(Type clrType) + private static bool SupportsType(Type clrType) { if (clrType == BooleanType) return true; if (clrType == ByteType) return true; @@ -2817,7 +2817,7 @@ protected override object ChangeListType(object value, Type destinationType, IXm /// 2. A strongly-typed array /// 3. A string /// - private bool IsListType(Type type) + private static bool IsListType(Type type) { // IsClrListType returns true if "type" is one of the list interfaces if (type == IListType || type == ICollectionType || type == IEnumerableType || type == StringType) @@ -2886,7 +2886,7 @@ private IList ToList(object list, IXmlNamespaceResolver? nsResolver) /// /// Tokenize "value" by splitting it on whitespace characters. Insert tokens into an ArrayList and return the list. /// - private List StringAsList(string value) + private static List StringAsList(string value) { return new List(XmlConvert.SplitString(value)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs index 9b7adb815b028..fe493a5a7de14 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs @@ -1012,7 +1012,7 @@ private void AttributeIdentityConstraints(string name, string ns, object? obj, s } } - private object? UnWrapUnion(object? typedValue) + private static object? UnWrapUnion(object? typedValue) { XsdSimpleValue? simpleValue = typedValue as XsdSimpleValue; if (simpleValue != null) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs index 0d867111bf655..83d77b08741de 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs @@ -167,7 +167,7 @@ internal LocalBuilder GetTempLocal(Type type) return localTmp; } - internal Type GetVariableType(object var) + internal static Type GetVariableType(object var) { if (var is ArgBuilder) return ((ArgBuilder)var).ArgType; @@ -339,7 +339,7 @@ internal void IfNot() OpCodes.Blt, }; - private OpCode GetBranchCode(Cmp cmp) + private static OpCode GetBranchCode(Cmp cmp) { return s_branchCodes[(int)cmp]; } @@ -712,7 +712,7 @@ internal void Unbox(Type type) }; - private OpCode GetLdindOpCode(TypeCode typeCode) + private static OpCode GetLdindOpCode(TypeCode typeCode) { return s_ldindOpCodes[(int)typeCode]; } @@ -1024,7 +1024,7 @@ internal void Ldlen() OpCodes.Ldelem_Ref, //String = 18, }; - private OpCode GetLdelemOpCode(TypeCode typeCode) + private static OpCode GetLdelemOpCode(TypeCode typeCode) { return s_ldelemOpCodes[(int)typeCode]; } @@ -1072,7 +1072,7 @@ internal void Ldelema(Type arrayElementType) OpCodes.Stelem_Ref, //String = 18, }; - private OpCode GetStelemOpCode(TypeCode typeCode) + private static OpCode GetStelemOpCode(TypeCode typeCode) { return s_stelemOpCodes[(int)typeCode]; } @@ -1184,7 +1184,7 @@ private void InternalIf(bool negate) OpCodes.Nop, //String = 18, }; - private OpCode GetConvOpCode(TypeCode typeCode) + private static OpCode GetConvOpCode(TypeCode typeCode) { return s_convOpCodes[(int)typeCode]; } @@ -1610,9 +1610,9 @@ public MethodBuilderInfo(MethodBuilder methodBuilder, Type[] parameterTypes) this.ParameterTypes = parameterTypes; } + [Conditional("DEBUG")] public void Validate(Type? returnType, Type[] parameterTypes, MethodAttributes attributes) { -#if DEBUG Debug.Assert(this.MethodBuilder.ReturnType == returnType); Debug.Assert(this.MethodBuilder.Attributes == attributes); Debug.Assert(this.ParameterTypes.Length == parameterTypes.Length); @@ -1620,7 +1620,6 @@ public void Validate(Type? returnType, Type[] parameterTypes, MethodAttributes a { Debug.Assert(this.ParameterTypes[i] == parameterTypes[i]); } -#endif } } 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 071052f5af01a..eb198919446b9 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 @@ -312,145 +312,136 @@ private static string GenerateAssemblyId(Type type) internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type?[] types, string? defaultNamespace, Assembly? assembly, Hashtable assemblies, Stream stream) { var compiler = new Compiler(); - try - { - var scopeTable = new Hashtable(); - foreach (XmlMapping mapping in xmlMappings) - scopeTable[mapping.Scope!] = mapping; + var scopeTable = new Hashtable(); + foreach (XmlMapping mapping in xmlMappings) + scopeTable[mapping.Scope!] = mapping; - var scopes = new TypeScope[scopeTable.Keys.Count]; - scopeTable.Keys.CopyTo(scopes, 0); - assemblies.Clear(); - var importedTypes = new Hashtable(); + var scopes = new TypeScope[scopeTable.Keys.Count]; + scopeTable.Keys.CopyTo(scopes, 0); + assemblies.Clear(); + var importedTypes = new Hashtable(); - foreach (TypeScope scope in scopes) + foreach (TypeScope scope in scopes) + { + foreach (Type t in scope.Types) { - foreach (Type t in scope.Types) + compiler.AddImport(t, importedTypes); + Assembly a = t.Assembly; + string name = a.FullName!; + if (assemblies[name] != null) { - compiler.AddImport(t, importedTypes); - Assembly a = t.Assembly; - string name = a.FullName!; - if (assemblies[name] != null) - { - continue; - } - - assemblies[name] = a; + continue; } - } - for (int i = 0; i < types.Length; i++) - { - compiler.AddImport(types[i], importedTypes); + assemblies[name] = a; } + } - compiler.AddImport(typeof(object).Assembly); - compiler.AddImport(typeof(System.Xml.Serialization.XmlSerializer).Assembly); - var writer = new IndentedWriter(compiler.Source, false); - writer.WriteLine("[assembly:System.Security.AllowPartiallyTrustedCallers()]"); - writer.WriteLine("[assembly:System.Security.SecurityTransparent()]"); - writer.WriteLine("[assembly:System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]"); + for (int i = 0; i < types.Length; i++) + { + compiler.AddImport(types[i], importedTypes); + } + + var writer = new IndentedWriter(compiler.Source, false); + writer.WriteLine("[assembly:System.Security.AllowPartiallyTrustedCallers()]"); + writer.WriteLine("[assembly:System.Security.SecurityTransparent()]"); + writer.WriteLine("[assembly:System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]"); - if (assembly != null && types.Length > 0) + if (assembly != null && types.Length > 0) + { + for (int i = 0; i < types.Length; i++) { - for (int i = 0; i < types.Length; i++) + Type? type = types[i]; + if (type == null) { - Type? type = types[i]; - if (type == null) - { - continue; - } - - if (DynamicAssemblies.IsTypeDynamic(type)) - { - throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, types[i]!.FullName)); - } + continue; } - writer.Write("[assembly:"); - writer.Write(typeof(XmlSerializerVersionAttribute).FullName); - writer.Write("("); - writer.Write("ParentAssemblyId="); - ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, GenerateAssemblyId(types[0]!)); - writer.Write(", Version="); - ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, ThisAssembly.Version); - if (defaultNamespace != null) + if (DynamicAssemblies.IsTypeDynamic(type)) { - writer.Write(", Namespace="); - ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, defaultNamespace); + throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, types[i]!.FullName)); } - - writer.WriteLine(")]"); } - var classes = new CodeIdentifiers(); - classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter"); - classes.AddUnique("XmlSerializationReader", "XmlSerializationReader"); - string? suffix = null; - - if (types != null && types.Length == 1 && types[0] != null) + writer.Write("[assembly:"); + writer.Write(typeof(XmlSerializerVersionAttribute).FullName); + writer.Write("("); + writer.Write("ParentAssemblyId="); + ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, GenerateAssemblyId(types[0]!)); + writer.Write(", Version="); + ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, ThisAssembly.Version); + if (defaultNamespace != null) { - suffix = CodeIdentifier.MakeValid(types[0]!.Name); - if (types[0]!.IsArray) - { - suffix += "Array"; - } + writer.Write(", Namespace="); + ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, defaultNamespace); } - writer.WriteLine($"namespace {GeneratedAssemblyNamespace} {{"); - writer.Indent++; - writer.WriteLine(); + writer.WriteLine(")]"); + } - string writerClass = $"XmlSerializationWriter{suffix}"; - writerClass = classes.AddUnique(writerClass, writerClass); - var writerCodeGen = new XmlSerializationWriterCodeGen(writer, scopes, "public", writerClass); - writerCodeGen.GenerateBegin(); - string?[] writeMethodNames = new string[xmlMappings.Length]; + var classes = new CodeIdentifiers(); + classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter"); + classes.AddUnique("XmlSerializationReader", "XmlSerializationReader"); + string? suffix = null; - for (int i = 0; i < xmlMappings.Length; i++) + if (types != null && types.Length == 1 && types[0] != null) + { + suffix = CodeIdentifier.MakeValid(types[0]!.Name); + if (types[0]!.IsArray) { - writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]); + suffix += "Array"; } + } - writerCodeGen.GenerateEnd(); - writer.WriteLine(); - - string readerClass = $"XmlSerializationReader{suffix}"; - readerClass = classes.AddUnique(readerClass, readerClass); - var readerCodeGen = new XmlSerializationReaderCodeGen(writer, scopes, "public", readerClass); - readerCodeGen.GenerateBegin(); - string?[] readMethodNames = new string[xmlMappings.Length]; - for (int i = 0; i < xmlMappings.Length; i++) - { - readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i])!; - } + writer.WriteLine($"namespace {GeneratedAssemblyNamespace} {{"); + writer.Indent++; + writer.WriteLine(); - readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types); + string writerClass = $"XmlSerializationWriter{suffix}"; + writerClass = classes.AddUnique(writerClass, writerClass); + var writerCodeGen = new XmlSerializationWriterCodeGen(writer, scopes, "public", writerClass); + writerCodeGen.GenerateBegin(); + string?[] writeMethodNames = new string[xmlMappings.Length]; - string baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes); - var serializers = new Hashtable(); - for (int i = 0; i < xmlMappings.Length; i++) - { - if (serializers[xmlMappings[i].Key!] == null) - { - serializers[xmlMappings[i].Key!] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); - } - } + for (int i = 0; i < xmlMappings.Length; i++) + { + writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]); + } - readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types!, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); - writer.Indent--; - writer.WriteLine("}"); + writerCodeGen.GenerateEnd(); + writer.WriteLine(); - string codecontent = compiler.Source.ToString()!; - byte[] info = new UTF8Encoding(true).GetBytes(codecontent); - stream.Write(info, 0, info.Length); - stream.Flush(); - return true; + string readerClass = $"XmlSerializationReader{suffix}"; + readerClass = classes.AddUnique(readerClass, readerClass); + var readerCodeGen = new XmlSerializationReaderCodeGen(writer, scopes, "public", readerClass); + readerCodeGen.GenerateBegin(); + string?[] readMethodNames = new string[xmlMappings.Length]; + for (int i = 0; i < xmlMappings.Length; i++) + { + readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i])!; } - finally + + readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types); + + string baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes); + var serializers = new Hashtable(); + for (int i = 0; i < xmlMappings.Length; i++) { - compiler.Close(); + if (serializers[xmlMappings[i].Key!] == null) + { + 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); + writer.Indent--; + writer.WriteLine("}"); + + string codecontent = compiler.Source.ToString()!; + byte[] info = new UTF8Encoding(true).GetBytes(codecontent); + stream.Write(info, 0, info.Length); + stream.Flush(); + return true; } [RequiresUnreferencedCode("calls GenerateElement")] @@ -625,7 +616,7 @@ internal static void VerifyLoadContext(Type? t, Assembly? assembly) [RequiresUnreferencedCode("calls Contract")] internal object? InvokeReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, string? encodingStyle) { - XmlSerializationReader? reader = null; + XmlSerializationReader? reader; try { encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key!); @@ -650,17 +641,12 @@ internal static void VerifyLoadContext(Type? t, Assembly? assembly) { throw new InvalidOperationException(SR.XmlNoPartialTrust, e); } - finally - { - if (reader != null) - reader.Dispose(); - } } [RequiresUnreferencedCode("calls Contract")] internal void InvokeWriter(XmlMapping mapping, XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? id) { - XmlSerializationWriter? writer = null; + XmlSerializationWriter? writer; try { encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key!); @@ -685,11 +671,6 @@ internal void InvokeWriter(XmlMapping mapping, XmlWriter xmlWriter, object? o, X { throw new InvalidOperationException(SR.XmlNoPartialTrust, e); } - finally - { - if (writer != null) - writer.Dispose(); - } } internal sealed class TempMethodDictionary : Dictionary diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compiler.cs index 7b08dd571daef..d4994f65bbf3e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compiler.cs @@ -77,14 +77,6 @@ internal void AddImport(Type? type, Hashtable types) } } - // SxS: This method does not take any resource name and does not expose any resources to the caller. - // It's OK to suppress the SxS warning. - internal void AddImport(Assembly assembly) - { - } - - internal void Close() { } - internal TextWriter Source { get { return _writer; } 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 81a4ee0f97e2c..9499f3243a041 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 @@ -248,7 +248,7 @@ private int GetHash(XmlSchemaObject o) return code; } - private string ToString(XmlSchemaObject o, SchemaObjectWriter writer) + private static string ToString(XmlSchemaObject o, SchemaObjectWriter writer) { return writer.WriteXmlSchemaObject(o); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs index 0c674716fbdc7..ab5b7c27ee8a1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs @@ -1264,7 +1264,7 @@ internal void CheckDuplicateElement(XmlSchemaElement? element, string? elementNs } } - private bool Match(XmlSchemaElement e1, XmlSchemaElement e2) + private static bool Match(XmlSchemaElement e1, XmlSchemaElement e2) { if (e1.IsNillable != e2.IsNillable) return false; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs index 8795759b04efc..792992c3115eb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs @@ -444,7 +444,7 @@ internal ConstantModel[] Constants } } - private ConstantModel? GetConstantModel(FieldInfo fieldInfo) + private static ConstantModel? GetConstantModel(FieldInfo fieldInfo) { if (fieldInfo.IsSpecialName) return null; return new ConstantModel(fieldInfo, ((IConvertible)fieldInfo.GetValue(null)!).ToInt64(null)); 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 83706c6bf5443..c60228f965273 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 @@ -312,7 +312,7 @@ private bool GenerateLiteralMembersElementInternal(MemberMapping[] mappings, boo return true; } - private void InitializeValueTypes(object?[] p, MemberMapping[] mappings) + private static void InitializeValueTypes(object?[] p, MemberMapping[] mappings) { for (int i = 0; i < mappings.Length; i++) { @@ -553,7 +553,7 @@ private void WriteMemberElementsCheckType(List checkTypeHrefsSo } } - private void ProcessUnknownNode(UnknownNodeAction action) + private static void ProcessUnknownNode(UnknownNodeAction action) { action?.Invoke(null); } @@ -570,7 +570,7 @@ private void WriteMembers(ref object? o, Member[] members, UnknownNodeAction ele } } - private void SetCollectionObjectWithCollectionMember([NotNull] ref object? collection, CollectionMember collectionMember, + private static void SetCollectionObjectWithCollectionMember([NotNull] ref object? collection, CollectionMember collectionMember, [DynamicallyAccessedMembers(TrimmerConstants.AllMethods)] Type collectionType) { if (collectionType.IsArray) @@ -675,7 +675,7 @@ private static ReflectionXmlSerializationReaderHelper.SetMemberValueDelegate Get return (ReflectionXmlSerializationReaderHelper.SetMemberValueDelegate)result; } - private object? GetMemberValue(object o, MemberInfo memberInfo) + private static object? GetMemberValue(object o, MemberInfo memberInfo) { if (memberInfo is PropertyInfo propertyInfo) { @@ -744,7 +744,7 @@ private bool WriteMemberText(Member anyText) return false; } - private bool IsSequence(Member[] members) + private static bool IsSequence(Member[] members) { // https://github.com/dotnet/runtime/issues/1402: // Currently the reflection based method treat this kind of type as normal types. @@ -1315,7 +1315,7 @@ private object WriteEnumMethod(EnumMapping mapping, string source) } } - private Hashtable WriteHashtable(EnumMapping mapping, string name) + private static Hashtable WriteHashtable(EnumMapping mapping, string name) { var h = new Hashtable(); ConstantMapping[] constants = mapping.Constants!; @@ -1327,7 +1327,7 @@ private Hashtable WriteHashtable(EnumMapping mapping, string name) return h; } - private object? ReflectionCreateObject( + private static object? ReflectionCreateObject( [DynamicallyAccessedMembers(TrimmerConstants.AllMethods)] Type type) { object? obj; @@ -1351,7 +1351,7 @@ private Hashtable WriteHashtable(EnumMapping mapping, string name) return obj; } - private ConstructorInfo? GetDefaultConstructor( + private static ConstructorInfo? GetDefaultConstructor( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type type) => type.IsValueType ? null : @@ -2025,7 +2025,7 @@ private void WriteAttribute(Member member, object? attr = null) } [RequiresUnreferencedCode(XmlSerializer.TrimSerializationWarning)] - private void SetOrAddValueToMember(object o, object value, MemberInfo memberInfo) + private static void SetOrAddValueToMember(object o, object value, MemberInfo memberInfo) { Type memberType = GetMemberType(memberInfo); @@ -2046,7 +2046,7 @@ private void SetOrAddValueToMember(object o, object value, MemberInfo memberInfo } [RequiresUnreferencedCode(XmlSerializer.TrimSerializationWarning)] - private void AddItemInArrayMember(object o, MemberInfo memberInfo, Type memberType, object item) + private static void AddItemInArrayMember(object o, MemberInfo memberInfo, Type memberType, object item) { var currentArray = (Array?)GetMemberValue(o, memberInfo); int length; @@ -2071,12 +2071,12 @@ private void AddItemInArrayMember(object o, MemberInfo memberInfo, Type memberTy } // WriteXmlNodeEqual - private bool XmlNodeEqual(XmlReader source, string name, string? ns) + private static bool XmlNodeEqual(XmlReader source, string name, string? ns) { return source.LocalName == name && string.Equals(source.NamespaceURI, ns); } - private bool QNameEqual(XmlQualifiedName xsiType, string? name, string? ns, string? defaultNamespace) + private static bool QNameEqual(XmlQualifiedName xsiType, string? name, string? ns, 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 6c4e4fb6bb6a4..1d7a207b319f3 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 @@ -658,7 +658,7 @@ private void WriteStructMethod(StructMapping mapping, string n, string? ns, obje } [RequiresUnreferencedCode("Calls GetType on object")] - private object? GetMemberValue(object o, string memberName) + private static object? GetMemberValue(object o, string memberName) { MemberInfo memberInfo = ReflectionXmlSerializationHelper.GetEffectiveGetInfo(o.GetType(), memberName); object? memberValue = GetMemberValue(o, memberInfo); @@ -754,7 +754,7 @@ private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, strin } } - private object? GetMemberValue(object? o, MemberInfo memberInfo) + private static object? GetMemberValue(object? o, MemberInfo memberInfo) { if (memberInfo is PropertyInfo memberProperty) { @@ -870,7 +870,7 @@ private void WriteMember(object? memberValue, AttributeAccessor attribute, TypeD } } - private bool CanOptimizeWriteListSequence(TypeDesc? listElementTypeDesc) + private static bool CanOptimizeWriteListSequence(TypeDesc? listElementTypeDesc) { // check to see if we can write values of the attribute sequentially // currently we have only one data type (XmlQualifiedName) that we can not write "inline", @@ -899,7 +899,7 @@ private void WriteAttribute(object memberValue, AttributeAccessor attribute, obj } } - private int FindXmlnsIndex(MemberMapping[] members) + private static int FindXmlnsIndex(MemberMapping[] members) { for (int i = 0; i < members.Length; i++) { @@ -1055,12 +1055,12 @@ private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, } } - private bool hasRequirement(WritePrimitiveMethodRequirement value, WritePrimitiveMethodRequirement requirement) + private static bool hasRequirement(WritePrimitiveMethodRequirement value, WritePrimitiveMethodRequirement requirement) { return (value & requirement) == requirement; } - private bool IsDefaultValue(TypeMapping mapping, object o, object value, bool isNullable) + private static bool IsDefaultValue(TypeMapping mapping, object o, object value, bool isNullable) { if (value is string && ((string)value).Length == 0) { @@ -1161,7 +1161,7 @@ private bool WritePrimitiveValue(TypeDesc typeDesc, object? o, bool isElement, o return false; } - private string ConvertPrimitiveToString(object o, TypeDesc typeDesc) + private static string ConvertPrimitiveToString(object o, TypeDesc typeDesc) { string stringValue = typeDesc.FormatterName switch { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs index 7e5a4ac6572a6..0d62782addbb9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs @@ -183,7 +183,7 @@ internal StructMapping ImportRootMapping() [RequiresUnreferencedCode("calls ImportType")] internal abstract void ImportDerivedTypes(XmlQualifiedName baseName); - internal void AddReference(XmlQualifiedName name, NameTable references, string error) + internal static void AddReference(XmlQualifiedName name, NameTable references, string error) { if (name.Namespace == XmlSchema.Namespace) return; @@ -194,7 +194,7 @@ internal void AddReference(XmlQualifiedName name, NameTable references, string e references[name] = name; } - internal void RemoveReference(XmlQualifiedName name, NameTable references) + internal static void RemoveReference(XmlQualifiedName name, NameTable references) { references[name] = null; } 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 93675ac797866..2d9e6b10224ea 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 @@ -580,7 +580,7 @@ private void Write9_XmlSchemaSimpleType(XmlSchemaSimpleType? o) WriteEndElement(); } - private string Write11_XmlSchemaDerivationMethod(XmlSchemaDerivationMethod v) + private static string Write11_XmlSchemaDerivationMethod(XmlSchemaDerivationMethod v) { return v.ToString(); } @@ -729,7 +729,7 @@ private void Write_XmlSchemaFacet(string name, XmlSchemaFacet? o) WriteEndElement(); } - private string? Write30_XmlSchemaUse(XmlSchemaUse v) + private static string? Write30_XmlSchemaUse(XmlSchemaUse v) { string? s = null; switch (v) @@ -786,7 +786,7 @@ private void Write33_XmlSchemaAnyAttribute(XmlSchemaAnyAttribute? o) WriteEndElement(); } - private string? Write34_XmlSchemaContentProcessing(XmlSchemaContentProcessing v) + private static string? Write34_XmlSchemaContentProcessing(XmlSchemaContentProcessing v) { string? s = null; switch (v) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs index d19f60ae5aeb2..462d4a7afe118 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs @@ -133,7 +133,7 @@ public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, X return xmlMapping; } - private Exception ReflectionException(string context, Exception e) + private static Exception ReflectionException(string context, Exception e) { return new InvalidOperationException(SR.Format(SR.XmlReflectionError, context), e); } @@ -167,7 +167,7 @@ private TypeMapping ImportTypeMapping(TypeModel model, string dataType, Recursio { throw new InvalidOperationException(SR.Format(SR.XmlInvalidDataTypeUsage, dataType, "SoapElementAttribute.DataType")); } - TypeDesc? td = _typeScope.GetTypeDesc(dataType!, XmlSchema.Namespace); + TypeDesc? td = TypeScope.GetTypeDesc(dataType!, XmlSchema.Namespace); if (td == null) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidXsdDataType, dataType, "SoapElementAttribute.DataType", new XmlQualifiedName(dataType, XmlSchema.Namespace).ToString())); @@ -203,7 +203,7 @@ private TypeMapping ImportTypeMapping(TypeModel model, string dataType, Recursio string typeNs = _defaultNs; if (baseAttributes.SoapType != null && baseAttributes.SoapType.Namespace != null) typeNs = baseAttributes.SoapType.Namespace; - TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc! : _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace)!; + TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc! : TypeScope.GetTypeDesc(dataType, XmlSchema.Namespace)!; string xsdTypeName = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc!.Name : dataType; TypeMapping? baseMapping = GetTypeMapping(xsdTypeName, typeNs, valueTypeDesc); if (baseMapping == null) @@ -525,17 +525,17 @@ private void SetArrayMappingType(ArrayMapping mapping) mapping.TypeName = uniqueName; } - private PrimitiveMapping ImportPrimitiveMapping(PrimitiveModel model, string dataType) + private static PrimitiveMapping ImportPrimitiveMapping(PrimitiveModel model, string dataType) { PrimitiveMapping mapping = new PrimitiveMapping(); mapping.IsSoap = true; if (dataType.Length > 0) { - mapping.TypeDesc = _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); + mapping.TypeDesc = TypeScope.GetTypeDesc(dataType, XmlSchema.Namespace); if (mapping.TypeDesc == null) { // try it as a non-Xsd type - mapping.TypeDesc = _typeScope.GetTypeDesc(dataType, UrtTypes.Namespace); + mapping.TypeDesc = TypeScope.GetTypeDesc(dataType, UrtTypes.Namespace); if (mapping.TypeDesc == null) { throw new InvalidOperationException(SR.Format(SR.XmlUdeclaredXsdType, dataType)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SourceInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SourceInfo.cs index d2ac7f8903bc8..33570557a07dc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SourceInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SourceInfo.cs @@ -74,7 +74,7 @@ private void InternalLoad(Type? elementType, bool asAddress = false) if (match.Success) { object varA = ILG.GetVariable(match.Groups["a"].Value); - Type varType = ILG.GetVariableType(varA); + Type varType = CodeGenerator.GetVariableType(varA); object varIA = ILG.GetVariable(match.Groups["ia"].Value); if (varType.IsArray) { @@ -148,7 +148,7 @@ private void InternalLoad(Type? elementType, bool asAddress = false) if (Arg.StartsWith("o.@", StringComparison.Ordinal) || MemberInfo != null) { var = ILG.GetVariable(Arg.StartsWith("o.@", StringComparison.Ordinal) ? "o" : Arg); - varType = ILG.GetVariableType(var); + varType = CodeGenerator.GetVariableType(var); if (varType.IsValueType) ILG.LoadAddress(var); else @@ -157,7 +157,7 @@ private void InternalLoad(Type? elementType, bool asAddress = false) else { var = ILG.GetVariable(Arg); - varType = ILG.GetVariableType(var); + varType = CodeGenerator.GetVariableType(var); if (CodeGenerator.IsNullableGenericType(varType) && varType.GetGenericArguments()[0] == elementType) 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 1e56793922b95..a4871e98bed6d 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 @@ -152,7 +152,7 @@ internal bool IsXsdType get { return _isXsdType; } } - internal bool IsMappedType + internal static bool IsMappedType { get { return false; } } @@ -686,12 +686,12 @@ private static void AddSoapEncodedPrimitive( AddNonXsdPrimitive(type, dataTypeName, ns, formatterName, baseTypeName, Array.Empty(), flags); } - internal TypeDesc? GetTypeDesc(string name, string ns) + internal static TypeDesc? GetTypeDesc(string name, string ns) { return GetTypeDesc(name, ns, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.CanBeAttributeValue); } - internal TypeDesc? GetTypeDesc(string name, string? ns, TypeFlags flags) + internal static TypeDesc? GetTypeDesc(string name, string? ns, TypeFlags flags) { TypeDesc? typeDesc = (TypeDesc?)s_primitiveNames[name, ns]; if (typeDesc != null) @@ -704,7 +704,7 @@ private static void AddSoapEncodedPrimitive( return null; } - internal TypeDesc? GetTypeDesc(XmlSchemaSimpleType dataType) + internal static TypeDesc? GetTypeDesc(XmlSchemaSimpleType dataType) { return (TypeDesc?)s_primitiveDataTypes[dataType]; } 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 80f57fa0d24e6..dd3c94ee69863 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 @@ -364,17 +364,17 @@ private Accessor ReconcileAccessor(Accessor accessor, NameTable accessors) throw new InvalidOperationException(SR.Format(SR.XmlCannotReconcileAccessor, accessor.Name, accessor.Namespace, GetMappingName(existing.Mapping!), GetMappingName(accessor.Mapping!))); } - private Exception CreateReflectionException(string context, Exception e) + private static Exception CreateReflectionException(string context, Exception e) { return new InvalidOperationException(SR.Format(SR.XmlReflectionError, context), e); } - private Exception CreateTypeReflectionException(string context, Exception e) + private static Exception CreateTypeReflectionException(string context, Exception e) { return new InvalidOperationException(SR.Format(SR.XmlTypeReflectionError, context), e); } - private Exception CreateMemberReflectionException(FieldModel model, Exception e) + private static Exception CreateMemberReflectionException(FieldModel model, Exception e) { return new InvalidOperationException(SR.Format(model.IsProperty ? SR.XmlPropertyReflectionError : SR.XmlFieldReflectionError, model.Name), e); } @@ -397,7 +397,7 @@ private TypeMapping ImportTypeMapping(TypeModel model, string? ns, ImportContext { throw new InvalidOperationException(SR.Format(SR.XmlInvalidDataTypeUsage, dataType, "XmlElementAttribute.DataType")); } - TypeDesc? td = _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); + TypeDesc? td = TypeScope.GetTypeDesc(dataType, XmlSchema.Namespace); if (td == null) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidXsdDataType, dataType, "XmlElementAttribute.DataType", new XmlQualifiedName(dataType, XmlSchema.Namespace).ToString())); @@ -436,7 +436,7 @@ private TypeMapping ImportTypeMapping(TypeModel model, string? ns, ImportContext if (context != ImportContext.Element) throw UnsupportedException(model.TypeDesc, context); if (model.TypeDesc.IsOptionalValue) { - TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc! : _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace)!; + TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc! : TypeScope.GetTypeDesc(dataType, XmlSchema.Namespace)!; string? xsdTypeName = valueTypeDesc.DataType == null ? valueTypeDesc.Name : valueTypeDesc.DataType.Name; TypeMapping? baseMapping = GetTypeMapping(xsdTypeName, ns, valueTypeDesc, _types, null); if (baseMapping == null) @@ -1132,7 +1132,7 @@ private ArrayMapping ImportArrayLikeMapping(ArrayModel model, string? ns, Recurs return mapping; } - private void CheckContext(TypeDesc typeDesc, ImportContext context) + private static void CheckContext(TypeDesc typeDesc, ImportContext context) { switch (context) { @@ -1152,16 +1152,16 @@ private void CheckContext(TypeDesc typeDesc, ImportContext context) throw UnsupportedException(typeDesc, context); } - private PrimitiveMapping ImportPrimitiveMapping(PrimitiveModel model, ImportContext context, string dataType, bool repeats) + private static PrimitiveMapping ImportPrimitiveMapping(PrimitiveModel model, ImportContext context, string dataType, bool repeats) { PrimitiveMapping mapping = new PrimitiveMapping(); if (dataType.Length > 0) { - mapping.TypeDesc = _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); + mapping.TypeDesc = TypeScope.GetTypeDesc(dataType, XmlSchema.Namespace); if (mapping.TypeDesc == null) { // try it as a non-Xsd type - mapping.TypeDesc = _typeScope.GetTypeDesc(dataType, UrtTypes.Namespace); + mapping.TypeDesc = TypeScope.GetTypeDesc(dataType, UrtTypes.Namespace); if (mapping.TypeDesc == null) { throw new InvalidOperationException(SR.Format(SR.XmlUdeclaredXsdType, dataType)); @@ -1417,7 +1417,7 @@ private MemberMapping ImportFieldMapping(StructModel parent, FieldModel model, X return member; } - private Type CheckChoiceIdentifierType(Type type, bool isArrayLike, string identifierName, string memberName) + private static Type CheckChoiceIdentifierType(Type type, bool isArrayLike, string identifierName, string memberName) { if (type.IsArray) { @@ -1442,7 +1442,7 @@ private Type CheckChoiceIdentifierType(Type type, bool isArrayLike, string ident return type; } - private Type GetChoiceIdentifierType(XmlChoiceIdentifierAttribute choice, XmlReflectionMember[] xmlReflectionMembers, bool isArrayLike, string accessorName) + private static Type GetChoiceIdentifierType(XmlChoiceIdentifierAttribute choice, XmlReflectionMember[] xmlReflectionMembers, bool isArrayLike, string accessorName) { for (int i = 0; i < xmlReflectionMembers.Length; i++) { @@ -1456,7 +1456,7 @@ private Type GetChoiceIdentifierType(XmlChoiceIdentifierAttribute choice, XmlRef } [RequiresUnreferencedCode("calls GetFieldModel")] - private Type GetChoiceIdentifierType(XmlChoiceIdentifierAttribute choice, StructModel structModel, bool isArrayLike, string accessorName) + private static Type GetChoiceIdentifierType(XmlChoiceIdentifierAttribute choice, StructModel structModel, bool isArrayLike, string accessorName) { // check that the choice field exists @@ -2035,7 +2035,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml } - private void CheckTopLevelAttributes(XmlAttributes a, string accessorName) + private static void CheckTopLevelAttributes(XmlAttributes a, string accessorName) { XmlAttributeFlags flags = a.XmlFlags; @@ -2116,7 +2116,7 @@ private void CheckAmbiguousChoice(XmlAttributes a, Type accessorType, string acc } } - private void CheckChoiceIdentifierMapping(EnumMapping choiceMapping) + private static void CheckChoiceIdentifierMapping(EnumMapping choiceMapping) { NameTable ids = new NameTable(); for (int i = 0; i < choiceMapping.Constants!.Length; i++) @@ -2135,7 +2135,7 @@ private void CheckChoiceIdentifierMapping(EnumMapping choiceMapping) } } - private object? GetDefaultValue(TypeDesc fieldTypeDesc, Type t, XmlAttributes a) + private static object? GetDefaultValue(TypeDesc fieldTypeDesc, Type t, XmlAttributes a) { if (a.XmlDefaultValue == null || a.XmlDefaultValue == DBNull.Value) return null; if (!(fieldTypeDesc.Kind == TypeKind.Primitive || fieldTypeDesc.Kind == TypeKind.Enum)) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs index b5a0098a700a7..3acfad40a188d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs @@ -340,7 +340,7 @@ private bool SchemaContainsItem(XmlSchemaObject item, string ns) return false; } - private XmlSchemaImport? FindImport(XmlSchema schema, string? ns) + private static XmlSchemaImport? FindImport(XmlSchema schema, string? ns) { foreach (object item in schema.Includes) { @@ -1199,7 +1199,7 @@ private XmlSchemaType ExportEnumMapping(EnumMapping mapping, string? ns) return dataType; } - private void AddXmlnsAnnotation(XmlSchemaComplexType type, string xmlnsMemberName) + private static void AddXmlnsAnnotation(XmlSchemaComplexType type, string xmlnsMemberName) { XmlSchemaAnnotation annotation = new XmlSchemaAnnotation(); XmlSchemaAppInfo appinfo = new XmlSchemaAppInfo(); 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 e6694d5ed00c6..56591b5d92ead 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 @@ -37,10 +37,10 @@ internal bool GenerateOrder get { return (Options & CodeGenerationOptions.GenerateOrder) != 0; } } - internal TypeMapping GetDefaultMapping(TypeFlags flags) + internal static TypeMapping GetDefaultMapping(TypeFlags flags) { PrimitiveMapping mapping = new PrimitiveMapping(); - mapping.TypeDesc = Scope.GetTypeDesc("string", XmlSchema.Namespace, flags); + mapping.TypeDesc = TypeScope.GetTypeDesc("string", XmlSchema.Namespace, flags); mapping.TypeName = mapping.TypeDesc!.DataType!.Name; mapping.Namespace = XmlSchema.Namespace; return mapping; @@ -350,18 +350,9 @@ private TypeMapping ImportElementType(XmlSchemaElement element, string identifie if (!(desiredMappingType.IsAssignableFrom(mapping.GetType()))) throw new InvalidOperationException(SR.Format(SR.XmlElementImportedTwice, element.Name, ns, mapping.GetType().Name, desiredMappingType.Name)); - // let the extensions to run - if (!mapping.TypeDesc!.IsMappedType) - { - RunSchemaExtensions(mapping, element.SchemaTypeName, element.SchemaType, element, TypeFlags.CanBeElementValue); - } return mapping; } - private void RunSchemaExtensions(TypeMapping mapping, XmlQualifiedName qname, XmlSchemaType? type, XmlSchemaObject context, TypeFlags flags) - { - // nop - } private string GenerateUniqueTypeName(string desiredName, string? ns) { int i = 1; @@ -873,7 +864,7 @@ private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identif return member; } - private bool IsNeedXmlSerializationAttributes(ArrayMapping arrayMapping) + private static bool IsNeedXmlSerializationAttributes(ArrayMapping arrayMapping) { if (arrayMapping.Elements!.Length != 1) return true; @@ -976,7 +967,7 @@ private bool GatherGroupChoices(XmlSchemaParticle? particle, NameTable choiceEle return false; } - private void AddScopeElement(INameScope? scope, ElementAccessor element, ref bool duplicateElements, bool allowDuplicates) + private static void AddScopeElement(INameScope? scope, ElementAccessor element, ref bool duplicateElements, bool allowDuplicates) { if (scope == null) return; @@ -1000,7 +991,7 @@ private void AddScopeElement(INameScope? scope, ElementAccessor element, ref boo } } - private void AddScopeElements(INameScope? scope, ElementAccessor[] elements, ref bool duplicateElements, bool allowDuplicates) + private static void AddScopeElements(INameScope? scope, ElementAccessor[] elements, ref bool duplicateElements, bool allowDuplicates) { for (int i = 0; i < elements.Length; i++) { @@ -1201,14 +1192,6 @@ private ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string? mapping.TypeDesc = Scope.GetTypeDesc(makeElement ? typeof(XmlElement) : typeof(XmlNode)); mapping.TypeName = mapping.TypeDesc.Name; - - TypeFlags flags = TypeFlags.CanBeElementValue; - if (makeElement) - flags |= TypeFlags.CanBeTextValue; - - // let the extensions to run - RunSchemaExtensions(mapping, XmlQualifiedName.Empty, null, any, flags); - if (GenerateOrder && any.Namespace != null) { NamespaceList list = new NamespaceList(any.Namespace, targetNamespace!); @@ -1396,13 +1379,6 @@ private bool IsCyclicReferencedType(XmlSchemaElement element, List ident mapping.TypeDesc = Scope.GetTypeDesc(mixed ? typeof(XmlNode) : typeof(XmlElement)); } - TypeFlags flags = TypeFlags.CanBeElementValue; - if (items.AnyAttribute != null || mixed) - flags |= TypeFlags.CanBeTextValue; - - // let the extensions to run - RunSchemaExtensions(mapping, XmlQualifiedName.Empty, null, any, flags); - mapping.TypeName = mapping.TypeDesc.Name; if (repeats) mapping.TypeDesc = mapping.TypeDesc.CreateArrayTypeDesc(); @@ -1513,7 +1489,7 @@ private void ImportAnyAttributeMember(XmlSchemaAnyAttribute any, CodeIdentifiers member.TypeDesc = member.TypeDesc.CreateArrayTypeDesc(); } - private bool KeepXmlnsDeclarations(XmlSchemaType type, out string? xmlnsMemberName) + private static bool KeepXmlnsDeclarations(XmlSchemaType type, out string? xmlnsMemberName) { xmlnsMemberName = null; if (type.Annotation == null) @@ -1632,11 +1608,6 @@ private AttributeAccessor ImportSpecialAttribute(XmlQualifiedName name, string i mapping = GetDefaultMapping(TypeFlags.CanBeAttributeValue); } - // let the extensions to run - if (mapping != null && !mapping.TypeDesc!.IsMappedType) - { - RunSchemaExtensions(mapping, attribute.SchemaTypeName, attribute.SchemaType, attribute, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeTextValue); - } AttributeAccessor accessor = new AttributeAccessor(); accessor.Name = attribute.Name; accessor.Namespace = ns; @@ -1746,7 +1717,7 @@ private AttributeAccessor ImportSpecialAttribute(XmlQualifiedName name, string i sourceType = FindType(sourceType.DerivedFrom, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue)!; } if (sourceType is XmlSchemaComplexType) return null; - TypeDesc? sourceTypeDesc = Scope.GetTypeDesc((XmlSchemaSimpleType)sourceType); + TypeDesc? sourceTypeDesc = TypeScope.GetTypeDesc((XmlSchemaSimpleType)sourceType); if (sourceTypeDesc != null && sourceTypeDesc.FullName != typeof(string).FullName) return ImportPrimitiveDataType(dataType, flags); identifier = Accessor.UnescapeName(identifier); @@ -1846,13 +1817,13 @@ private PrimitiveMapping ImportPrimitiveDataType(XmlSchemaSimpleType dataType, T return mapping; } - private PrimitiveMapping? ImportNonXsdPrimitiveDataType(XmlSchemaSimpleType dataType, string? ns, TypeFlags flags) + private static PrimitiveMapping? ImportNonXsdPrimitiveDataType(XmlSchemaSimpleType dataType, string? ns, TypeFlags flags) { PrimitiveMapping? mapping = null; TypeDesc? typeDesc; if (dataType.Name != null && dataType.Name.Length != 0) { - typeDesc = Scope.GetTypeDesc(dataType.Name, ns, flags); + typeDesc = TypeScope.GetTypeDesc(dataType.Name, ns, flags); if (typeDesc != null) { mapping = new PrimitiveMapping(); @@ -1908,7 +1879,7 @@ private TypeDesc GetDataTypeSource(XmlSchemaSimpleType dataType, TypeFlags flags TypeDesc? typeDesc; if (dataType.Name != null && dataType.Name.Length != 0) { - typeDesc = Scope.GetTypeDesc(dataType); + typeDesc = TypeScope.GetTypeDesc(dataType); if (typeDesc != null) return typeDesc; } XmlQualifiedName qname = BaseTypeName(dataType); @@ -1928,7 +1899,7 @@ private TypeDesc GetDataTypeSource(XmlSchemaSimpleType dataType, TypeFlags flags return (XmlSchemaSimpleType?)Scope.GetTypeDesc(typeof(string)).DataType; } - TypeDesc? typeDesc = Scope.GetTypeDesc(name.Name, name.Namespace, flags); + TypeDesc? typeDesc = TypeScope.GetTypeDesc(name.Name, name.Namespace, flags); if (typeDesc != null && typeDesc.DataType is XmlSchemaSimpleType) return (XmlSchemaSimpleType)typeDesc.DataType; @@ -1940,7 +1911,7 @@ private TypeDesc GetDataTypeSource(XmlSchemaSimpleType dataType, TypeFlags flags if (name.Namespace == XmlSchema.Namespace) { - return (XmlSchemaSimpleType?)Scope.GetTypeDesc("string", XmlSchema.Namespace, flags)!.DataType; + return (XmlSchemaSimpleType?)TypeScope.GetTypeDesc("string", XmlSchema.Namespace, flags)!.DataType; } else { @@ -1989,7 +1960,7 @@ private XmlSchemaAttribute FindAttribute(XmlQualifiedName name) return attribute; } - private XmlSchemaForm ElementForm(string? ns, XmlSchemaElement element) + private static XmlSchemaForm ElementForm(string? ns, XmlSchemaElement element) { if (element.Form == XmlSchemaForm.None) { @@ -2017,7 +1988,7 @@ private XmlSchemaForm ElementForm(string? ns, XmlSchemaElement element) return element.Form; } - private XmlSchemaForm AttributeForm(string? ns, XmlSchemaAttribute attribute) + private static XmlSchemaForm AttributeForm(string? ns, XmlSchemaAttribute attribute) { if (attribute.Form == XmlSchemaForm.None) { 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 858b4db17b512..d47f7384f8a84 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 @@ -204,7 +204,7 @@ private void AddName(XmlSchema schema) } } - private void Prepare(XmlSchema schema) + private static void Prepare(XmlSchema schema) { // need to remove illegal externals; ArrayList removes = new ArrayList(); @@ -361,7 +361,7 @@ private void Merge(XmlSchema schema) } } - private void AddImport(IList schemas, string? ns) + private static void AddImport(IList schemas, string? ns) { foreach (XmlSchema s in schemas) { @@ -618,7 +618,7 @@ private static string MergeFailedMessage(XmlSchemaObject src, XmlSchemaObject de return err; } - internal XmlSchemaObject? Find(XmlSchemaObject o, IList originals) + internal static XmlSchemaObject? Find(XmlSchemaObject o, IList originals) { string? name = ItemName(o); if (name == null) 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 49bc01a560647..47c27f17c897b 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 @@ -16,14 +16,6 @@ namespace System.Xml.Serialization /// public abstract class XmlSerializationGeneratedCode { - internal void Init(TempAssembly? tempAssembly) - { - } - - // this method must be called at the end of serialization - internal void Dispose() - { - } } internal class XmlSerializationCodeGen { @@ -92,7 +84,7 @@ internal void GenerateReferencedMethods() return (string?)_methodNames[mapping]; } - private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) + private static TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) { if (a == null) return new TypeMapping[32]; if (index < a.Length) return a; 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 c9b4c4a0f495a..23eed6528d285 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 @@ -120,7 +120,7 @@ internal void GenerateReferencedMethods() return methodName; } - private TypeMapping[] EnsureArrayIndex(TypeMapping[]? a, int index) + private static TypeMapping[] EnsureArrayIndex(TypeMapping[]? a, int index) { if (a == null) return new TypeMapping[32]; if (index < a.Length) return a; @@ -130,7 +130,7 @@ private TypeMapping[] EnsureArrayIndex(TypeMapping[]? a, int index) } [return: NotNullIfNotNull("value")] - internal string? GetCSharpString(string? value) + internal static string? GetCSharpString(string? value) { return ReflectionAwareILGen.GetCSharpString(value); } 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 979756374c8bb..ce5b5c1b8caf0 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 @@ -116,7 +116,6 @@ internal void Init(XmlReader r, XmlDeserializationEvents events, string? encodin _r = r; _d = null; _soap12 = (encodingStyle == Soap12.Encoding); - Init(tempAssembly); _schemaNsID = r.NameTable.Add(XmlSchema.Namespace); _schemaNs2000ID = r.NameTable.Add("http://www.w3.org/2000/10/XMLSchema"); @@ -1047,7 +1046,7 @@ private SoapArrayInfo ParseArrayType(string value) return soapArrayInfo; } - private SoapArrayInfo ParseSoap12ArrayType(string? itemType, string? arraySize) + private static SoapArrayInfo ParseSoap12ArrayType(string? itemType, string? arraySize) { SoapArrayInfo soapArrayInfo = default; @@ -2456,7 +2455,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) return GenerateLiteralMembersElement(xmlMembersMapping); } - private string? GetChoiceIdentifierSource(MemberMapping[] mappings, MemberMapping member) + private static string? GetChoiceIdentifierSource(MemberMapping[] mappings, MemberMapping member) { string? choiceSource = null; if (member.ChoiceIdentifier != null) @@ -3991,7 +3990,7 @@ private void WriteMemberBegin(Member[] members) } } - private string ExpectedElements(Member[] members) + private static string ExpectedElements(Member[] members) { if (IsSequence(members)) return "null"; @@ -4193,7 +4192,7 @@ private void WriteMemberElementsElse(Member? anyElement, string elementElseStrin } } - private bool IsSequence(Member[] members) + private static bool IsSequence(Member[] members) { for (int i = 0; i < members.Length; i++) { 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 5be6f6656a8c7..0c801f1e2431e 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 @@ -85,20 +85,20 @@ internal Member(XmlSerializationReaderILGen outerClass, string source, string? a if (arraySource != null) _arraySource = arraySource; else - _arraySource = outerClass.GetArraySource(mapping.TypeDesc, _arrayName, multiRef); + _arraySource = XmlSerializationReaderILGen.GetArraySource(mapping.TypeDesc, _arrayName, multiRef); _isArray = mapping.TypeDesc.IsArray; _isList = !_isArray; if (mapping.ChoiceIdentifier != null) { - _choiceArraySource = outerClass.GetArraySource(mapping.TypeDesc, _choiceArrayName, multiRef); + _choiceArraySource = XmlSerializationReaderILGen.GetArraySource(mapping.TypeDesc, _choiceArrayName, multiRef); string a = _choiceArrayName; string c = $"c{a}"; string choiceTypeFullName = mapping.ChoiceIdentifier.Mapping!.TypeDesc!.CSharpName; string castString = $"({choiceTypeFullName}[])"; - string init = $"{a} = {castString}EnsureArrayIndex({a}, {c}, {outerClass.RaCodeGen.GetStringForTypeof(choiceTypeFullName)});"; - _choiceArraySource = init + outerClass.RaCodeGen.GetStringForArrayMember(a, $"{c}++", mapping.ChoiceIdentifier.Mapping.TypeDesc); + string init = $"{a} = {castString}EnsureArrayIndex({a}, {c}, {ReflectionAwareILGen.GetStringForTypeof(choiceTypeFullName)});"; + _choiceArraySource = init + ReflectionAwareILGen.GetStringForArrayMember(a, $"{c}++", mapping.ChoiceIdentifier.Mapping.TypeDesc); } else { @@ -203,7 +203,7 @@ internal void GenerateBegin() if (mapping is StructMapping || mapping is EnumMapping || mapping is NullableMapping) MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc!.Name)); } - RaCodeGen.WriteReflectionInit(scope); + ReflectionAwareILGen.WriteReflectionInit(scope); } } @@ -326,7 +326,7 @@ private void WriteUnknownNode(string func, string node, ElementAccessor? e, bool { object pVar = ilg.GetVariable("p"); ilg.Load(pVar); - ilg.ConvertValue(ilg.GetVariableType(pVar), typeof(object)); + ilg.ConvertValue(CodeGenerator.GetVariableType(pVar), typeof(object)); } argTypes.Add(typeof(object)); if (e != null) @@ -363,7 +363,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) return GenerateLiteralMembersElement(xmlMembersMapping); } - private string GetChoiceIdentifierSource(MemberMapping[] mappings, MemberMapping member) + private static string GetChoiceIdentifierSource(MemberMapping[] mappings, MemberMapping member) { string? choiceSource = null; if (member.ChoiceIdentifier != null) @@ -385,11 +385,11 @@ private string GetChoiceIdentifierSource(MemberMapping[] mappings, MemberMapping return choiceSource!; } - private string GetChoiceIdentifierSource(MemberMapping mapping, string parent, TypeDesc parentTypeDesc) + private static string GetChoiceIdentifierSource(MemberMapping mapping, string parent, TypeDesc parentTypeDesc) { if (mapping.ChoiceIdentifier == null) return ""; CodeIdentifier.CheckValidIdentifier(mapping.ChoiceIdentifier.MemberName); - return RaCodeGen.GetStringForMember(parent, mapping.ChoiceIdentifier.MemberName, parentTypeDesc); + return ReflectionAwareILGen.GetStringForMember(parent, mapping.ChoiceIdentifier.MemberName, parentTypeDesc); } [RequiresUnreferencedCode("calls InitializeValueTypes")] @@ -632,7 +632,7 @@ private void InitializeValueTypes(string arrayName, MemberMapping[] mappings) LocalBuilder arrayLoc = ilg.GetLocal(arrayName); ilg.Ldloc(arrayLoc); ilg.Ldc(i); - RaCodeGen.ILGenForCreateInstance(ilg, mappings[i].TypeDesc!.Type!, false, false); + ReflectionAwareILGen.ILGenForCreateInstance(ilg, mappings[i].TypeDesc!.Type!, false, false); ilg.ConvertValue(mappings[i].TypeDesc!.Type!, typeof(object)); ilg.Stelem(arrayLoc.LocalType.GetElementType()!); } @@ -1275,7 +1275,7 @@ private void WriteEnumAndArrayTypes() LocalBuilder aLoc = ilg.DeclareLocal(mapping.TypeDesc.Type!, aVar); if (mapping.TypeDesc.IsValueType) { - RaCodeGen.ILGenForCreateInstance(ilg, td.Type!, false, false); + ReflectionAwareILGen.ILGenForCreateInstance(ilg, td.Type!, false, false); } else ilg.Load(null); @@ -1563,13 +1563,13 @@ private void WriteLiteralStructMethod(StructMapping structMapping) { MemberMapping mapping = mappings[i]; CodeIdentifier.CheckValidIdentifier(mapping.Name); - string source = RaCodeGen.GetStringForMember("o", mapping.Name, structMapping.TypeDesc); + string source = ReflectionAwareILGen.GetStringForMember("o", mapping.Name, structMapping.TypeDesc); Member member = new Member(this, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o", structMapping.TypeDesc)); if (!mapping.IsSequence) member.ParamsReadSource = $"paramsRead[{i}]"; member.IsNullable = mapping.TypeDesc!.IsNullable; if (mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) - member.CheckSpecifiedSource = RaCodeGen.GetStringForMember("o", $"{mapping.Name}Specified", structMapping.TypeDesc); + member.CheckSpecifiedSource = ReflectionAwareILGen.GetStringForMember("o", $"{mapping.Name}Specified", structMapping.TypeDesc); if (mapping.Text != null) anyText = member; if (mapping.Attribute != null && mapping.Attribute.Any) @@ -2217,7 +2217,7 @@ private void WriteMemberBegin(Member[] members) else { WriteSourceBegin(member.Source); - RaCodeGen.ILGenForCreateInstance(ilg, member.Mapping.TypeDesc.Type!, typeDesc.CannotNew, true); + ReflectionAwareILGen.ILGenForCreateInstance(ilg, member.Mapping.TypeDesc.Type!, typeDesc.CannotNew, true); WriteSourceEnd(member.Source, member.Mapping.TypeDesc.Type!); } ilg.EndIf(); // if ((object)(member.Source) == null @@ -2229,7 +2229,7 @@ private void WriteMemberBegin(Member[] members) } } - private string ExpectedElements(Member[] members) + private static string ExpectedElements(Member[] members) { if (IsSequence(members)) return "null"; @@ -2480,7 +2480,7 @@ private void WriteMemberElementsElse(Member? anyElement, string elementElseStrin } } - private bool IsSequence(Member[] members) + private static bool IsSequence(Member[] members) { for (int i = 0; i < members.Length; i++) { @@ -2621,11 +2621,11 @@ private void WriteMemberElementsIf(Member[] members, Member? anyElement, string } } - private string GetArraySource(TypeDesc typeDesc, string arrayName) + private static string GetArraySource(TypeDesc typeDesc, string arrayName) { return GetArraySource(typeDesc, arrayName, false); } - private string GetArraySource(TypeDesc typeDesc, string arrayName, bool multiRef) + private static string GetArraySource(TypeDesc typeDesc, string arrayName, bool multiRef) { string a = arrayName; string c = $"c{a}"; @@ -2638,8 +2638,8 @@ private string GetArraySource(TypeDesc typeDesc, string arrayName, bool multiRef if (typeDesc.IsArray) { string arrayTypeFullName = typeDesc.ArrayElementTypeDesc!.CSharpName; - init = $"{init}{a} = ({arrayTypeFullName}[])EnsureArrayIndex({a}, {c}, {RaCodeGen.GetStringForTypeof(arrayTypeFullName)});"; - string arraySource = RaCodeGen.GetStringForArrayMember(a, $"{c}++", typeDesc); + init = $"{init}{a} = ({arrayTypeFullName}[])EnsureArrayIndex({a}, {c}, {ReflectionAwareILGen.GetStringForTypeof(arrayTypeFullName)});"; + string arraySource = ReflectionAwareILGen.GetStringForArrayMember(a, $"{c}++", typeDesc); if (multiRef) { init = $"{init} soap[1] = {a};"; @@ -2649,7 +2649,7 @@ private string GetArraySource(TypeDesc typeDesc, string arrayName, bool multiRef } else { - return RaCodeGen.GetStringForMethod(arrayName, typeDesc.CSharpName, "Add"); + return ReflectionAwareILGen.GetStringForMethod(arrayName, typeDesc.CSharpName, "Add"); } } @@ -2736,7 +2736,7 @@ private void WriteSourceBegin(string source) object? variable; if (ilg.TryGetVariable(source, out variable)) { - Type varType = ilg.GetVariableType(variable); + Type varType = CodeGenerator.GetVariableType(variable); if (CodeGenerator.IsNullableGenericType(varType)) { // local address to invoke ctor on WriteSourceEnd @@ -2800,7 +2800,7 @@ private void WriteSourceBegin(string source) match = P0Regex().Match(source); if (match.Success) { - System.Diagnostics.Debug.Assert(ilg.GetVariableType(ilg.GetVariable(match.Groups["a"].Value)).IsArray); + System.Diagnostics.Debug.Assert(CodeGenerator.GetVariableType(ilg.GetVariable(match.Groups["a"].Value)).IsArray); ilg.Load(ilg.GetVariable(match.Groups["a"].Value)); ilg.Load(ilg.GetVariable(match.Groups["ia"].Value)); return; @@ -2819,7 +2819,7 @@ private void WriteSourceEnd(string source, Type elementType, Type stackType) object? variable; if (ilg.TryGetVariable(source, out variable)) { - Type varType = ilg.GetVariableType(variable); + Type varType = CodeGenerator.GetVariableType(variable); if (CodeGenerator.IsNullableGenericType(varType)) { ilg.Call(varType.GetConstructor(varType.GetGenericArguments())!); @@ -2847,7 +2847,7 @@ private void WriteSourceEnd(string source, Type elementType, Type stackType) if (match.Success) { object oVar = ilg.GetVariable(match.Groups["locA1"].Value); - Type arrayElementType = ilg.GetVariableType(oVar).GetElementType()!; + Type arrayElementType = CodeGenerator.GetVariableType(oVar).GetElementType()!; ilg.ConvertValue(elementType, arrayElementType); if (CodeGenerator.IsNullableGenericType(arrayElementType) || arrayElementType.IsValueType) { @@ -2882,7 +2882,7 @@ private void WriteSourceEnd(string source, Type elementType, Type stackType) match = P0Regex().Match(source); if (match.Success) { - Type varType = ilg.GetVariableType(ilg.GetVariable(match.Groups["a"].Value)); + Type varType = CodeGenerator.GetVariableType(ilg.GetVariable(match.Groups["a"].Value)); System.Diagnostics.Debug.Assert(varType.IsArray); Type varElementType = varType.GetElementType()!; ilg.ConvertValue(stackType, varElementType); @@ -3273,7 +3273,7 @@ private void WriteElement(string source, string? arrayName, string? choiceSource isWrappedAny ? new Type[] { typeof(IXmlSerializable), typeof(bool) } : new Type[] { typeof(IXmlSerializable) } )!; ilg.Ldarg(0); - RaCodeGen.ILGenForCreateInstance(ilg, sm.TypeDesc!.Type!, sm.TypeDesc.CannotNew, false); + ReflectionAwareILGen.ILGenForCreateInstance(ilg, sm.TypeDesc!.Type!, sm.TypeDesc.CannotNew, false); if (sm.TypeDesc.CannotNew) ilg.ConvertValue(typeof(object), typeof(IXmlSerializable)); if (isWrappedAny) @@ -3306,7 +3306,7 @@ private void WriteElement(string source, string? arrayName, string? choiceSource WriteSourceBegin(choiceSource!); CodeIdentifier.CheckValidIdentifier(choice.MemberIds![elementIndex]); - RaCodeGen.ILGenForEnumMember(ilg, choice.Mapping!.TypeDesc!.Type!, choice.MemberIds[elementIndex]); + ReflectionAwareILGen.ILGenForEnumMember(ilg, choice.Mapping!.TypeDesc!.Type!, choice.MemberIds[elementIndex]); WriteSourceEnd(choiceSource!, choice.Mapping.TypeDesc.Type!); } } @@ -3345,7 +3345,7 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp isWrappedAny ? new Type[] { typeof(IXmlSerializable), typeof(bool) } : new Type[] { typeof(IXmlSerializable) } )!; ilg.Ldarg(0); - RaCodeGen.ILGenForCreateInstance(ilg, derived.TypeDesc!.Type!, derived.TypeDesc.CannotNew, false); + ReflectionAwareILGen.ILGenForCreateInstance(ilg, derived.TypeDesc!.Type!, derived.TypeDesc.CannotNew, false); if (derived.TypeDesc.CannotNew) ilg.ConvertValue(typeof(object), typeof(IXmlSerializable)); if (isWrappedAny) @@ -3473,7 +3473,7 @@ private void WriteCreateMapping(TypeMapping mapping, string local) { ilg.BeginExceptionBlock(); } - RaCodeGen.ILGenForCreateInstance(ilg, mapping.TypeDesc.Type!, mapping.TypeDesc.CannotNew, true); + ReflectionAwareILGen.ILGenForCreateInstance(ilg, mapping.TypeDesc.Type!, mapping.TypeDesc.CannotNew, true); ilg.Stloc(loc); if (ctorInaccessible) { @@ -3513,19 +3513,19 @@ private void WriteCatchException(Type exceptionType) [RequiresUnreferencedCode("calls WriteArrayLocalDecl")] private void WriteArrayLocalDecl(string typeName, string variableName, string initValue, TypeDesc arrayTypeDesc) { - RaCodeGen.WriteArrayLocalDecl(typeName, variableName, new SourceInfo(initValue, initValue, null, arrayTypeDesc.Type, ilg), arrayTypeDesc); + ReflectionAwareILGen.WriteArrayLocalDecl(typeName, variableName, new SourceInfo(initValue, initValue, null, arrayTypeDesc.Type, ilg), arrayTypeDesc); } [RequiresUnreferencedCode("calls WriteCreateInstance")] private void WriteCreateInstance(string source, bool ctorInaccessible, Type type) { - RaCodeGen.WriteCreateInstance(source, ctorInaccessible, type, ilg); + ReflectionAwareILGen.WriteCreateInstance(source, ctorInaccessible, type, ilg); } [RequiresUnreferencedCode("calls WriteLocalDecl")] - private void WriteLocalDecl(string variableName, SourceInfo initValue) + private static void WriteLocalDecl(string variableName, SourceInfo initValue) { - RaCodeGen.WriteLocalDecl(variableName, initValue); + ReflectionAwareILGen.WriteLocalDecl(variableName, initValue); } [RegexGenerator("UnknownNode[(]null, @[\"](?[^\"]*)[\"][)];")] 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 a91cdfc768511..d250d23566290 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 @@ -45,7 +45,6 @@ internal void Init(XmlWriter w, XmlSerializerNamespaces? namespaces, string? enc _namespaces = namespaces; _soap12 = (encodingStyle == Soap12.Encoding); _idBase = idBase; - Init(tempAssembly); } protected bool EscapeName @@ -534,7 +533,7 @@ protected void WriteStartElement(string name, string? ns, object? o, bool writeP WriteNamespaceDeclarations(xmlns); } - private HashSet? ListUsedPrefixes(XmlSerializerNamespaces nsList, string prefix) + private static HashSet? ListUsedPrefixes(XmlSerializerNamespaces nsList, string prefix) { var qnIndexes = new HashSet(); int prefixLength = prefix.Length; @@ -1881,7 +1880,7 @@ internal string GetStringForEnumCompare(EnumMapping mapping, string memberName, string memberAccess = GetStringForEnumMember(mapping.TypeDesc!.CSharpName, memberName, useReflection); return GetStringForEnumLongValue(memberAccess, useReflection); } - internal string GetStringForEnumLongValue(string variable, bool useReflection) + internal static string GetStringForEnumLongValue(string variable, bool useReflection) { if (useReflection) return $"{typeof(Convert).FullName}.ToInt64({variable})"; @@ -1975,7 +1974,7 @@ internal string GetStringForCreateInstance(string escapedTypeName, bool useRefle return GetStringForCreateInstance(GetStringForTypeof(escapedTypeName, useReflection), cast && !useReflection ? escapedTypeName : null, ctorInaccessible, arg); } - internal string GetStringForCreateInstance(string type, string? cast, bool nonPublic, string? arg) + internal static string GetStringForCreateInstance(string type, string? cast, bool nonPublic, string? arg) { StringBuilder createInstance = new StringBuilder(); if (cast != null && cast.Length > 0) @@ -2431,7 +2430,7 @@ private void WritePrimitive(string method, string name, string? ns, object? defa Writer.Write("if ("); if (mapping.TypeDesc!.UseReflection) - Writer.Write(RaCodeGen.GetStringForEnumLongValue(source, mapping.TypeDesc.UseReflection)); + Writer.Write(ReflectionAwareCodeGen.GetStringForEnumLongValue(source, mapping.TypeDesc.UseReflection)); else Writer.Write(source); Writer.Write(" != "); @@ -2859,7 +2858,7 @@ private void WriteEnumMethod(EnumMapping mapping) { Hashtable values = new Hashtable(); if (mapping.TypeDesc.UseReflection) - Writer.WriteLine($"switch ({RaCodeGen.GetStringForEnumLongValue("v", mapping.TypeDesc.UseReflection)} ){{"); + Writer.WriteLine($"switch ({ReflectionAwareCodeGen.GetStringForEnumLongValue("v", mapping.TypeDesc.UseReflection)} ){{"); else Writer.WriteLine("switch (v) {"); Writer.Indent++; @@ -2880,7 +2879,7 @@ private void WriteEnumMethod(EnumMapping mapping) if (mapping.IsFlags) { Writer.Write("default: s = FromEnum("); - Writer.Write(RaCodeGen.GetStringForEnumLongValue("v", mapping.TypeDesc.UseReflection)); + Writer.Write(ReflectionAwareCodeGen.GetStringForEnumLongValue("v", mapping.TypeDesc.UseReflection)); Writer.Write(", new string[] {"); Writer.Indent++; for (int i = 0; i < constants.Length; i++) @@ -2918,7 +2917,7 @@ private void WriteEnumMethod(EnumMapping mapping) else { Writer.Write("default: throw CreateInvalidEnumValueException("); - Writer.Write(RaCodeGen.GetStringForEnumLongValue("v", mapping.TypeDesc.UseReflection)); + Writer.Write(ReflectionAwareCodeGen.GetStringForEnumLongValue("v", mapping.TypeDesc.UseReflection)); Writer.Write(".ToString(System.Globalization.CultureInfo.InvariantCulture), "); WriteQuotedCSharpString(mapping.TypeDesc.FullName); Writer.WriteLine(");"); @@ -3661,7 +3660,7 @@ private void WriteElements(string source, string? enumSource, ElementAccessor[] if (wroteFirstIf) Writer.Write("else "); else wroteFirstIf = true; Writer.Write("if ("); - Writer.Write(enumUseReflection ? RaCodeGen.GetStringForEnumLongValue(enumSource!, enumUseReflection) : enumSource); + Writer.Write(enumUseReflection ? ReflectionAwareCodeGen.GetStringForEnumLongValue(enumSource!, enumUseReflection) : enumSource); Writer.Write(" == "); Writer.Write(enumFullName); if (isNullable && !element.IsNullable) @@ -3734,7 +3733,7 @@ private void WriteElements(string source, string? enumSource, ElementAccessor[] bool enumUseReflection = choice.Mapping!.TypeDesc!.UseReflection; enumFullName = (enumUseReflection ? "" : $"{enumTypeName}.@") + FindChoiceEnumValue(element, (EnumMapping)choice.Mapping, enumUseReflection); Writer.Write("if ("); - Writer.Write(enumUseReflection ? RaCodeGen.GetStringForEnumLongValue(enumSource!, enumUseReflection) : enumSource); + Writer.Write(enumUseReflection ? ReflectionAwareCodeGen.GetStringForEnumLongValue(enumSource!, enumUseReflection) : enumSource); Writer.Write(" == "); Writer.Write(enumFullName); if (isNullable && !element.IsNullable) @@ -4363,7 +4362,7 @@ private void WriteNamespaces(string source) Writer.WriteLine(");"); } - private int FindXmlnsIndex(MemberMapping[] members) + private static int FindXmlnsIndex(MemberMapping[] members) { for (int i = 0; i < members.Length; i++) { @@ -4418,7 +4417,7 @@ private void WriteEnumCase(string fullTypeName, ConstantMapping c, bool useRefle RaCodeGen.WriteEnumCase(fullTypeName, c, useReflection); } - private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMapping, bool useReflection) + private static string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMapping, bool useReflection) { string? enumValue = null; 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 2b865d46501e7..67fe92c5093c8 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 @@ -42,7 +42,7 @@ internal void GenerateBegin() MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc!.Name)); } } - RaCodeGen.WriteReflectionInit(scope); + ReflectionAwareILGen.WriteReflectionInit(scope); } } @@ -338,7 +338,7 @@ private void WriteEndElement(string source) object oVar = ilg.GetVariable(source); ilg.Ldarg(0); ilg.Load(oVar); - ilg.ConvertValue(ilg.GetVariableType(oVar), typeof(object)); + ilg.ConvertValue(CodeGenerator.GetVariableType(oVar), typeof(object)); ilg.Call(XmlSerializationWriter_WriteEndElement); } @@ -660,7 +660,7 @@ private void WriteEnumMethod(EnumMapping mapping) ilg.Br(endSwitchLabel); } ilg.MarkLabel(defaultLabel); - RaCodeGen.ILGenForEnumLongValue(ilg, "v"); + ReflectionAwareILGen.ILGenForEnumLongValue(ilg, "v"); LocalBuilder strArray = ilg.DeclareLocal(typeof(string[]), "strArray"); ilg.NewArray(typeof(string), constants.Length); ilg.Stloc(strArray); @@ -765,7 +765,7 @@ private void WriteDerivedTypes(StructMapping mapping) argTypes.Add(typeof(string)); ilg.Ldarg("ns"); object oVar = ilg.GetVariable("o"); - Type oType = ilg.GetVariableType(oVar); + Type oType = CodeGenerator.GetVariableType(oVar); ilg.Load(oVar); ilg.ConvertValue(oType, derived.TypeDesc.Type!); argTypes.Add(derived.TypeDesc.Type!); @@ -849,7 +849,7 @@ private void WriteEnumAndArrayTypes() object oVar = ilg.GetVariable("o"); ilg.Ldarg(0); ilg.Load(oVar); - ilg.ConvertValue(ilg.GetVariableType(oVar), mapping.TypeDesc.Type!); + ilg.ConvertValue(CodeGenerator.GetVariableType(oVar), mapping.TypeDesc.Type!); ilg.Call(methodBuilder); ilg.Call(XmlWriter_WriteString); MethodInfo XmlWriter_WriteEndElement = typeof(XmlWriter).GetMethod( @@ -1037,7 +1037,7 @@ private void WriteStructMethod(StructMapping mapping) { MemberMapping member = members[xmlnsMember]; CodeIdentifier.CheckValidIdentifier(member.Name); - xmlnsSource = RaCodeGen.GetStringForMember("o", member.Name, mapping.TypeDesc); + xmlnsSource = ReflectionAwareILGen.GetStringForMember("o", member.Name, mapping.TypeDesc); } ilg.Ldarg(0); @@ -1091,11 +1091,11 @@ private void WriteStructMethod(StructMapping mapping) } if (m.CheckSpecified != SpecifiedAccessor.None) { - string memberGet = RaCodeGen.GetStringForMember("o", $"{m.Name}Specified", mapping.TypeDesc); + string memberGet = ReflectionAwareILGen.GetStringForMember("o", $"{m.Name}Specified", mapping.TypeDesc); ILGenLoad(memberGet); ilg.If(); } - WriteMember(RaCodeGen.GetSourceForMember("o", m, mapping.TypeDesc, ilg), m.Attribute, m.TypeDesc!, "o"); + WriteMember(ReflectionAwareILGen.GetSourceForMember("o", m, mapping.TypeDesc, ilg), m.Attribute, m.TypeDesc!, "o"); if (m.CheckSpecified != SpecifiedAccessor.None) { @@ -1124,7 +1124,7 @@ private void WriteStructMethod(StructMapping mapping) } if (m.CheckSpecified != SpecifiedAccessor.None) { - string memberGet = RaCodeGen.GetStringForMember("o", $"{m.Name}Specified", mapping.TypeDesc); + string memberGet = ReflectionAwareILGen.GetStringForMember("o", $"{m.Name}Specified", mapping.TypeDesc); ILGenLoad(memberGet); ilg.If(); } @@ -1133,10 +1133,10 @@ private void WriteStructMethod(StructMapping mapping) if (m.ChoiceIdentifier != null) { CodeIdentifier.CheckValidIdentifier(m.ChoiceIdentifier.MemberName); - choiceSource = RaCodeGen.GetStringForMember("o", m.ChoiceIdentifier.MemberName, mapping.TypeDesc); + choiceSource = ReflectionAwareILGen.GetStringForMember("o", m.ChoiceIdentifier.MemberName, mapping.TypeDesc); } - WriteMember(RaCodeGen.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, mapping.TypeDesc, ilg), choiceSource, m.ElementsSortedByDerivation!, m.Text, m.ChoiceIdentifier, m.TypeDesc!, true); if (m.CheckSpecified != SpecifiedAccessor.None) { @@ -1222,7 +1222,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, RaCodeGen.GetStringForArrayMember(aVar, iVar, memberTypeDesc), arrayElementTypeDesc.Type!); + WriteLocalDecl(aiVar, ReflectionAwareILGen.GetStringForArrayMember(aVar, iVar, memberTypeDesc), arrayElementTypeDesc.Type!); } if (attribute.IsList) { @@ -1564,16 +1564,16 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor? text, Cho int count = elements.Length + (text == null ? 0 : 1); if (count > 1) { - WriteLocalDecl(arrayNamePlusI, RaCodeGen.GetStringForArrayMember(arrayName, iPlusArrayName, arrayTypeDesc), arrayElementTypeDesc.Type!); + WriteLocalDecl(arrayNamePlusI, ReflectionAwareILGen.GetStringForArrayMember(arrayName, iPlusArrayName, arrayTypeDesc), arrayElementTypeDesc.Type!); if (choice != null) { - WriteLocalDecl($"{choiceName}i", RaCodeGen.GetStringForArrayMember(choiceName, iPlusArrayName, choice.Mapping!.TypeDesc!), choice.Mapping.TypeDesc!.Type!); + WriteLocalDecl($"{choiceName}i", ReflectionAwareILGen.GetStringForArrayMember(choiceName, iPlusArrayName, choice.Mapping!.TypeDesc!), 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(RaCodeGen.GetStringForArrayMember(arrayName, iPlusArrayName, arrayTypeDesc), null, null, arrayElementTypeDesc.Type, ilg), null, elements, text, choice, arrayNamePlusA, true, arrayElementTypeDesc.IsNullable); + WriteElements(new SourceInfo(ReflectionAwareILGen.GetStringForArrayMember(arrayName, iPlusArrayName, arrayTypeDesc), null, null, arrayElementTypeDesc.Type, ilg), null, elements, text, choice, arrayNamePlusA, true, arrayElementTypeDesc.IsNullable); } ilg.EndFor(); } @@ -2228,7 +2228,7 @@ private void WriteNamespaces(string source) ilg.Call(XmlSerializationWriter_WriteNamespaceDeclarations); } - private int FindXmlnsIndex(MemberMapping[] members) + private static int FindXmlnsIndex(MemberMapping[] members) { for (int i = 0; i < members.Length; i++) { @@ -2242,31 +2242,31 @@ private int FindXmlnsIndex(MemberMapping[] members) [RequiresUnreferencedCode("calls WriteLocalDecl")] private void WriteLocalDecl(string variableName, string initValue, Type type) { - RaCodeGen.WriteLocalDecl(variableName, new SourceInfo(initValue, initValue, null, type, ilg)); + ReflectionAwareILGen.WriteLocalDecl(variableName, new SourceInfo(initValue, initValue, null, type, ilg)); } [RequiresUnreferencedCode("calls WriteArrayLocalDecl")] - private void WriteArrayLocalDecl(string typeName, string variableName, SourceInfo initValue, TypeDesc arrayTypeDesc) + private static void WriteArrayLocalDecl(string typeName, string variableName, SourceInfo initValue, TypeDesc arrayTypeDesc) { - RaCodeGen.WriteArrayLocalDecl(typeName, variableName, initValue, arrayTypeDesc); + ReflectionAwareILGen.WriteArrayLocalDecl(typeName, variableName, initValue, arrayTypeDesc); } private void WriteTypeCompare(string variable, Type type) { - RaCodeGen.WriteTypeCompare(variable, type, ilg); + ReflectionAwareILGen.WriteTypeCompare(variable, type, ilg); } [RequiresUnreferencedCode("calls WriteInstanceOf")] private void WriteInstanceOf(SourceInfo source, Type type) { - RaCodeGen.WriteInstanceOf(source, type, ilg); + ReflectionAwareILGen.WriteInstanceOf(source, type, ilg); } private void WriteArrayTypeCompare(string variable, Type arrayType) { - RaCodeGen.WriteArrayTypeCompare(variable, arrayType, ilg); + ReflectionAwareILGen.WriteArrayTypeCompare(variable, arrayType, ilg); } - private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMapping, out object? eValue) + private static string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMapping, out object? eValue) { string? enumValue = null; eValue = null; @@ -2335,7 +2335,7 @@ internal sealed class ReflectionAwareILGen internal ReflectionAwareILGen() { } [RequiresUnreferencedCode("calls GetTypeDesc")] - internal void WriteReflectionInit(TypeScope scope) + internal static void WriteReflectionInit(TypeScope scope) { foreach (Type type in scope.Types) { @@ -2343,49 +2343,45 @@ internal void WriteReflectionInit(TypeScope scope) } } - internal void ILGenForEnumLongValue(CodeGenerator ilg, string variable) + internal static void ILGenForEnumLongValue(CodeGenerator ilg, string variable) { ArgBuilder argV = ilg.GetArg(variable); ilg.Ldarg(argV); ilg.ConvertValue(argV.ArgType, typeof(long)); } - internal string GetStringForTypeof(string typeFullName) + internal static string GetStringForTypeof(string typeFullName) { - { - return $"typeof({typeFullName})"; - } + return $"typeof({typeFullName})"; } - internal string GetStringForMember(string obj, string memberName, TypeDesc typeDesc) + internal static string GetStringForMember(string obj, string memberName, TypeDesc typeDesc) { return $"{obj}.@{memberName}"; } - internal SourceInfo GetSourceForMember(string obj, MemberMapping member, TypeDesc typeDesc, CodeGenerator ilg) + internal static SourceInfo GetSourceForMember(string obj, MemberMapping member, TypeDesc typeDesc, CodeGenerator ilg) { return GetSourceForMember(obj, member, member.MemberInfo, typeDesc, ilg); } - internal SourceInfo GetSourceForMember(string obj, MemberMapping member, MemberInfo? memberInfo, TypeDesc typeDesc, CodeGenerator ilg) + internal static SourceInfo GetSourceForMember(string obj, MemberMapping member, MemberInfo? memberInfo, TypeDesc typeDesc, CodeGenerator ilg) { return new SourceInfo(GetStringForMember(obj, member.Name, typeDesc), obj, memberInfo, member.TypeDesc!.Type, ilg); } - internal void ILGenForEnumMember(CodeGenerator ilg, Type type, string memberName) + internal static void ILGenForEnumMember(CodeGenerator ilg, Type type, string memberName) { ilg.Ldc(Enum.Parse(type, memberName, false)); } - internal string GetStringForArrayMember(string? arrayName, string subscript, TypeDesc arrayTypeDesc) + internal static string GetStringForArrayMember(string? arrayName, string subscript, TypeDesc arrayTypeDesc) { - { - return $"{arrayName}[{subscript}]"; - } + return $"{arrayName}[{subscript}]"; } - internal string GetStringForMethod(string obj, string typeFullName, string memberName) + internal static string GetStringForMethod(string obj, string typeFullName, string memberName) { return $"{obj}.{memberName}("; } [RequiresUnreferencedCode("calls ILGenForCreateInstance")] - internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, bool ctorInaccessible, bool cast) + internal static void ILGenForCreateInstance(CodeGenerator ilg, Type type, bool ctorInaccessible, bool cast) { if (!ctorInaccessible) { @@ -2409,7 +2405,7 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, bool ctorInac } [RequiresUnreferencedCode("calls GetType")] - internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type? cast, bool nonPublic) + internal static void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type? cast, bool nonPublic) { // Special case DBNull if (type == typeof(DBNull)) @@ -2518,7 +2514,7 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type? cast, b } [RequiresUnreferencedCode("calls LoadMember")] - internal void WriteLocalDecl(string variableName, SourceInfo initValue) + internal static void WriteLocalDecl(string variableName, SourceInfo initValue) { Type localType = initValue.Type!; LocalBuilder localA = initValue.ILG.DeclareOrGetLocal(localType, variableName); @@ -2544,7 +2540,7 @@ internal void WriteLocalDecl(string variableName, SourceInfo initValue) { string[] vars = initValue.Source.Split('.'); object fixup = initValue.ILG.GetVariable(vars[0]); - PropertyInfo propInfo = initValue.ILG.GetVariableType(fixup).GetProperty(vars[1])!; + PropertyInfo propInfo = CodeGenerator.GetVariableType(fixup).GetProperty(vars[1])!; initValue.ILG.LoadMember(fixup, propInfo); initValue.ILG.ConvertValue(propInfo.PropertyType, localA.LocalType); } @@ -2552,7 +2548,7 @@ internal void WriteLocalDecl(string variableName, SourceInfo initValue) { object sVar = initValue.ILG.GetVariable(initValue.Arg); initValue.ILG.Load(sVar); - initValue.ILG.ConvertValue(initValue.ILG.GetVariableType(sVar), localA.LocalType); + initValue.ILG.ConvertValue(CodeGenerator.GetVariableType(sVar), localA.LocalType); } } initValue.ILG.Stloc(localA); @@ -2560,7 +2556,7 @@ internal void WriteLocalDecl(string variableName, SourceInfo initValue) } [RequiresUnreferencedCode("calls ILGenForCreateInstance")] - internal void WriteCreateInstance(string source, bool ctorInaccessible, Type type, CodeGenerator ilg) + internal static void WriteCreateInstance(string source, bool ctorInaccessible, Type type, CodeGenerator ilg) { LocalBuilder sLoc = ilg.DeclareOrGetLocal(type, source); ILGenForCreateInstance(ilg, type, ctorInaccessible, ctorInaccessible); @@ -2568,7 +2564,7 @@ internal void WriteCreateInstance(string source, bool ctorInaccessible, Type typ } [RequiresUnreferencedCode("calls Load")] - internal void WriteInstanceOf(SourceInfo source, Type type, CodeGenerator ilg) + internal static void WriteInstanceOf(SourceInfo source, Type type, CodeGenerator ilg) { { source.Load(typeof(object)); @@ -2580,7 +2576,7 @@ internal void WriteInstanceOf(SourceInfo source, Type type, CodeGenerator ilg) } [RequiresUnreferencedCode("calls Load")] - internal void WriteArrayLocalDecl(string typeName, string variableName, SourceInfo initValue, TypeDesc arrayTypeDesc) + internal static void WriteArrayLocalDecl(string typeName, string variableName, SourceInfo initValue, TypeDesc arrayTypeDesc) { Debug.Assert(typeName == arrayTypeDesc.CSharpName || typeName == $"{arrayTypeDesc.CSharpName}[]"); Type localType = (typeName == arrayTypeDesc.CSharpName) ? arrayTypeDesc.Type! : arrayTypeDesc.Type!.MakeArrayType(); @@ -2592,7 +2588,7 @@ internal void WriteArrayLocalDecl(string typeName, string variableName, SourceIn initValue.ILG.Stloc(local); } } - internal void WriteTypeCompare(string variable, Type type, CodeGenerator ilg) + internal static void WriteTypeCompare(string variable, Type type, CodeGenerator ilg) { Debug.Assert(type != null); Debug.Assert(ilg != null); @@ -2600,7 +2596,7 @@ internal void WriteTypeCompare(string variable, Type type, CodeGenerator ilg) ilg.Ldc(type); ilg.Ceq(); } - internal void WriteArrayTypeCompare(string variable, Type arrayType, CodeGenerator ilg) + internal static void WriteArrayTypeCompare(string variable, Type arrayType, CodeGenerator ilg) { { Debug.Assert(arrayType != null); 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 b77f9824dd984..cf2beede63959 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 @@ -275,7 +275,7 @@ public XmlSerializer(Type type!!, XmlAttributeOverrides? overrides, Type[]? extr } [RequiresUnreferencedCode("calls ImportTypeMapping")] - private XmlTypeMapping GenerateXmlTypeMapping(Type type, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace) + private static XmlTypeMapping GenerateXmlTypeMapping(Type type, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace) { XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace); if (extraTypes != null) @@ -377,14 +377,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); - try - { - Serialize(o, writer); - } - finally - { - writer.Dispose(); - } + Serialize(o, writer); } else { @@ -476,14 +469,7 @@ private XmlMapping GetMapping() { XmlSerializationReader reader = CreateReader(); reader.Init(xmlReader, events, encodingStyle, _tempAssembly); - try - { - return Deserialize(reader); - } - finally - { - reader.Dispose(); - } + return Deserialize(reader); } else { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Query.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Query.cs index 3d08b72aee913..d79bde89ac977 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Query.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Query.cs @@ -182,7 +182,7 @@ public static XmlNodeOrder CompareNodes(XPathNavigator l, XPathNavigator r) // On my best knowledge this happens only in XsltContext.ResolveFunction() / IXsltContextFunction.ReturnType - protected XPathResultType GetXPathType(object value) + protected static XPathResultType GetXPathType(object value) { if (value is XPathNodeIterator) return XPathResultType.NodeSet; if (value is string) return XPathResultType.String; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathDocument.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathDocument.cs index f7fb25d6ddb13..2568429bb77d2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathDocument.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathDocument.cs @@ -441,7 +441,7 @@ internal int LookupIdElement(string id, out XPathNode[]? pageElem) /// /// Set properties on the reader so that it is backwards-compatible with V1. /// - private XmlTextReaderImpl SetupReader(XmlTextReaderImpl reader) + private static XmlTextReaderImpl SetupReader(XmlTextReaderImpl reader) { reader.EntityHandling = EntityHandling.ExpandEntities; reader.XmlValidatingReaderCompatibilityMode = true; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs index 360ededdb57ce..1d6c7591fcbc6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs @@ -1087,7 +1087,7 @@ public virtual bool CheckValidity(XmlSchemaSet schemas, ValidationEventHandler v return validityTracker.IsValid; } - private XmlReader GetValidatingReader(XmlReader reader, XmlSchemaSet schemas, ValidationEventHandler validationEvent, XmlSchemaType? schemaType, XmlSchemaElement? schemaElement, XmlSchemaAttribute? schemaAttribute) + private static XmlReader GetValidatingReader(XmlReader reader, XmlSchemaSet schemas, ValidationEventHandler validationEvent, XmlSchemaType? schemaType, XmlSchemaElement? schemaElement, XmlSchemaAttribute? schemaAttribute) { if (schemaAttribute != null) { @@ -1839,7 +1839,7 @@ private static int GetDepth(XPathNavigator nav) // namespace(0) ?(0) before(-1) before(-2) // attribute(1) after(1) ?(0) before(-1) // other (2) after(2) after(1) ?(0) - private XmlNodeOrder CompareSiblings(XPathNavigator n1, XPathNavigator n2) + private static XmlNodeOrder CompareSiblings(XPathNavigator n1, XPathNavigator n2) { int cmp = 0; @@ -2043,7 +2043,7 @@ private XmlReader CreateContextReader(string xml!!, bool fromCurrentNode) return reader; } - internal void BuildSubtree(XmlReader reader, XmlWriter writer) + internal static void BuildSubtree(XmlReader reader, XmlWriter writer) { // important (perf) string literal... string xmlnsUri = XmlReservedNs.NsXmlNs; // http://www.w3.org/2000/xmlns/ diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManager.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManager.cs index 9ceef6da61f9c..83ebba25199ec 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManager.cs @@ -9,7 +9,7 @@ namespace System.Xml { internal sealed partial class XmlDownloadManager { - internal Stream GetStream(Uri uri, ICredentials? credentials, IWebProxy? proxy) + internal static Stream GetStream(Uri uri, ICredentials? credentials, IWebProxy? proxy) { if (uri.Scheme == "file") { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManagerAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManagerAsync.cs index 1e5efb99d35d7..c2d774d0f4006 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManagerAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManagerAsync.cs @@ -11,7 +11,7 @@ namespace System.Xml { internal sealed partial class XmlDownloadManager { - internal Task GetStreamAsync(Uri uri, ICredentials? credentials, IWebProxy? proxy) + internal static Task GetStreamAsync(Uri uri, ICredentials? credentials, IWebProxy? proxy) { if (uri.Scheme == "file") { @@ -24,7 +24,7 @@ internal Task GetStreamAsync(Uri uri, ICredentials? credentials, IWebPro } } - private async Task GetNonFileStreamAsync(Uri uri, ICredentials? credentials, IWebProxy? proxy) + private static async Task GetNonFileStreamAsync(Uri uri, ICredentials? credentials, IWebProxy? proxy) { var handler = new HttpClientHandler(); using (var client = new HttpClient(handler)) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlEncoding.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlEncoding.cs index 05029d3ab6b49..fd40fcdbb1129 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlEncoding.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlEncoding.cs @@ -536,7 +536,7 @@ public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] } } - internal void Ucs4ToUTF16(uint code, char[] chars, int charIndex) + internal static void Ucs4ToUTF16(uint code, char[] chars, int charIndex) { chars[charIndex] = (char)(XmlCharType.SurHighStart + (char)((code >> 16) - 1) + (char)((code >> 10) & 0x3F)); chars[charIndex + 1] = (char)(XmlCharType.SurLowStart + (char)(code & 0x3FF)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolver.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolver.cs index 3f39f1ab09d57..558ad2e4b0218 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolver.cs @@ -44,7 +44,7 @@ public RequestCachePolicy CachePolicy { if (ofObjectToReturn is null || ofObjectToReturn == typeof(System.IO.Stream) || ofObjectToReturn == typeof(object)) { - return DownloadManager.GetStream(absoluteUri, _credentials, _proxy); + return XmlDownloadManager.GetStream(absoluteUri, _credentials, _proxy); } throw new XmlException(SR.Xml_UnsupportedClass, string.Empty); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolverAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolverAsync.cs index 62125f9d8042b..17ac98df3eb8b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolverAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolverAsync.cs @@ -13,7 +13,7 @@ public override async Task GetEntityAsync(Uri absoluteUri, string? role, { if (ofObjectToReturn == null || ofObjectToReturn == typeof(System.IO.Stream) || ofObjectToReturn == typeof(object)) { - return await DownloadManager.GetStreamAsync(absoluteUri, _credentials, _proxy).ConfigureAwait(false); + return await XmlDownloadManager.GetStreamAsync(absoluteUri, _credentials, _proxy).ConfigureAwait(false); } throw new XmlException(SR.Xml_UnsupportedClass, string.Empty); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/GenerateHelper.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/GenerateHelper.cs index 6df4baafd7bd9..ced264ac2e092 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/GenerateHelper.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/GenerateHelper.cs @@ -803,6 +803,7 @@ public void TailCall(MethodInfo meth) Emit(OpCodes.Ret); } +#pragma warning disable CA1822 [Conditional("DEBUG")] private void TraceCall(OpCode opcode, MethodInfo meth) { @@ -830,6 +831,7 @@ private void TraceCall(OpCode opcode, MethodInfo meth) } #endif } +#pragma warning restore CA1822 public void Call(MethodInfo meth) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs index 71fad3e186cda..8900458587a3c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs @@ -770,7 +770,7 @@ private void EndLoop(XmlQueryType typ, XmlILConstructInfo info) /// /// Return true if an instance of the specified type might be an attribute or a namespace node. /// - private bool MaybeAttrNmsp(XmlQueryType typ) + private static bool MaybeAttrNmsp(XmlQueryType typ) { return (typ.NodeKinds & (XmlNodeKindFlags.Attribute | XmlNodeKindFlags.Namespace)) != XmlNodeKindFlags.None; } @@ -778,7 +778,7 @@ private bool MaybeAttrNmsp(XmlQueryType typ) /// /// Return true if an instance of the specified type might be a non-empty content type (attr/nsmp don't count). /// - private bool MaybeContent(XmlQueryType typ) + private static bool MaybeContent(XmlQueryType typ) { return !typ.IsNode || (typ.NodeKinds & ~(XmlNodeKindFlags.Attribute | XmlNodeKindFlags.Namespace)) != XmlNodeKindFlags.None; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs index 513066fcbedc6..0c7db85e7bb84 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs @@ -5112,7 +5112,7 @@ protected override QilNode VisitRoot(QilUnary root) /// /// Returns true if any operator within the "expr" subtree references "target". /// - private bool DependsOn(QilNode expr, QilNode target) + private static bool DependsOn(QilNode expr, QilNode target) { return new NodeFinder().Find(expr, target); } @@ -5120,7 +5120,7 @@ private bool DependsOn(QilNode expr, QilNode target) /// /// Returns true if there is no PositionOf operator within the "expr" subtree that references iterator "iter". /// - private bool NonPositional(QilNode expr, QilNode iter) + private static bool NonPositional(QilNode expr, QilNode iter) { return !(new PositionOfFinder().Find(expr, iter)); } @@ -5167,7 +5167,7 @@ private bool IsGlobalValue(QilNode nd) /// /// Return true if "typ" is xs:decimal=, xs:integer=, xs:int=, xs:double=, or xs:float=. /// - private bool IsPrimitiveNumeric(XmlQueryType? typ) + private static bool IsPrimitiveNumeric(XmlQueryType? typ) { if (typ == XmlQueryTypeFactory.IntX) return true; if (typ == XmlQueryTypeFactory.IntegerX) return true; @@ -5181,7 +5181,7 @@ private bool IsPrimitiveNumeric(XmlQueryType? typ) /// /// Returns true if "typ" matches one of the XPath content node tests: *, text(), comment(), pi(), or node(). /// - private bool MatchesContentTest(XmlQueryType typ) + private static bool MatchesContentTest(XmlQueryType typ) { if (typ == XmlQueryTypeFactory.Element) return true; if (typ == XmlQueryTypeFactory.Text) return true; @@ -5256,7 +5256,7 @@ private bool IsConstructedExpression(QilNode nd) /// /// True if the specified expression is a literal value. /// - private bool IsLiteral(QilNode nd) + private static bool IsLiteral(QilNode nd) { switch (nd.NodeType) { @@ -5276,7 +5276,7 @@ private bool IsLiteral(QilNode nd) /// /// Return true if all children of "nd" are constant. /// - private bool AreLiteralArgs(QilNode nd) + private static bool AreLiteralArgs(QilNode nd) { foreach (QilNode child in nd) if (!IsLiteral(child)) @@ -5288,7 +5288,7 @@ private bool AreLiteralArgs(QilNode nd) /// /// Extract the value of a literal. /// - private object ExtractLiteralValue(QilNode nd) + private static object ExtractLiteralValue(QilNode nd) { if (nd.NodeType == QilNodeType.True) return true; @@ -5304,7 +5304,7 @@ private object ExtractLiteralValue(QilNode nd) /// /// Return true if "nd" has a child of type Sequence. /// - private bool HasNestedSequence(QilNode nd) + private static bool HasNestedSequence(QilNode nd) { foreach (QilNode child in nd) { @@ -5317,7 +5317,7 @@ private bool HasNestedSequence(QilNode nd) /// /// True if the JoinAndDod pattern is allowed to match the specified node. /// - private bool AllowJoinAndDod(QilNode nd) + private static bool AllowJoinAndDod(QilNode nd) { OptimizerPatterns patt = OptimizerPatterns.Read(nd); @@ -5338,7 +5338,7 @@ private bool AllowJoinAndDod(QilNode nd) /// /// True if the DodReverse pattern is allowed to match the specified node. /// - private bool AllowDodReverse(QilNode nd) + private static bool AllowDodReverse(QilNode nd) { OptimizerPatterns patt = OptimizerPatterns.Read(nd); @@ -5588,7 +5588,7 @@ private QilNode FoldArithmetic(QilNodeType opType, QilLiteral left, QilLiteral r /// /// Mark the specified node as matching the Step pattern and set the step node and step input arguments. /// - private void AddStepPattern(QilNode nd, QilNode input) + private static void AddStepPattern(QilNode nd, QilNode input) { OptimizerPatterns patt = OptimizerPatterns.Write(nd); patt.AddPattern(OptimizerPatternName.Step); @@ -5599,7 +5599,7 @@ private void AddStepPattern(QilNode nd, QilNode input) /// /// Return true if "nd" matches the Step pattern and the StepType argument is equal to "stepType". /// - private bool IsDocOrderDistinct(QilNode nd) + private static bool IsDocOrderDistinct(QilNode nd) { return OptimizerPatterns.Read(nd).MatchesPattern(OptimizerPatternName.IsDocOrderDistinct); } @@ -5607,7 +5607,7 @@ private bool IsDocOrderDistinct(QilNode nd) /// /// Return true if "nd" matches the Step pattern and the StepType argument is equal to "stepType". /// - private bool IsStepPattern(QilNode nd, QilNodeType stepType) + private static bool IsStepPattern(QilNode nd, QilNodeType stepType) { return IsStepPattern(OptimizerPatterns.Read(nd), stepType); } @@ -5615,7 +5615,7 @@ private bool IsStepPattern(QilNode nd, QilNodeType stepType) /// /// Return true if "patt" matches the Step pattern and the StepType argument is equal to "stepType". /// - private bool IsStepPattern(OptimizerPatterns patt, QilNodeType stepType) + private static bool IsStepPattern(OptimizerPatterns patt, QilNodeType stepType) { return patt.MatchesPattern(OptimizerPatternName.Step) && ((QilNode)patt.GetArgument(OptimizerPatternArgument.StepNode)).NodeType == stepType; } 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 6e893aadb868c..acc522636f0ec 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 @@ -3821,7 +3821,7 @@ protected override QilNode VisitXsltConvert(QilTargetType ndConv) /// Get the XsltConvert method that converts from "typSrc" to "typDst". Return false if no /// such method exists. This conversion matrix should match the one in XsltConvert.ExternalValueToExternalValue. /// - private bool GetXsltConvertMethod(XmlQueryType typSrc, XmlQueryType typDst, out MethodInfo? meth) + private static bool GetXsltConvertMethod(XmlQueryType typSrc, XmlQueryType typDst, out MethodInfo? meth) { meth = null; @@ -4465,7 +4465,7 @@ private void EndWriterLoop(QilNode nd, bool hasOnEnd, Label lblOnEnd) /// Returns true if the specified node's owner element might have local namespaces added to it /// after attributes have already been added. /// - private bool MightHaveNamespacesAfterAttributes(XmlILConstructInfo? info) + private static bool MightHaveNamespacesAfterAttributes(XmlILConstructInfo? info) { // Get parent element if (info != null) @@ -4482,7 +4482,7 @@ private bool MightHaveNamespacesAfterAttributes(XmlILConstructInfo? info) /// /// Returns true if the specified element should cache attributes. /// - private bool ElementCachesAttributes(XmlILConstructInfo info) + private static bool ElementCachesAttributes(XmlILConstructInfo info) { // Attributes will be cached if namespaces might be constructed after the attributes return info.MightHaveDuplicateAttributes || info.MightHaveNamespacesAfterAttributes; @@ -4536,7 +4536,7 @@ private void AfterEndChecks(QilNode ndCtor) /// /// Return true if a runtime check needs to be made in order to transition into the WithinContent state. /// - private bool CheckWithinContent(XmlILConstructInfo info) + private static bool CheckWithinContent(XmlILConstructInfo info) { switch (info.InitialStates) { @@ -4553,7 +4553,7 @@ private bool CheckWithinContent(XmlILConstructInfo info) /// /// Return true if a runtime check needs to be made in order to transition into the EnumAttrs state. /// - private bool CheckEnumAttrs(XmlILConstructInfo info) + private static bool CheckEnumAttrs(XmlILConstructInfo info) { switch (info.InitialStates) { @@ -4569,7 +4569,7 @@ private bool CheckEnumAttrs(XmlILConstructInfo info) /// /// Map the XmlNodeKindFlags enumeration into the XPathNodeType enumeration. /// - private XPathNodeType QilXmlToXPathNodeType(XmlNodeKindFlags xmlTypes) + private static XPathNodeType QilXmlToXPathNodeType(XmlNodeKindFlags xmlTypes) { switch (xmlTypes) { @@ -4585,7 +4585,7 @@ private XPathNodeType QilXmlToXPathNodeType(XmlNodeKindFlags xmlTypes) /// /// Map a QilExpression constructor type into the XPathNodeType enumeration. /// - private XPathNodeType QilConstructorToNodeType(QilNodeType typ) + private static XPathNodeType QilConstructorToNodeType(QilNodeType typ) { switch (typ) { @@ -4956,7 +4956,7 @@ private bool CachesResult(QilNode nd) /// /// Shortcut call to XmlILTypeHelper.GetStorageType. /// - private Type GetStorageType(QilNode nd) + private static Type GetStorageType(QilNode nd) { return XmlILTypeHelper.GetStorageType(nd.XmlType!); } @@ -4964,7 +4964,7 @@ private Type GetStorageType(QilNode nd) /// /// Shortcut call to XmlILTypeHelper.GetStorageType. /// - private Type GetStorageType(XmlQueryType typ) + private static Type GetStorageType(XmlQueryType typ) { return XmlILTypeHelper.GetStorageType(typ); } @@ -4972,7 +4972,7 @@ private Type GetStorageType(XmlQueryType typ) /// /// Shortcut call to XmlILTypeHelper.GetStorageType, using an expression's prime type. /// - private Type GetItemStorageType(QilNode nd) + private static Type GetItemStorageType(QilNode nd) { return XmlILTypeHelper.GetStorageType(nd.XmlType!.Prime); } @@ -4980,7 +4980,7 @@ private Type GetItemStorageType(QilNode nd) /// /// Shortcut call to XmlILTypeHelper.GetStorageType, using the prime type. /// - private Type GetItemStorageType(XmlQueryType typ) + private static Type GetItemStorageType(XmlQueryType typ) { return XmlILTypeHelper.GetStorageType(typ.Prime); } 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 4c6fe3fa700e8..ccfac9993d9ff 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 @@ -13,19 +13,10 @@ namespace System.Xml.Xsl.Qil /// internal sealed class QilFactory { - private readonly QilTypeChecker _typeCheck; - public QilFactory() { - _typeCheck = new QilTypeChecker(); - } - - public QilTypeChecker TypeChecker - { - get { return _typeCheck; } } - //----------------------------------------------- // Convenience methods //----------------------------------------------- @@ -33,7 +24,7 @@ public QilTypeChecker TypeChecker public QilExpression QilExpression(QilNode root, QilFactory factory) { QilExpression n = new QilExpression(QilNodeType.QilExpression, root, factory); - n.XmlType = _typeCheck.CheckQilExpression(n); + n.XmlType = QilTypeChecker.CheckQilExpression(n); TraceNode(n); return n; } @@ -107,7 +98,7 @@ public QilFunction Function(QilNode arguments, QilNode sideEffects, XmlQueryType public QilList FunctionList() { QilList n = new QilList(QilNodeType.FunctionList); - n.XmlType = _typeCheck.CheckFunctionList(n); + n.XmlType = QilTypeChecker.CheckFunctionList(n); TraceNode(n); return n; } @@ -115,7 +106,7 @@ public QilList FunctionList() public QilList GlobalVariableList() { QilList n = new QilList(QilNodeType.GlobalVariableList); - n.XmlType = _typeCheck.CheckGlobalVariableList(n); + n.XmlType = QilTypeChecker.CheckGlobalVariableList(n); TraceNode(n); return n; } @@ -123,7 +114,7 @@ public QilList GlobalVariableList() public QilList GlobalParameterList() { QilList n = new QilList(QilNodeType.GlobalParameterList); - n.XmlType = _typeCheck.CheckGlobalParameterList(n); + n.XmlType = QilTypeChecker.CheckGlobalParameterList(n); TraceNode(n); return n; } @@ -131,7 +122,7 @@ public QilList GlobalParameterList() public QilList ActualParameterList() { QilList n = new QilList(QilNodeType.ActualParameterList); - n.XmlType = _typeCheck.CheckActualParameterList(n); + n.XmlType = QilTypeChecker.CheckActualParameterList(n); TraceNode(n); return n; } @@ -139,7 +130,7 @@ public QilList ActualParameterList() public QilList FormalParameterList() { QilList n = new QilList(QilNodeType.FormalParameterList); - n.XmlType = _typeCheck.CheckFormalParameterList(n); + n.XmlType = QilTypeChecker.CheckFormalParameterList(n); TraceNode(n); return n; } @@ -147,7 +138,7 @@ public QilList FormalParameterList() public QilList SortKeyList() { QilList n = new QilList(QilNodeType.SortKeyList); - n.XmlType = _typeCheck.CheckSortKeyList(n); + n.XmlType = QilTypeChecker.CheckSortKeyList(n); TraceNode(n); return n; } @@ -155,7 +146,7 @@ public QilList SortKeyList() public QilList BranchList() { QilList n = new QilList(QilNodeType.BranchList); - n.XmlType = _typeCheck.CheckBranchList(n); + n.XmlType = QilTypeChecker.CheckBranchList(n); TraceNode(n); return n; } @@ -163,7 +154,7 @@ public QilList BranchList() public QilUnary OptimizeBarrier(QilNode child) { QilUnary n = new QilUnary(QilNodeType.OptimizeBarrier, child); - n.XmlType = _typeCheck.CheckOptimizeBarrier(n); + n.XmlType = QilTypeChecker.CheckOptimizeBarrier(n); TraceNode(n); return n; } @@ -171,7 +162,7 @@ public QilUnary OptimizeBarrier(QilNode child) public QilNode Unknown(XmlQueryType xmlType) { QilNode n = new QilNode(QilNodeType.Unknown, xmlType); - n.XmlType = _typeCheck.CheckUnknown(n); + n.XmlType = QilTypeChecker.CheckUnknown(n); TraceNode(n); return n; } @@ -185,7 +176,7 @@ public QilNode Unknown(XmlQueryType xmlType) public QilDataSource DataSource(QilNode name, QilNode baseUri) { QilDataSource n = new QilDataSource(QilNodeType.DataSource, name, baseUri); - n.XmlType = _typeCheck.CheckDataSource(n); + n.XmlType = QilTypeChecker.CheckDataSource(n); TraceNode(n); return n; } @@ -193,7 +184,7 @@ public QilDataSource DataSource(QilNode name, QilNode baseUri) public QilUnary Nop(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Nop, child); - n.XmlType = _typeCheck.CheckNop(n); + n.XmlType = QilTypeChecker.CheckNop(n); TraceNode(n); return n; } @@ -201,7 +192,7 @@ public QilUnary Nop(QilNode child) public QilUnary Error(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Error, child); - n.XmlType = _typeCheck.CheckError(n); + n.XmlType = QilTypeChecker.CheckError(n); TraceNode(n); return n; } @@ -209,7 +200,7 @@ public QilUnary Error(QilNode child) public QilUnary Warning(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Warning, child); - n.XmlType = _typeCheck.CheckWarning(n); + n.XmlType = QilTypeChecker.CheckWarning(n); TraceNode(n); return n; } @@ -223,7 +214,7 @@ public QilUnary Warning(QilNode child) public QilIterator For(QilNode binding) { QilIterator n = new QilIterator(QilNodeType.For, binding); - n.XmlType = _typeCheck.CheckFor(n); + n.XmlType = QilTypeChecker.CheckFor(n); TraceNode(n); return n; } @@ -231,7 +222,7 @@ public QilIterator For(QilNode binding) public QilIterator Let(QilNode binding) { QilIterator n = new QilIterator(QilNodeType.Let, binding); - n.XmlType = _typeCheck.CheckLet(n); + n.XmlType = QilTypeChecker.CheckLet(n); TraceNode(n); return n; } @@ -239,7 +230,7 @@ public QilIterator Let(QilNode binding) public QilParameter Parameter(QilNode? defaultValue, QilNode? name, XmlQueryType xmlType) { QilParameter n = new QilParameter(QilNodeType.Parameter, defaultValue, name, xmlType); - n.XmlType = _typeCheck.CheckParameter(n); + n.XmlType = QilTypeChecker.CheckParameter(n); TraceNode(n); return n; } @@ -247,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 = _typeCheck.CheckPositionOf(n); + n.XmlType = QilTypeChecker.CheckPositionOf(n); TraceNode(n); return n; } @@ -261,7 +252,7 @@ public QilUnary PositionOf(QilNode child) public QilNode True() { QilNode n = new QilNode(QilNodeType.True); - n.XmlType = _typeCheck.CheckTrue(n); + n.XmlType = QilTypeChecker.CheckTrue(n); TraceNode(n); return n; } @@ -269,7 +260,7 @@ public QilNode True() public QilNode False() { QilNode n = new QilNode(QilNodeType.False); - n.XmlType = _typeCheck.CheckFalse(n); + n.XmlType = QilTypeChecker.CheckFalse(n); TraceNode(n); return n; } @@ -277,7 +268,7 @@ public QilNode False() public QilLiteral LiteralString(string? value) { QilLiteral n = new QilLiteral(QilNodeType.LiteralString, value); - n.XmlType = _typeCheck.CheckLiteralString(n); + n.XmlType = QilTypeChecker.CheckLiteralString(n); TraceNode(n); return n; } @@ -285,7 +276,7 @@ public QilLiteral LiteralString(string? value) public QilLiteral LiteralInt32(int value) { QilLiteral n = new QilLiteral(QilNodeType.LiteralInt32, value); - n.XmlType = _typeCheck.CheckLiteralInt32(n); + n.XmlType = QilTypeChecker.CheckLiteralInt32(n); TraceNode(n); return n; } @@ -293,7 +284,7 @@ public QilLiteral LiteralInt32(int value) public QilLiteral LiteralInt64(long value) { QilLiteral n = new QilLiteral(QilNodeType.LiteralInt64, value); - n.XmlType = _typeCheck.CheckLiteralInt64(n); + n.XmlType = QilTypeChecker.CheckLiteralInt64(n); TraceNode(n); return n; } @@ -301,7 +292,7 @@ public QilLiteral LiteralInt64(long value) public QilLiteral LiteralDouble(double value) { QilLiteral n = new QilLiteral(QilNodeType.LiteralDouble, value); - n.XmlType = _typeCheck.CheckLiteralDouble(n); + n.XmlType = QilTypeChecker.CheckLiteralDouble(n); TraceNode(n); return n; } @@ -309,7 +300,7 @@ public QilLiteral LiteralDouble(double value) public QilLiteral LiteralDecimal(decimal value) { QilLiteral n = new QilLiteral(QilNodeType.LiteralDecimal, value); - n.XmlType = _typeCheck.CheckLiteralDecimal(n); + n.XmlType = QilTypeChecker.CheckLiteralDecimal(n); TraceNode(n); return n; } @@ -317,7 +308,7 @@ public QilLiteral LiteralDecimal(decimal value) public QilName LiteralQName(string localName, string namespaceUri, string prefix) { QilName n = new QilName(QilNodeType.LiteralQName, localName, namespaceUri, prefix); - n.XmlType = _typeCheck.CheckLiteralQName(n); + n.XmlType = QilTypeChecker.CheckLiteralQName(n); TraceNode(n); return n; } @@ -325,7 +316,7 @@ public QilName LiteralQName(string localName, string namespaceUri, string prefix public QilLiteral LiteralType(XmlQueryType value) { QilLiteral n = new QilLiteral(QilNodeType.LiteralType, value); - n.XmlType = _typeCheck.CheckLiteralType(n); + n.XmlType = QilTypeChecker.CheckLiteralType(n); TraceNode(n); return n; } @@ -333,7 +324,7 @@ public QilLiteral LiteralType(XmlQueryType value) public QilLiteral LiteralObject(object value) { QilLiteral n = new QilLiteral(QilNodeType.LiteralObject, value); - n.XmlType = _typeCheck.CheckLiteralObject(n); + n.XmlType = QilTypeChecker.CheckLiteralObject(n); TraceNode(n); return n; } @@ -347,7 +338,7 @@ public QilLiteral LiteralObject(object value) public QilBinary And(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.And, left, right); - n.XmlType = _typeCheck.CheckAnd(n); + n.XmlType = QilTypeChecker.CheckAnd(n); TraceNode(n); return n; } @@ -355,7 +346,7 @@ public QilBinary And(QilNode left, QilNode right) public QilBinary Or(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Or, left, right); - n.XmlType = _typeCheck.CheckOr(n); + n.XmlType = QilTypeChecker.CheckOr(n); TraceNode(n); return n; } @@ -363,7 +354,7 @@ public QilBinary Or(QilNode left, QilNode right) public QilUnary Not(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Not, child); - n.XmlType = _typeCheck.CheckNot(n); + n.XmlType = QilTypeChecker.CheckNot(n); TraceNode(n); return n; } @@ -377,7 +368,7 @@ public QilUnary Not(QilNode child) public QilTernary Conditional(QilNode left, QilNode center, QilNode right) { QilTernary n = new QilTernary(QilNodeType.Conditional, left, center, right); - n.XmlType = _typeCheck.CheckConditional(n); + n.XmlType = QilTypeChecker.CheckConditional(n); TraceNode(n); return n; } @@ -385,7 +376,7 @@ public QilTernary Conditional(QilNode left, QilNode center, QilNode right) public QilChoice Choice(QilNode expression, QilNode branches) { QilChoice n = new QilChoice(QilNodeType.Choice, expression, branches); - n.XmlType = _typeCheck.CheckChoice(n); + n.XmlType = QilTypeChecker.CheckChoice(n); TraceNode(n); return n; } @@ -399,7 +390,7 @@ public QilChoice Choice(QilNode expression, QilNode branches) public QilUnary Length(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Length, child); - n.XmlType = _typeCheck.CheckLength(n); + n.XmlType = QilTypeChecker.CheckLength(n); TraceNode(n); return n; } @@ -407,7 +398,7 @@ public QilUnary Length(QilNode child) public QilList Sequence() { QilList n = new QilList(QilNodeType.Sequence); - n.XmlType = _typeCheck.CheckSequence(n); + n.XmlType = QilTypeChecker.CheckSequence(n); TraceNode(n); return n; } @@ -415,7 +406,7 @@ public QilList Sequence() public QilBinary Union(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Union, left, right); - n.XmlType = _typeCheck.CheckUnion(n); + n.XmlType = QilTypeChecker.CheckUnion(n); TraceNode(n); return n; } @@ -423,7 +414,7 @@ public QilBinary Union(QilNode left, QilNode right) public QilBinary Intersection(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Intersection, left, right); - n.XmlType = _typeCheck.CheckIntersection(n); + n.XmlType = QilTypeChecker.CheckIntersection(n); TraceNode(n); return n; } @@ -431,7 +422,7 @@ public QilBinary Intersection(QilNode left, QilNode right) public QilBinary Difference(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Difference, left, right); - n.XmlType = _typeCheck.CheckDifference(n); + n.XmlType = QilTypeChecker.CheckDifference(n); TraceNode(n); return n; } @@ -439,7 +430,7 @@ public QilBinary Difference(QilNode left, QilNode right) public QilUnary Sum(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Sum, child); - n.XmlType = _typeCheck.CheckSum(n); + n.XmlType = QilTypeChecker.CheckSum(n); TraceNode(n); return n; } @@ -453,7 +444,7 @@ public QilUnary Sum(QilNode child) public QilUnary Negate(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Negate, child); - n.XmlType = _typeCheck.CheckNegate(n); + n.XmlType = QilTypeChecker.CheckNegate(n); TraceNode(n); return n; } @@ -461,7 +452,7 @@ public QilUnary Negate(QilNode child) public QilBinary Add(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Add, left, right); - n.XmlType = _typeCheck.CheckAdd(n); + n.XmlType = QilTypeChecker.CheckAdd(n); TraceNode(n); return n; } @@ -469,7 +460,7 @@ public QilBinary Add(QilNode left, QilNode right) public QilBinary Subtract(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Subtract, left, right); - n.XmlType = _typeCheck.CheckSubtract(n); + n.XmlType = QilTypeChecker.CheckSubtract(n); TraceNode(n); return n; } @@ -477,7 +468,7 @@ public QilBinary Subtract(QilNode left, QilNode right) public QilBinary Multiply(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Multiply, left, right); - n.XmlType = _typeCheck.CheckMultiply(n); + n.XmlType = QilTypeChecker.CheckMultiply(n); TraceNode(n); return n; } @@ -485,7 +476,7 @@ public QilBinary Multiply(QilNode left, QilNode right) public QilBinary Divide(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Divide, left, right); - n.XmlType = _typeCheck.CheckDivide(n); + n.XmlType = QilTypeChecker.CheckDivide(n); TraceNode(n); return n; } @@ -493,7 +484,7 @@ public QilBinary Divide(QilNode left, QilNode right) public QilBinary Modulo(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Modulo, left, right); - n.XmlType = _typeCheck.CheckModulo(n); + n.XmlType = QilTypeChecker.CheckModulo(n); TraceNode(n); return n; } @@ -507,7 +498,7 @@ public QilBinary Modulo(QilNode left, QilNode right) public QilUnary StrLength(QilNode child) { QilUnary n = new QilUnary(QilNodeType.StrLength, child); - n.XmlType = _typeCheck.CheckStrLength(n); + n.XmlType = QilTypeChecker.CheckStrLength(n); TraceNode(n); return n; } @@ -515,7 +506,7 @@ public QilUnary StrLength(QilNode child) public QilStrConcat StrConcat(QilNode delimiter, QilNode values) { QilStrConcat n = new QilStrConcat(QilNodeType.StrConcat, delimiter, values); - n.XmlType = _typeCheck.CheckStrConcat(n); + n.XmlType = QilTypeChecker.CheckStrConcat(n); TraceNode(n); return n; } @@ -523,7 +514,7 @@ public QilStrConcat StrConcat(QilNode delimiter, QilNode values) public QilBinary StrParseQName(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.StrParseQName, left, right); - n.XmlType = _typeCheck.CheckStrParseQName(n); + n.XmlType = QilTypeChecker.CheckStrParseQName(n); TraceNode(n); return n; } @@ -537,7 +528,7 @@ public QilBinary StrParseQName(QilNode left, QilNode right) public QilBinary Ne(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Ne, left, right); - n.XmlType = _typeCheck.CheckNe(n); + n.XmlType = QilTypeChecker.CheckNe(n); TraceNode(n); return n; } @@ -545,7 +536,7 @@ public QilBinary Ne(QilNode left, QilNode right) public QilBinary Eq(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Eq, left, right); - n.XmlType = _typeCheck.CheckEq(n); + n.XmlType = QilTypeChecker.CheckEq(n); TraceNode(n); return n; } @@ -553,7 +544,7 @@ public QilBinary Eq(QilNode left, QilNode right) public QilBinary Gt(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Gt, left, right); - n.XmlType = _typeCheck.CheckGt(n); + n.XmlType = QilTypeChecker.CheckGt(n); TraceNode(n); return n; } @@ -561,7 +552,7 @@ public QilBinary Gt(QilNode left, QilNode right) public QilBinary Ge(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Ge, left, right); - n.XmlType = _typeCheck.CheckGe(n); + n.XmlType = QilTypeChecker.CheckGe(n); TraceNode(n); return n; } @@ -569,7 +560,7 @@ public QilBinary Ge(QilNode left, QilNode right) public QilBinary Lt(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Lt, left, right); - n.XmlType = _typeCheck.CheckLt(n); + n.XmlType = QilTypeChecker.CheckLt(n); TraceNode(n); return n; } @@ -577,7 +568,7 @@ public QilBinary Lt(QilNode left, QilNode right) public QilBinary Le(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Le, left, right); - n.XmlType = _typeCheck.CheckLe(n); + n.XmlType = QilTypeChecker.CheckLe(n); TraceNode(n); return n; } @@ -591,7 +582,7 @@ public QilBinary Le(QilNode left, QilNode right) public QilBinary Is(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Is, left, right); - n.XmlType = _typeCheck.CheckIs(n); + n.XmlType = QilTypeChecker.CheckIs(n); TraceNode(n); return n; } @@ -599,7 +590,7 @@ public QilBinary Is(QilNode left, QilNode right) public QilBinary Before(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Before, left, right); - n.XmlType = _typeCheck.CheckBefore(n); + n.XmlType = QilTypeChecker.CheckBefore(n); TraceNode(n); return n; } @@ -613,7 +604,7 @@ public QilBinary Before(QilNode left, QilNode right) public QilLoop Loop(QilNode variable, QilNode body) { QilLoop n = new QilLoop(QilNodeType.Loop, variable, body); - n.XmlType = _typeCheck.CheckLoop(n); + n.XmlType = QilTypeChecker.CheckLoop(n); TraceNode(n); return n; } @@ -621,7 +612,7 @@ public QilLoop Loop(QilNode variable, QilNode body) public QilLoop Filter(QilNode variable, QilNode body) { QilLoop n = new QilLoop(QilNodeType.Filter, variable, body); - n.XmlType = _typeCheck.CheckFilter(n); + n.XmlType = QilTypeChecker.CheckFilter(n); TraceNode(n); return n; } @@ -635,7 +626,7 @@ public QilLoop Filter(QilNode variable, QilNode body) public QilLoop Sort(QilNode variable, QilNode body) { QilLoop n = new QilLoop(QilNodeType.Sort, variable, body); - n.XmlType = _typeCheck.CheckSort(n); + n.XmlType = QilTypeChecker.CheckSort(n); TraceNode(n); return n; } @@ -643,7 +634,7 @@ public QilLoop Sort(QilNode variable, QilNode body) public QilSortKey SortKey(QilNode key, QilNode collation) { QilSortKey n = new QilSortKey(QilNodeType.SortKey, key, collation); - n.XmlType = _typeCheck.CheckSortKey(n); + n.XmlType = QilTypeChecker.CheckSortKey(n); TraceNode(n); return n; } @@ -651,7 +642,7 @@ public QilSortKey SortKey(QilNode key, QilNode collation) public QilUnary DocOrderDistinct(QilNode child) { QilUnary n = new QilUnary(QilNodeType.DocOrderDistinct, child); - n.XmlType = _typeCheck.CheckDocOrderDistinct(n); + n.XmlType = QilTypeChecker.CheckDocOrderDistinct(n); TraceNode(n); return n; } @@ -665,7 +656,7 @@ public QilUnary DocOrderDistinct(QilNode child) public QilFunction Function(QilNode arguments, QilNode definition, QilNode sideEffects, XmlQueryType xmlType) { QilFunction n = new QilFunction(QilNodeType.Function, arguments, definition, sideEffects, xmlType); - n.XmlType = _typeCheck.CheckFunction(n); + n.XmlType = QilTypeChecker.CheckFunction(n); TraceNode(n); return n; } @@ -673,7 +664,7 @@ public QilFunction Function(QilNode arguments, QilNode definition, QilNode sideE public QilInvoke Invoke(QilNode function, QilNode arguments) { QilInvoke n = new QilInvoke(QilNodeType.Invoke, function, arguments); - n.XmlType = _typeCheck.CheckInvoke(n); + n.XmlType = QilTypeChecker.CheckInvoke(n); TraceNode(n); return n; } @@ -687,7 +678,7 @@ public QilInvoke Invoke(QilNode function, QilNode arguments) public QilUnary Content(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Content, child); - n.XmlType = _typeCheck.CheckContent(n); + n.XmlType = QilTypeChecker.CheckContent(n); TraceNode(n); return n; } @@ -695,7 +686,7 @@ public QilUnary Content(QilNode child) public QilBinary Attribute(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Attribute, left, right); - n.XmlType = _typeCheck.CheckAttribute(n); + n.XmlType = QilTypeChecker.CheckAttribute(n); TraceNode(n); return n; } @@ -703,7 +694,7 @@ public QilBinary Attribute(QilNode left, QilNode right) public QilUnary Parent(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Parent, child); - n.XmlType = _typeCheck.CheckParent(n); + n.XmlType = QilTypeChecker.CheckParent(n); TraceNode(n); return n; } @@ -711,7 +702,7 @@ public QilUnary Parent(QilNode child) public QilUnary Root(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Root, child); - n.XmlType = _typeCheck.CheckRoot(n); + n.XmlType = QilTypeChecker.CheckRoot(n); TraceNode(n); return n; } @@ -719,7 +710,7 @@ public QilUnary Root(QilNode child) public QilNode XmlContext() { QilNode n = new QilNode(QilNodeType.XmlContext); - n.XmlType = _typeCheck.CheckXmlContext(n); + n.XmlType = QilTypeChecker.CheckXmlContext(n); TraceNode(n); return n; } @@ -727,7 +718,7 @@ public QilNode XmlContext() public QilUnary Descendant(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Descendant, child); - n.XmlType = _typeCheck.CheckDescendant(n); + n.XmlType = QilTypeChecker.CheckDescendant(n); TraceNode(n); return n; } @@ -735,7 +726,7 @@ public QilUnary Descendant(QilNode child) public QilUnary DescendantOrSelf(QilNode child) { QilUnary n = new QilUnary(QilNodeType.DescendantOrSelf, child); - n.XmlType = _typeCheck.CheckDescendantOrSelf(n); + n.XmlType = QilTypeChecker.CheckDescendantOrSelf(n); TraceNode(n); return n; } @@ -743,7 +734,7 @@ public QilUnary DescendantOrSelf(QilNode child) public QilUnary Ancestor(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Ancestor, child); - n.XmlType = _typeCheck.CheckAncestor(n); + n.XmlType = QilTypeChecker.CheckAncestor(n); TraceNode(n); return n; } @@ -751,7 +742,7 @@ public QilUnary Ancestor(QilNode child) public QilUnary AncestorOrSelf(QilNode child) { QilUnary n = new QilUnary(QilNodeType.AncestorOrSelf, child); - n.XmlType = _typeCheck.CheckAncestorOrSelf(n); + n.XmlType = QilTypeChecker.CheckAncestorOrSelf(n); TraceNode(n); return n; } @@ -759,7 +750,7 @@ public QilUnary AncestorOrSelf(QilNode child) public QilUnary Preceding(QilNode child) { QilUnary n = new QilUnary(QilNodeType.Preceding, child); - n.XmlType = _typeCheck.CheckPreceding(n); + n.XmlType = QilTypeChecker.CheckPreceding(n); TraceNode(n); return n; } @@ -767,7 +758,7 @@ public QilUnary Preceding(QilNode child) public QilUnary FollowingSibling(QilNode child) { QilUnary n = new QilUnary(QilNodeType.FollowingSibling, child); - n.XmlType = _typeCheck.CheckFollowingSibling(n); + n.XmlType = QilTypeChecker.CheckFollowingSibling(n); TraceNode(n); return n; } @@ -775,7 +766,7 @@ public QilUnary FollowingSibling(QilNode child) public QilUnary PrecedingSibling(QilNode child) { QilUnary n = new QilUnary(QilNodeType.PrecedingSibling, child); - n.XmlType = _typeCheck.CheckPrecedingSibling(n); + n.XmlType = QilTypeChecker.CheckPrecedingSibling(n); TraceNode(n); return n; } @@ -783,7 +774,7 @@ public QilUnary PrecedingSibling(QilNode child) public QilBinary NodeRange(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.NodeRange, left, right); - n.XmlType = _typeCheck.CheckNodeRange(n); + n.XmlType = QilTypeChecker.CheckNodeRange(n); TraceNode(n); return n; } @@ -791,7 +782,7 @@ public QilBinary NodeRange(QilNode left, QilNode right) public QilBinary Deref(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.Deref, left, right); - n.XmlType = _typeCheck.CheckDeref(n); + n.XmlType = QilTypeChecker.CheckDeref(n); TraceNode(n); return n; } @@ -805,7 +796,7 @@ public QilBinary Deref(QilNode left, QilNode right) public QilBinary ElementCtor(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.ElementCtor, left, right); - n.XmlType = _typeCheck.CheckElementCtor(n); + n.XmlType = QilTypeChecker.CheckElementCtor(n); TraceNode(n); return n; } @@ -813,7 +804,7 @@ public QilBinary ElementCtor(QilNode left, QilNode right) public QilBinary AttributeCtor(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.AttributeCtor, left, right); - n.XmlType = _typeCheck.CheckAttributeCtor(n); + n.XmlType = QilTypeChecker.CheckAttributeCtor(n); TraceNode(n); return n; } @@ -821,7 +812,7 @@ public QilBinary AttributeCtor(QilNode left, QilNode right) public QilUnary CommentCtor(QilNode child) { QilUnary n = new QilUnary(QilNodeType.CommentCtor, child); - n.XmlType = _typeCheck.CheckCommentCtor(n); + n.XmlType = QilTypeChecker.CheckCommentCtor(n); TraceNode(n); return n; } @@ -829,7 +820,7 @@ public QilUnary CommentCtor(QilNode child) public QilBinary PICtor(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.PICtor, left, right); - n.XmlType = _typeCheck.CheckPICtor(n); + n.XmlType = QilTypeChecker.CheckPICtor(n); TraceNode(n); return n; } @@ -837,7 +828,7 @@ public QilBinary PICtor(QilNode left, QilNode right) public QilUnary TextCtor(QilNode child) { QilUnary n = new QilUnary(QilNodeType.TextCtor, child); - n.XmlType = _typeCheck.CheckTextCtor(n); + n.XmlType = QilTypeChecker.CheckTextCtor(n); TraceNode(n); return n; } @@ -845,7 +836,7 @@ public QilUnary TextCtor(QilNode child) public QilUnary RawTextCtor(QilNode child) { QilUnary n = new QilUnary(QilNodeType.RawTextCtor, child); - n.XmlType = _typeCheck.CheckRawTextCtor(n); + n.XmlType = QilTypeChecker.CheckRawTextCtor(n); TraceNode(n); return n; } @@ -853,7 +844,7 @@ public QilUnary RawTextCtor(QilNode child) public QilUnary DocumentCtor(QilNode child) { QilUnary n = new QilUnary(QilNodeType.DocumentCtor, child); - n.XmlType = _typeCheck.CheckDocumentCtor(n); + n.XmlType = QilTypeChecker.CheckDocumentCtor(n); TraceNode(n); return n; } @@ -861,7 +852,7 @@ public QilUnary DocumentCtor(QilNode child) public QilBinary NamespaceDecl(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.NamespaceDecl, left, right); - n.XmlType = _typeCheck.CheckNamespaceDecl(n); + n.XmlType = QilTypeChecker.CheckNamespaceDecl(n); TraceNode(n); return n; } @@ -869,7 +860,7 @@ public QilBinary NamespaceDecl(QilNode left, QilNode right) public QilBinary RtfCtor(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.RtfCtor, left, right); - n.XmlType = _typeCheck.CheckRtfCtor(n); + n.XmlType = QilTypeChecker.CheckRtfCtor(n); TraceNode(n); return n; } @@ -883,7 +874,7 @@ public QilBinary RtfCtor(QilNode left, QilNode right) public QilUnary NameOf(QilNode child) { QilUnary n = new QilUnary(QilNodeType.NameOf, child); - n.XmlType = _typeCheck.CheckNameOf(n); + n.XmlType = QilTypeChecker.CheckNameOf(n); TraceNode(n); return n; } @@ -891,7 +882,7 @@ public QilUnary NameOf(QilNode child) public QilUnary LocalNameOf(QilNode child) { QilUnary n = new QilUnary(QilNodeType.LocalNameOf, child); - n.XmlType = _typeCheck.CheckLocalNameOf(n); + n.XmlType = QilTypeChecker.CheckLocalNameOf(n); TraceNode(n); return n; } @@ -899,7 +890,7 @@ public QilUnary LocalNameOf(QilNode child) public QilUnary NamespaceUriOf(QilNode child) { QilUnary n = new QilUnary(QilNodeType.NamespaceUriOf, child); - n.XmlType = _typeCheck.CheckNamespaceUriOf(n); + n.XmlType = QilTypeChecker.CheckNamespaceUriOf(n); TraceNode(n); return n; } @@ -907,7 +898,7 @@ public QilUnary NamespaceUriOf(QilNode child) public QilUnary PrefixOf(QilNode child) { QilUnary n = new QilUnary(QilNodeType.PrefixOf, child); - n.XmlType = _typeCheck.CheckPrefixOf(n); + n.XmlType = QilTypeChecker.CheckPrefixOf(n); TraceNode(n); return n; } @@ -921,7 +912,7 @@ public QilUnary PrefixOf(QilNode child) public QilTargetType TypeAssert(QilNode source, QilNode targetType) { QilTargetType n = new QilTargetType(QilNodeType.TypeAssert, source, targetType); - n.XmlType = _typeCheck.CheckTypeAssert(n); + n.XmlType = QilTypeChecker.CheckTypeAssert(n); TraceNode(n); return n; } @@ -929,7 +920,7 @@ public QilTargetType TypeAssert(QilNode source, QilNode targetType) public QilTargetType IsType(QilNode source, QilNode targetType) { QilTargetType n = new QilTargetType(QilNodeType.IsType, source, targetType); - n.XmlType = _typeCheck.CheckIsType(n); + n.XmlType = QilTypeChecker.CheckIsType(n); TraceNode(n); return n; } @@ -937,7 +928,7 @@ public QilTargetType IsType(QilNode source, QilNode targetType) public QilUnary IsEmpty(QilNode child) { QilUnary n = new QilUnary(QilNodeType.IsEmpty, child); - n.XmlType = _typeCheck.CheckIsEmpty(n); + n.XmlType = QilTypeChecker.CheckIsEmpty(n); TraceNode(n); return n; } @@ -951,7 +942,7 @@ public QilUnary IsEmpty(QilNode child) public QilUnary XPathNodeValue(QilNode child) { QilUnary n = new QilUnary(QilNodeType.XPathNodeValue, child); - n.XmlType = _typeCheck.CheckXPathNodeValue(n); + n.XmlType = QilTypeChecker.CheckXPathNodeValue(n); TraceNode(n); return n; } @@ -959,7 +950,7 @@ public QilUnary XPathNodeValue(QilNode child) public QilUnary XPathFollowing(QilNode child) { QilUnary n = new QilUnary(QilNodeType.XPathFollowing, child); - n.XmlType = _typeCheck.CheckXPathFollowing(n); + n.XmlType = QilTypeChecker.CheckXPathFollowing(n); TraceNode(n); return n; } @@ -967,7 +958,7 @@ public QilUnary XPathFollowing(QilNode child) public QilUnary XPathPreceding(QilNode child) { QilUnary n = new QilUnary(QilNodeType.XPathPreceding, child); - n.XmlType = _typeCheck.CheckXPathPreceding(n); + n.XmlType = QilTypeChecker.CheckXPathPreceding(n); TraceNode(n); return n; } @@ -975,7 +966,7 @@ public QilUnary XPathPreceding(QilNode child) public QilUnary XPathNamespace(QilNode child) { QilUnary n = new QilUnary(QilNodeType.XPathNamespace, child); - n.XmlType = _typeCheck.CheckXPathNamespace(n); + n.XmlType = QilTypeChecker.CheckXPathNamespace(n); TraceNode(n); return n; } @@ -989,7 +980,7 @@ public QilUnary XPathNamespace(QilNode child) public QilUnary XsltGenerateId(QilNode child) { QilUnary n = new QilUnary(QilNodeType.XsltGenerateId, child); - n.XmlType = _typeCheck.CheckXsltGenerateId(n); + n.XmlType = QilTypeChecker.CheckXsltGenerateId(n); TraceNode(n); return n; } @@ -997,7 +988,7 @@ public QilUnary XsltGenerateId(QilNode child) public QilInvokeLateBound XsltInvokeLateBound(QilNode name, QilNode arguments) { QilInvokeLateBound n = new QilInvokeLateBound(QilNodeType.XsltInvokeLateBound, name, arguments); - n.XmlType = _typeCheck.CheckXsltInvokeLateBound(n); + n.XmlType = QilTypeChecker.CheckXsltInvokeLateBound(n); TraceNode(n); return n; } @@ -1005,7 +996,7 @@ public QilInvokeLateBound XsltInvokeLateBound(QilNode name, QilNode arguments) public QilInvokeEarlyBound XsltInvokeEarlyBound(QilNode name, QilNode clrMethod, QilNode arguments, XmlQueryType xmlType) { QilInvokeEarlyBound n = new QilInvokeEarlyBound(QilNodeType.XsltInvokeEarlyBound, name, clrMethod, arguments, xmlType); - n.XmlType = _typeCheck.CheckXsltInvokeEarlyBound(n); + n.XmlType = QilTypeChecker.CheckXsltInvokeEarlyBound(n); TraceNode(n); return n; } @@ -1013,7 +1004,7 @@ public QilInvokeEarlyBound XsltInvokeEarlyBound(QilNode name, QilNode clrMethod, public QilBinary XsltCopy(QilNode left, QilNode right) { QilBinary n = new QilBinary(QilNodeType.XsltCopy, left, right); - n.XmlType = _typeCheck.CheckXsltCopy(n); + n.XmlType = QilTypeChecker.CheckXsltCopy(n); TraceNode(n); return n; } @@ -1021,7 +1012,7 @@ public QilBinary XsltCopy(QilNode left, QilNode right) public QilUnary XsltCopyOf(QilNode child) { QilUnary n = new QilUnary(QilNodeType.XsltCopyOf, child); - n.XmlType = _typeCheck.CheckXsltCopyOf(n); + n.XmlType = QilTypeChecker.CheckXsltCopyOf(n); TraceNode(n); return n; } @@ -1029,7 +1020,7 @@ public QilUnary XsltCopyOf(QilNode child) public QilTargetType XsltConvert(QilNode source, QilNode targetType) { QilTargetType n = new QilTargetType(QilNodeType.XsltConvert, source, targetType); - n.XmlType = _typeCheck.CheckXsltConvert(n); + n.XmlType = QilTypeChecker.CheckXsltConvert(n); TraceNode(n); return n; } @@ -1038,12 +1029,16 @@ public QilTargetType XsltConvert(QilNode source, QilNode targetType) #endregion #region Diagnostic Support [System.Diagnostics.Conditional("QIL_TRACE_NODE_CREATION")] + +#pragma warning disable CA1822 public void TraceNode(QilNode n) { #if QIL_TRACE_NODE_CREATION this.diag.AddNode(n); #endif } +#pragma warning restore CA1822 + #endregion } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilReplaceVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilReplaceVisitor.cs index 087a035283479..f6497bf7fe743 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilReplaceVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilReplaceVisitor.cs @@ -72,7 +72,7 @@ protected virtual void RecalculateType(QilNode node, XmlQueryType oldType) { XmlQueryType newType; - newType = f.TypeChecker.Check(node); + newType = QilTypeChecker.Check(node); // Note the use of AtMost to account for cases when folding of Error nodes in the graph cause // cardinality to be recalculated. 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 f23c823cd0914..518767be0f823 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 @@ -18,13 +18,9 @@ namespace System.Xml.Xsl.Qil /// 1. Infer XmlQueryType of Qil nodes (constant, from arguments, etc) /// 2. Validate the arguments of Qil nodes if DEBUG is defined /// - internal sealed class QilTypeChecker + internal static class QilTypeChecker { - public QilTypeChecker() - { - } - - public XmlQueryType Check(QilNode n) + public static XmlQueryType Check(QilNode n) { #region AUTOGENERATED return n.NodeType switch @@ -165,7 +161,7 @@ public XmlQueryType Check(QilNode n) //----------------------------------------------- // meta //----------------------------------------------- - public XmlQueryType CheckQilExpression(QilExpression node) + public static XmlQueryType CheckQilExpression(QilExpression node) { Check(node[0].NodeType == QilNodeType.False || node[0].NodeType == QilNodeType.True, node, "IsDebug must either be True or False"); CheckLiteralValue(node[1], typeof(XmlWriterSettings)); @@ -177,21 +173,21 @@ public XmlQueryType CheckQilExpression(QilExpression node) return XmlQueryTypeFactory.ItemS; } - public XmlQueryType CheckFunctionList(QilList node) + public static XmlQueryType CheckFunctionList(QilList node) { foreach (QilNode child in node) CheckClassAndNodeType(child, typeof(QilFunction), QilNodeType.Function); return node.XmlType; } - public XmlQueryType CheckGlobalVariableList(QilList node) + public static XmlQueryType CheckGlobalVariableList(QilList node) { foreach (QilNode child in node) CheckClassAndNodeType(child, typeof(QilIterator), QilNodeType.Let); return node.XmlType; } - public XmlQueryType CheckGlobalParameterList(QilList node) + public static XmlQueryType CheckGlobalParameterList(QilList node) { foreach (QilNode child in node) { @@ -201,36 +197,36 @@ public XmlQueryType CheckGlobalParameterList(QilList node) return node.XmlType; } - public XmlQueryType CheckActualParameterList(QilList node) + public static XmlQueryType CheckActualParameterList(QilList node) { return node.XmlType; } - public XmlQueryType CheckFormalParameterList(QilList node) + public static XmlQueryType CheckFormalParameterList(QilList node) { foreach (QilNode child in node) CheckClassAndNodeType(child, typeof(QilParameter), QilNodeType.Parameter); return node.XmlType; } - public XmlQueryType CheckSortKeyList(QilList node) + public static XmlQueryType CheckSortKeyList(QilList node) { foreach (QilNode child in node) CheckClassAndNodeType(child, typeof(QilSortKey), QilNodeType.SortKey); return node.XmlType; } - public XmlQueryType CheckBranchList(QilList node) + public static XmlQueryType CheckBranchList(QilList node) { return node.XmlType; } - public XmlQueryType CheckOptimizeBarrier(QilUnary node) + public static XmlQueryType CheckOptimizeBarrier(QilUnary node) { return node.Child.XmlType!; } - public XmlQueryType CheckUnknown(QilNode node) + public static XmlQueryType CheckUnknown(QilNode node) { return node.XmlType!; } @@ -241,25 +237,25 @@ public XmlQueryType CheckUnknown(QilNode node) //----------------------------------------------- // specials //----------------------------------------------- - public XmlQueryType CheckDataSource(QilDataSource node) + public static XmlQueryType CheckDataSource(QilDataSource node) { CheckXmlType(node.Name, XmlQueryTypeFactory.StringX); CheckXmlType(node.BaseUri, XmlQueryTypeFactory.StringX); return XmlQueryTypeFactory.NodeNotRtfQ; } - public XmlQueryType CheckNop(QilUnary node) + public static XmlQueryType CheckNop(QilUnary node) { return node.Child.XmlType!; } - public XmlQueryType CheckError(QilUnary node) + public static XmlQueryType CheckError(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.StringX); return XmlQueryTypeFactory.None; } - public XmlQueryType CheckWarning(QilUnary node) + public static XmlQueryType CheckWarning(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.StringX); return XmlQueryTypeFactory.Empty; @@ -271,23 +267,23 @@ public XmlQueryType CheckWarning(QilUnary node) //----------------------------------------------- // variables //----------------------------------------------- - public XmlQueryType CheckFor(QilIterator node) + public static XmlQueryType CheckFor(QilIterator node) { return node.Binding!.XmlType!.Prime; } - public XmlQueryType CheckLet(QilIterator node) + public static XmlQueryType CheckLet(QilIterator node) { return node.Binding!.XmlType!; } - public XmlQueryType CheckParameter(QilParameter node) + public static XmlQueryType CheckParameter(QilParameter node) { Check(node.Binding == null || node.Binding.XmlType!.IsSubtypeOf(node.XmlType!), node, "Parameter binding's xml type must be a subtype of the parameter's type"); return node.XmlType!; } - public XmlQueryType CheckPositionOf(QilUnary node) + public static XmlQueryType CheckPositionOf(QilUnary node) { return XmlQueryTypeFactory.IntX; } @@ -298,47 +294,47 @@ public XmlQueryType CheckPositionOf(QilUnary node) //----------------------------------------------- // literals //----------------------------------------------- - public XmlQueryType CheckTrue(QilNode node) + public static XmlQueryType CheckTrue(QilNode node) { return XmlQueryTypeFactory.BooleanX; } - public XmlQueryType CheckFalse(QilNode node) + public static XmlQueryType CheckFalse(QilNode node) { return XmlQueryTypeFactory.BooleanX; } - public XmlQueryType CheckLiteralString(QilLiteral node) + public static XmlQueryType CheckLiteralString(QilLiteral node) { CheckLiteralValue(node, typeof(string)); return XmlQueryTypeFactory.StringX; } - public XmlQueryType CheckLiteralInt32(QilLiteral node) + public static XmlQueryType CheckLiteralInt32(QilLiteral node) { CheckLiteralValue(node, typeof(int)); return XmlQueryTypeFactory.IntX; } - public XmlQueryType CheckLiteralInt64(QilLiteral node) + public static XmlQueryType CheckLiteralInt64(QilLiteral node) { CheckLiteralValue(node, typeof(long)); return XmlQueryTypeFactory.IntegerX; } - public XmlQueryType CheckLiteralDouble(QilLiteral node) + public static XmlQueryType CheckLiteralDouble(QilLiteral node) { CheckLiteralValue(node, typeof(double)); return XmlQueryTypeFactory.DoubleX; } - public XmlQueryType CheckLiteralDecimal(QilLiteral node) + public static XmlQueryType CheckLiteralDecimal(QilLiteral node) { CheckLiteralValue(node, typeof(decimal)); return XmlQueryTypeFactory.DecimalX; } - public XmlQueryType CheckLiteralQName(QilName node) + public static XmlQueryType CheckLiteralQName(QilName node) { CheckLiteralValue(node, typeof(QilName)); // BUGBUG: Xslt constructs invalid QNames, so don't check this @@ -346,13 +342,13 @@ public XmlQueryType CheckLiteralQName(QilName node) return XmlQueryTypeFactory.QNameX; } - public XmlQueryType CheckLiteralType(QilLiteral node) + public static XmlQueryType CheckLiteralType(QilLiteral node) { CheckLiteralValue(node, typeof(XmlQueryType)); return (XmlQueryType)node; } - public XmlQueryType CheckLiteralObject(QilLiteral node) + public static XmlQueryType CheckLiteralObject(QilLiteral node) { Check(node.Value != null, node, "Literal value is null"); return XmlQueryTypeFactory.ItemS; @@ -364,19 +360,19 @@ public XmlQueryType CheckLiteralObject(QilLiteral node) //----------------------------------------------- // boolean operators //----------------------------------------------- - public XmlQueryType CheckAnd(QilBinary node) + public static XmlQueryType CheckAnd(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.BooleanX); CheckXmlType(node.Right, XmlQueryTypeFactory.BooleanX); return XmlQueryTypeFactory.BooleanX; } - public XmlQueryType CheckOr(QilBinary node) + public static XmlQueryType CheckOr(QilBinary node) { return CheckAnd(node); } - public XmlQueryType CheckNot(QilUnary node) + public static XmlQueryType CheckNot(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.BooleanX); return XmlQueryTypeFactory.BooleanX; @@ -388,13 +384,13 @@ public XmlQueryType CheckNot(QilUnary node) //----------------------------------------------- // choice //----------------------------------------------- - public XmlQueryType CheckConditional(QilTernary node) + public static XmlQueryType CheckConditional(QilTernary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.BooleanX); return XmlQueryTypeFactory.Choice(node.Center.XmlType!, node.Right.XmlType!); } - public XmlQueryType CheckChoice(QilChoice node) + public static XmlQueryType CheckChoice(QilChoice node) { CheckXmlType(node.Expression, XmlQueryTypeFactory.IntX); CheckClassAndNodeType(node.Branches, typeof(QilList), QilNodeType.BranchList); @@ -408,53 +404,53 @@ public XmlQueryType CheckChoice(QilChoice node) //----------------------------------------------- // collection operators //----------------------------------------------- - public XmlQueryType CheckLength(QilUnary node) + public static XmlQueryType CheckLength(QilUnary node) { return XmlQueryTypeFactory.IntX; } - public XmlQueryType CheckSequence(QilList node) + public static XmlQueryType CheckSequence(QilList node) { return node.XmlType; } - public XmlQueryType CheckUnion(QilBinary node) + public static XmlQueryType CheckUnion(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtfS); CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS); return DistinctType(XmlQueryTypeFactory.Sequence(node.Left.XmlType!, node.Right.XmlType!)); } - public XmlQueryType CheckIntersection(QilBinary node) + public static XmlQueryType CheckIntersection(QilBinary node) { return CheckUnion(node); } - public XmlQueryType CheckDifference(QilBinary node) + public static XmlQueryType CheckDifference(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtfS); CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS); return XmlQueryTypeFactory.AtMost(node.Left.XmlType!, node.Left.XmlType!.Cardinality); } - public XmlQueryType CheckAverage(QilUnary node) + public static XmlQueryType CheckAverage(QilUnary node) { XmlQueryType xmlType = node.Child.XmlType!; CheckNumericXS(node.Child); return XmlQueryTypeFactory.PrimeProduct(xmlType, xmlType.MaybeEmpty ? XmlQueryCardinality.ZeroOrOne : XmlQueryCardinality.One); } - public XmlQueryType CheckSum(QilUnary node) + public static XmlQueryType CheckSum(QilUnary node) { return CheckAverage(node); } - public XmlQueryType CheckMinimum(QilUnary node) + public static XmlQueryType CheckMinimum(QilUnary node) { return CheckAverage(node); } - public XmlQueryType CheckMaximum(QilUnary node) + public static XmlQueryType CheckMaximum(QilUnary node) { return CheckAverage(node); } @@ -465,13 +461,13 @@ public XmlQueryType CheckMaximum(QilUnary node) //----------------------------------------------- // arithmetic operators //----------------------------------------------- - public XmlQueryType CheckNegate(QilUnary node) + public static XmlQueryType CheckNegate(QilUnary node) { CheckNumericX(node.Child); return node.Child.XmlType!; } - public XmlQueryType CheckAdd(QilBinary node) + public static XmlQueryType CheckAdd(QilBinary node) { CheckNumericX(node.Left); CheckNumericX(node.Right); @@ -479,22 +475,22 @@ public XmlQueryType CheckAdd(QilBinary node) return node.Left.XmlType!.TypeCode == XmlTypeCode.None ? node.Right.XmlType! : node.Left.XmlType!; } - public XmlQueryType CheckSubtract(QilBinary node) + public static XmlQueryType CheckSubtract(QilBinary node) { return CheckAdd(node); } - public XmlQueryType CheckMultiply(QilBinary node) + public static XmlQueryType CheckMultiply(QilBinary node) { return CheckAdd(node); } - public XmlQueryType CheckDivide(QilBinary node) + public static XmlQueryType CheckDivide(QilBinary node) { return CheckAdd(node); } - public XmlQueryType CheckModulo(QilBinary node) + public static XmlQueryType CheckModulo(QilBinary node) { return CheckAdd(node); } @@ -505,20 +501,20 @@ public XmlQueryType CheckModulo(QilBinary node) //----------------------------------------------- // string operators //----------------------------------------------- - public XmlQueryType CheckStrLength(QilUnary node) + public static XmlQueryType CheckStrLength(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.StringX); return XmlQueryTypeFactory.IntX; } - public XmlQueryType CheckStrConcat(QilStrConcat node) + public static XmlQueryType CheckStrConcat(QilStrConcat node) { CheckXmlType(node.Delimiter, XmlQueryTypeFactory.StringX); CheckXmlType(node.Values, XmlQueryTypeFactory.StringXS); return XmlQueryTypeFactory.StringX; } - public XmlQueryType CheckStrParseQName(QilBinary node) + public static XmlQueryType CheckStrParseQName(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.StringX); Check(node.Right.XmlType!.IsSubtypeOf(XmlQueryTypeFactory.StringX) || node.Right.XmlType.IsSubtypeOf(XmlQueryTypeFactory.NamespaceS), @@ -532,7 +528,7 @@ public XmlQueryType CheckStrParseQName(QilBinary node) //----------------------------------------------- // value comparison operators //----------------------------------------------- - public XmlQueryType CheckNe(QilBinary node) + public static XmlQueryType CheckNe(QilBinary node) { CheckAtomicX(node.Left); CheckAtomicX(node.Right); @@ -540,27 +536,27 @@ public XmlQueryType CheckNe(QilBinary node) return XmlQueryTypeFactory.BooleanX; } - public XmlQueryType CheckEq(QilBinary node) + public static XmlQueryType CheckEq(QilBinary node) { return CheckNe(node); } - public XmlQueryType CheckGt(QilBinary node) + public static XmlQueryType CheckGt(QilBinary node) { return CheckNe(node); } - public XmlQueryType CheckGe(QilBinary node) + public static XmlQueryType CheckGe(QilBinary node) { return CheckNe(node); } - public XmlQueryType CheckLt(QilBinary node) + public static XmlQueryType CheckLt(QilBinary node) { return CheckNe(node); } - public XmlQueryType CheckLe(QilBinary node) + public static XmlQueryType CheckLe(QilBinary node) { return CheckNe(node); } @@ -571,19 +567,19 @@ public XmlQueryType CheckLe(QilBinary node) //----------------------------------------------- // node comparison operators //----------------------------------------------- - public XmlQueryType CheckIs(QilBinary node) + public static XmlQueryType CheckIs(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf); CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.BooleanX; } - public XmlQueryType CheckAfter(QilBinary node) + public static XmlQueryType CheckAfter(QilBinary node) { return CheckIs(node); } - public XmlQueryType CheckBefore(QilBinary node) + public static XmlQueryType CheckBefore(QilBinary node) { return CheckIs(node); } @@ -594,7 +590,7 @@ public XmlQueryType CheckBefore(QilBinary node) //----------------------------------------------- // loops //----------------------------------------------- - public XmlQueryType CheckLoop(QilLoop node) + public static XmlQueryType CheckLoop(QilLoop node) { CheckClass(node[0], typeof(QilIterator)); Check(node.Variable.NodeType == QilNodeType.For || node.Variable.NodeType == QilNodeType.Let, node, "Loop variable must be a For or Let iterator"); @@ -606,7 +602,7 @@ public XmlQueryType CheckLoop(QilLoop node) return XmlQueryTypeFactory.PrimeProduct(bodyType, variableCard * bodyType.Cardinality); } - public XmlQueryType CheckFilter(QilLoop node) + public static XmlQueryType CheckFilter(QilLoop node) { CheckClass(node[0], typeof(QilIterator)); Check(node.Variable.NodeType == QilNodeType.For || node.Variable.NodeType == QilNodeType.Let, node, "Filter variable must be a For or Let iterator"); @@ -626,7 +622,7 @@ public XmlQueryType CheckFilter(QilLoop node) //----------------------------------------------- // sorting //----------------------------------------------- - public XmlQueryType CheckSort(QilLoop node) + public static XmlQueryType CheckSort(QilLoop node) { XmlQueryType varType = node.Variable.Binding!.XmlType!; @@ -637,14 +633,14 @@ public XmlQueryType CheckSort(QilLoop node) return XmlQueryTypeFactory.PrimeProduct(varType, varType.Cardinality); } - public XmlQueryType CheckSortKey(QilSortKey node) + public static XmlQueryType CheckSortKey(QilSortKey node) { CheckAtomicX(node.Key); CheckXmlType(node.Collation, XmlQueryTypeFactory.StringX); return node.Key.XmlType!; } - public XmlQueryType CheckDocOrderDistinct(QilUnary node) + public static XmlQueryType CheckDocOrderDistinct(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtfS); return DistinctType(node.Child.XmlType!); @@ -656,7 +652,7 @@ public XmlQueryType CheckDocOrderDistinct(QilUnary node) //----------------------------------------------- // function definition and invocation //----------------------------------------------- - public XmlQueryType CheckFunction(QilFunction node) + public static XmlQueryType CheckFunction(QilFunction node) { CheckClassAndNodeType(node[0], typeof(QilList), QilNodeType.FormalParameterList); Check(node[2].NodeType == QilNodeType.False || node[2].NodeType == QilNodeType.True, node, "SideEffects must either be True or False"); @@ -664,7 +660,7 @@ public XmlQueryType CheckFunction(QilFunction node) return node.XmlType!; } - public XmlQueryType CheckInvoke(QilInvoke node) + public static XmlQueryType CheckInvoke(QilInvoke node) { #if DEBUG CheckClassAndNodeType(node[1], typeof(QilList), QilNodeType.ActualParameterList); @@ -686,86 +682,86 @@ public XmlQueryType CheckInvoke(QilInvoke node) //----------------------------------------------- // XML navigation //----------------------------------------------- - public XmlQueryType CheckContent(QilUnary node) + public static XmlQueryType CheckContent(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.AttributeOrContentS; } - public XmlQueryType CheckAttribute(QilBinary node) + public static XmlQueryType CheckAttribute(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf); CheckXmlType(node.Right, XmlQueryTypeFactory.QNameX); return XmlQueryTypeFactory.AttributeQ; } - public XmlQueryType CheckParent(QilUnary node) + public static XmlQueryType CheckParent(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.DocumentOrElementQ; } - public XmlQueryType CheckRoot(QilUnary node) + public static XmlQueryType CheckRoot(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.NodeNotRtf; } - public XmlQueryType CheckXmlContext(QilNode node) + public static XmlQueryType CheckXmlContext(QilNode node) { return XmlQueryTypeFactory.NodeNotRtf; } - public XmlQueryType CheckDescendant(QilUnary node) + public static XmlQueryType CheckDescendant(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.ContentS; } - public XmlQueryType CheckDescendantOrSelf(QilUnary node) + public static XmlQueryType CheckDescendantOrSelf(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.Choice(node.Child.XmlType!, XmlQueryTypeFactory.ContentS); } - public XmlQueryType CheckAncestor(QilUnary node) + public static XmlQueryType CheckAncestor(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.DocumentOrElementS; } - public XmlQueryType CheckAncestorOrSelf(QilUnary node) + public static XmlQueryType CheckAncestorOrSelf(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.Choice(node.Child.XmlType!, XmlQueryTypeFactory.DocumentOrElementS); } - public XmlQueryType CheckPreceding(QilUnary node) + public static XmlQueryType CheckPreceding(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.DocumentOrContentS; } - public XmlQueryType CheckFollowingSibling(QilUnary node) + public static XmlQueryType CheckFollowingSibling(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.ContentS; } - public XmlQueryType CheckPrecedingSibling(QilUnary node) + public static XmlQueryType CheckPrecedingSibling(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.ContentS; } - public XmlQueryType CheckNodeRange(QilBinary node) + public static XmlQueryType CheckNodeRange(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf); CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.Choice(node.Left.XmlType!, XmlQueryTypeFactory.ContentS, node.Right.XmlType!); } - public XmlQueryType CheckDeref(QilBinary node) + public static XmlQueryType CheckDeref(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf); CheckXmlType(node.Right, XmlQueryTypeFactory.StringX); @@ -778,59 +774,59 @@ public XmlQueryType CheckDeref(QilBinary node) //----------------------------------------------- // XML construction //----------------------------------------------- - public XmlQueryType CheckElementCtor(QilBinary node) + public static XmlQueryType CheckElementCtor(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.QNameX); CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS); return XmlQueryTypeFactory.UntypedElement; } - public XmlQueryType CheckAttributeCtor(QilBinary node) + public static XmlQueryType CheckAttributeCtor(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.QNameX); CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS); return XmlQueryTypeFactory.UntypedAttribute; } - public XmlQueryType CheckCommentCtor(QilUnary node) + public static XmlQueryType CheckCommentCtor(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtfS); return XmlQueryTypeFactory.Comment; } - public XmlQueryType CheckPICtor(QilBinary node) + public static XmlQueryType CheckPICtor(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.StringX); CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS); return XmlQueryTypeFactory.PI; } - public XmlQueryType CheckTextCtor(QilUnary node) + public static XmlQueryType CheckTextCtor(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.StringX); return XmlQueryTypeFactory.Text; } - public XmlQueryType CheckRawTextCtor(QilUnary node) + public static XmlQueryType CheckRawTextCtor(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.StringX); return XmlQueryTypeFactory.Text; } - public XmlQueryType CheckDocumentCtor(QilUnary node) + public static XmlQueryType CheckDocumentCtor(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtfS); return XmlQueryTypeFactory.UntypedDocument; } - public XmlQueryType CheckNamespaceDecl(QilBinary node) + public static XmlQueryType CheckNamespaceDecl(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.StringX); CheckXmlType(node.Right, XmlQueryTypeFactory.StringX); return XmlQueryTypeFactory.Namespace; } - public XmlQueryType CheckRtfCtor(QilBinary node) + public static XmlQueryType CheckRtfCtor(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtfS); CheckClassAndNodeType(node.Right, typeof(QilLiteral), QilNodeType.LiteralString); @@ -843,25 +839,25 @@ public XmlQueryType CheckRtfCtor(QilBinary node) //----------------------------------------------- // Node properties //----------------------------------------------- - public XmlQueryType CheckNameOf(QilUnary node) + public static XmlQueryType CheckNameOf(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.Node); return XmlQueryTypeFactory.QNameX; } - public XmlQueryType CheckLocalNameOf(QilUnary node) + public static XmlQueryType CheckLocalNameOf(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.Node); return XmlQueryTypeFactory.StringX; } - public XmlQueryType CheckNamespaceUriOf(QilUnary node) + public static XmlQueryType CheckNamespaceUriOf(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.Node); return XmlQueryTypeFactory.StringX; } - public XmlQueryType CheckPrefixOf(QilUnary node) + public static XmlQueryType CheckPrefixOf(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.Node); return XmlQueryTypeFactory.StringX; @@ -876,19 +872,19 @@ public XmlQueryType CheckPrefixOf(QilUnary node) //----------------------------------------------- // Type operators //----------------------------------------------- - public XmlQueryType CheckTypeAssert(QilTargetType node) + public static XmlQueryType CheckTypeAssert(QilTargetType node) { CheckClassAndNodeType(node[1], typeof(QilLiteral), QilNodeType.LiteralType); return node.TargetType; } - public XmlQueryType CheckIsType(QilTargetType node) + public static XmlQueryType CheckIsType(QilTargetType node) { CheckClassAndNodeType(node[1], typeof(QilLiteral), QilNodeType.LiteralType); return XmlQueryTypeFactory.BooleanX; } - public XmlQueryType CheckIsEmpty(QilUnary node) + public static XmlQueryType CheckIsEmpty(QilUnary node) { return XmlQueryTypeFactory.BooleanX; } @@ -899,25 +895,25 @@ public XmlQueryType CheckIsEmpty(QilUnary node) //----------------------------------------------- // XPath operators //----------------------------------------------- - public XmlQueryType CheckXPathNodeValue(QilUnary node) + public static XmlQueryType CheckXPathNodeValue(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeS); return XmlQueryTypeFactory.StringX; } - public XmlQueryType CheckXPathFollowing(QilUnary node) + public static XmlQueryType CheckXPathFollowing(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.ContentS; } - public XmlQueryType CheckXPathPreceding(QilUnary node) + public static XmlQueryType CheckXPathPreceding(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.ContentS; } - public XmlQueryType CheckXPathNamespace(QilUnary node) + public static XmlQueryType CheckXPathNamespace(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.NamespaceS; @@ -929,20 +925,20 @@ public XmlQueryType CheckXPathNamespace(QilUnary node) //----------------------------------------------- // XSLT //----------------------------------------------- - public XmlQueryType CheckXsltGenerateId(QilUnary node) + public static XmlQueryType CheckXsltGenerateId(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtfS); return XmlQueryTypeFactory.StringX; } - public XmlQueryType CheckXsltInvokeLateBound(QilInvokeLateBound node) + public static XmlQueryType CheckXsltInvokeLateBound(QilInvokeLateBound node) { CheckLiteralValue(node[0], typeof(QilName)); CheckClassAndNodeType(node[1], typeof(QilList), QilNodeType.ActualParameterList); return XmlQueryTypeFactory.ItemS; } - public XmlQueryType CheckXsltInvokeEarlyBound(QilInvokeEarlyBound node) + public static XmlQueryType CheckXsltInvokeEarlyBound(QilInvokeEarlyBound node) { #if DEBUG CheckLiteralValue(node[0], typeof(QilName)); @@ -962,14 +958,14 @@ public XmlQueryType CheckXsltInvokeEarlyBound(QilInvokeEarlyBound node) return node.XmlType!; } - public XmlQueryType CheckXsltCopy(QilBinary node) + public static XmlQueryType CheckXsltCopy(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf); CheckXmlType(node.Right, XmlQueryTypeFactory.NodeS); return XmlQueryTypeFactory.Choice(node.Left.XmlType!, node.Right.XmlType!); } - public XmlQueryType CheckXsltCopyOf(QilUnary node) + public static XmlQueryType CheckXsltCopyOf(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.Node); @@ -979,7 +975,7 @@ public XmlQueryType CheckXsltCopyOf(QilUnary node) return node.Child.XmlType; } - public XmlQueryType CheckXsltConvert(QilTargetType node) + public static XmlQueryType CheckXsltConvert(QilTargetType node) { CheckClassAndNodeType(node[1], typeof(QilLiteral), QilNodeType.LiteralType); return node.TargetType; @@ -992,14 +988,14 @@ public XmlQueryType CheckXsltConvert(QilTargetType node) //----------------------------------------------- [Conditional("DEBUG")] - private void Check(bool value, QilNode node, string message) + private static void Check(bool value, QilNode node, string message) { if (!value) QilValidationVisitor.SetError(node, message); } [Conditional("DEBUG")] - private void CheckLiteralValue(QilNode node, Type clrTypeValue) + private static void CheckLiteralValue(QilNode node, Type clrTypeValue) { Check(node is QilLiteral, node, "Node must be instance of QilLiteral"); @@ -1008,50 +1004,50 @@ private void CheckLiteralValue(QilNode node, Type clrTypeValue) } [Conditional("DEBUG")] - private void CheckClass(QilNode node, Type clrTypeClass) + private static void CheckClass(QilNode node, Type clrTypeClass) { Check(clrTypeClass.IsAssignableFrom(node.GetType()), node, $"Node must be instance of {clrTypeClass.Name}"); } [Conditional("DEBUG")] - private void CheckClassAndNodeType(QilNode node, Type clrTypeClass, QilNodeType nodeType) + private static void CheckClassAndNodeType(QilNode node, Type clrTypeClass, QilNodeType nodeType) { CheckClass(node, clrTypeClass); Check(node.NodeType == nodeType, node, $"Node must have QilNodeType.{nodeType}"); } [Conditional("DEBUG")] - private void CheckXmlType(QilNode node, XmlQueryType xmlType) + private static void CheckXmlType(QilNode node, XmlQueryType xmlType) { Check(node.XmlType!.IsSubtypeOf(xmlType), node, $"Node's type {node.XmlType} is not a subtype of {xmlType}"); } [Conditional("DEBUG")] - private void CheckNumericX(QilNode node) + private static void CheckNumericX(QilNode node) { Check(node.XmlType!.IsNumeric && node.XmlType.IsSingleton && node.XmlType.IsStrict, node, $"Node's type {node.XmlType} must be a strict singleton numeric type"); } [Conditional("DEBUG")] - private void CheckNumericXS(QilNode node) + private static void CheckNumericXS(QilNode node) { Check(node.XmlType!.IsNumeric && node.XmlType.IsStrict, node, $"Node's type {node.XmlType} must be a strict numeric type"); } [Conditional("DEBUG")] - private void CheckAtomicX(QilNode node) + private static void CheckAtomicX(QilNode node) { Check(node.XmlType!.IsAtomicValue && node.XmlType.IsStrict, node, $"Node's type {node.XmlType} must be a strict atomic value type"); } [Conditional("DEBUG")] - private void CheckNotDisjoint(QilBinary node) + private static void CheckNotDisjoint(QilBinary node) { Check(node.Left.XmlType!.IsSubtypeOf(node.Right.XmlType!) || node.Right.XmlType!.IsSubtypeOf(node.Left.XmlType), node, $"Node must not have arguments with disjoint types {node.Left.XmlType} and {node.Right.XmlType}"); } - private XmlQueryType DistinctType(XmlQueryType type) + private static XmlQueryType DistinctType(XmlQueryType type) { if (type.Cardinality == XmlQueryCardinality.More) return XmlQueryTypeFactory.PrimeProduct(type, XmlQueryCardinality.OneOrMore); @@ -1062,7 +1058,7 @@ private XmlQueryType DistinctType(XmlQueryType type) return type; } - private XmlQueryType? FindFilterType(QilIterator variable, QilNode body) + private static XmlQueryType? FindFilterType(QilIterator variable, QilNode body) { XmlQueryType? leftType; QilBinary binary; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilValidationVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilValidationVisitor.cs index b6db4182a56b0..4c83f87adb8f0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilValidationVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilValidationVisitor.cs @@ -26,10 +26,6 @@ namespace System.Xml.Xsl.Qil /// internal sealed class QilValidationVisitor : QilScopedVisitor { -#if DEBUG - private readonly QilTypeChecker _typeCheck = new QilTypeChecker(); -#endif - //----------------------------------------------- // Entry //----------------------------------------------- @@ -68,7 +64,7 @@ protected override QilNode VisitChildren(QilNode parent) } else { - XmlQueryType type = _typeCheck.Check(parent); + XmlQueryType type = QilTypeChecker.Check(parent); // BUGBUG: Hack to account for Xslt compiler type fixups if (!type.IsSubtypeOf(parent.XmlType)) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs index e88c7c7210b3d..670aff81778bb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs @@ -265,7 +265,7 @@ protected override void BeginScope(QilNode node) /// protected override void EndScope(QilNode node) { - _ngen.ClearName(node); + NameGenerator.ClearName(node); } /// @@ -430,7 +430,7 @@ public string NameOf(QilNode n) /// Clear name annotation from a node. /// /// the node - public void ClearName(QilNode n) + public static void ClearName(QilNode n) { if (n.Annotation is NameAnnotation) n.Annotation = ((NameAnnotation)n.Annotation).PriorAnnotation; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlExtensionFunction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlExtensionFunction.cs index da2e1b645d436..c932dca6b99d9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlExtensionFunction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlExtensionFunction.cs @@ -340,7 +340,7 @@ private Type GetClrType(Type clrType) /// /// Infer an Xml type from a Clr type using Xslt inference rules /// - private XmlQueryType InferXmlType(Type clrType) + private static XmlQueryType InferXmlType(Type clrType) { return XsltConvert.InferXsltType(clrType); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs index b1f064c03ed93..b98814770aac1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs @@ -308,7 +308,7 @@ public IList InvokeXsltLateBoundFunction(string name, string namespac // 4. Change the Clr representation to the Clr type of the formal argument clrTypeFormalArg = extFunc.GetClrArgumentType(i); if (xmlTypeFormalArg.TypeCode == XmlTypeCode.Item || !clrTypeFormalArg.IsAssignableFrom(objActualArgs[i].GetType())) - objActualArgs[i] = _runtime.ChangeTypeXsltArgument(xmlTypeFormalArg, objActualArgs[i], clrTypeFormalArg); + objActualArgs[i] = XmlQueryRuntime.ChangeTypeXsltArgument(xmlTypeFormalArg, objActualArgs[i], clrTypeFormalArg); } // 1. Invoke the late bound method diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs index ff568796cb0de..cd3400775c2b1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs @@ -1328,7 +1328,7 @@ private void WriteCachedNamespaces() /// /// Return the type of node that is under construction given the specified XmlState. /// - private XPathNodeType XmlStateToNodeType(XmlState xstate) + private static XPathNodeType XmlStateToNodeType(XmlState xstate) { switch (xstate) { 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 f645633dbbb47..45746ac58d8dc 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 @@ -486,7 +486,7 @@ public object ChangeTypeXsltArgument(int indexType, object value, Type destinati /// Convert from the Clr type of "value" to Clr type "destinationType" using V1 Xslt rules. /// These rules include converting any Rtf values to Nodes. /// - internal object ChangeTypeXsltArgument(XmlQueryType xmlType, object value, Type destinationType) + internal static object ChangeTypeXsltArgument(XmlQueryType xmlType, object value, Type destinationType) { Debug.Assert(XmlILTypeHelper.GetStorageType(xmlType).IsAssignableFrom(value.GetType()), "Values passed to ChangeTypeXsltArgument should be in ILGen's default Clr representation."); @@ -793,7 +793,7 @@ public bool MatchesXmlType(XPathItem item, XmlTypeCode code) /// /// Create an XmlQueryType that represents the type of "item". /// - private XmlQueryType CreateXmlType(XPathItem item) + private static XmlQueryType CreateXmlType(XPathItem item) { if (item.IsNode) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs index c6b516c7fdbea..d834225751238 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs @@ -171,7 +171,7 @@ public int RegisterDecimalFormat(XmlQualifiedName name, string infinitySymbol, s return 0; // have to return something } - private DecimalFormat CreateDecimalFormat(string infinitySymbol, string nanSymbol, string characters) + private static DecimalFormat CreateDecimalFormat(string infinitySymbol, string nanSymbol, string characters) { // BUGBUG: Fallback to the old XSLT implementation NumberFormatInfo info = new NumberFormatInfo(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathBuilder.cs index afbe996d494ed..8e83ca7fbb4c2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathBuilder.cs @@ -166,7 +166,7 @@ private QilNode CompareValues(XPathOperator op, QilNode left, QilNode right, Xml private QilNode CompareNodeSetAndValue(XPathOperator op, QilNode nodeset, QilNode val, XmlTypeCode compType) { - _f.CheckNodeSet(nodeset); + XPathQilFactory.CheckNodeSet(nodeset); Debug.Assert(val.XmlType!.IsSingleton); Debug.Assert(compType == XmlTypeCode.Boolean || compType == XmlTypeCode.Double || compType == XmlTypeCode.String, "I don't know what to do with RTF here"); if (compType == XmlTypeCode.Boolean || nodeset.XmlType!.IsSingleton) @@ -194,8 +194,8 @@ private static XPathOperator InvertOp(XPathOperator op) private QilNode CompareNodeSetAndNodeSet(XPathOperator op, QilNode left, QilNode right, XmlTypeCode compType) { - _f.CheckNodeSet(left); - _f.CheckNodeSet(right); + XPathQilFactory.CheckNodeSet(left); + XPathQilFactory.CheckNodeSet(right); if (right.XmlType!.IsSingleton) { return CompareNodeSetAndValue(op, /*nodeset:*/left, /*value:*/right, compType); @@ -216,7 +216,7 @@ private QilNode EqualityOperator(XPathOperator op, QilNode left, QilNode right) XmlQueryType leftType = left.XmlType!; XmlQueryType rightType = right.XmlType!; - if (_f.IsAnyType(left) || _f.IsAnyType(right)) + if (XPathQilFactory.IsAnyType(left) || XPathQilFactory.IsAnyType(right)) { return _f.InvokeEqualityOperator(s_qilOperator[(int)op], left, right); } @@ -249,7 +249,7 @@ private QilNode RelationalOperator(XPathOperator op, QilNode left, QilNode right XmlQueryType leftType = left.XmlType!; XmlQueryType rightType = right.XmlType!; - if (_f.IsAnyType(left) || _f.IsAnyType(right)) + if (XPathQilFactory.IsAnyType(left) || XPathQilFactory.IsAnyType(right)) { return _f.InvokeRelationalOperator(s_qilOperator[(int)op], left, right); } @@ -439,7 +439,7 @@ public virtual QilNode Axis(XPathAxis xpathAxis, XPathNodeType nodeType, string? // "left/right" public virtual QilNode JoinStep(QilNode left, QilNode right) { - _f.CheckNodeSet(right); + XPathQilFactory.CheckNodeSet(right); QilIterator leftIt = _f.For(_f.EnsureNodeSet(left)); // in XPath 1.0 step is always nodetest and as a result it can't contain last(). right = _fixupVisitor.Fixup(right, /*current:*/leftIt, /*last:*/null); @@ -473,7 +473,7 @@ public virtual QilNode Predicate(QilNode nodeset, QilNode predicate, bool isReve public static QilNode PredicateToBoolean(QilNode predicate, XPathQilFactory f, IXPathEnvironment env) { // Prepocess predicate: if (predicate is number) then predicate := (position() == predicate) - if (!f.IsAnyType(predicate)) + if (!XPathQilFactory.IsAnyType(predicate)) { if (predicate.XmlType!.TypeCode == XmlTypeCode.Double) { @@ -611,7 +611,7 @@ public virtual QilNode Function(string prefix, string name, IList args) private QilNode LocalNameOfFirstNode(QilNode arg) { - _f.CheckNodeSet(arg); + XPathQilFactory.CheckNodeSet(arg); if (arg.XmlType!.IsSingleton) { return _f.LocalNameOf(arg); @@ -625,7 +625,7 @@ private QilNode LocalNameOfFirstNode(QilNode arg) private QilNode NamespaceOfFirstNode(QilNode arg) { - _f.CheckNodeSet(arg); + XPathQilFactory.CheckNodeSet(arg); if (arg.XmlType!.IsSingleton) { return _f.NamespaceUriOf(arg); @@ -639,7 +639,7 @@ private QilNode NamespaceOfFirstNode(QilNode arg) private QilNode NameOf(QilNode arg) { - _f.CheckNodeNotRtf(arg); + XPathQilFactory.CheckNodeNotRtf(arg); // We may want to introduce a new QIL node that returns a string. if (arg is QilIterator) { @@ -657,7 +657,7 @@ private QilNode NameOf(QilNode arg) private QilNode NameOfFirstNode(QilNode arg) { - _f.CheckNodeSet(arg); + XPathQilFactory.CheckNodeSet(arg); if (arg.XmlType!.IsSingleton) { return NameOf(arg); @@ -671,7 +671,7 @@ private QilNode NameOfFirstNode(QilNode arg) private QilNode Sum(QilNode arg) { - _f.CheckNodeSet(arg); + XPathQilFactory.CheckNodeSet(arg); QilIterator i; return _f.Sum(_f.Sequence(_f.Double(0d), _f.Loop(i = _f.For(arg), _f.ConvertToNumber(i)))); } @@ -1047,7 +1047,7 @@ public void CastArguments(IList args, string name, XPathQilFactory f) Debug.Assert(args.Count == 0 || argTypes != null); for (int i = 0; i < args.Count; i++) { - if (argTypes![i] == XmlTypeCode.Node && f.CannotBeNodeSet(args[i])) + if (argTypes![i] == XmlTypeCode.Node && XPathQilFactory.CannotBeNodeSet(args[i])) { throw new XPathCompileException(SR.XPath_NodeSetArgumentExpected, name, (i + 1).ToString(CultureInfo.InvariantCulture)); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs index 72466b36240c1..6ef90e31efd0f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs @@ -35,7 +35,7 @@ public QilIterator FirstNode(QilNode n) return For(Filter(i, Eq(PositionOf(i), Int32(1)))); } - public bool IsAnyType(QilNode n) + public static bool IsAnyType(QilNode n) { XmlQueryType? xt = n.XmlType; bool result = !(xt!.IsStrict || xt.IsNode); @@ -44,49 +44,49 @@ public bool IsAnyType(QilNode n) } [Conditional("DEBUG")] - public void CheckNode(QilNode n) + public static void CheckNode(QilNode n) { Debug.Assert(n != null && n.XmlType!.IsSingleton && n.XmlType.IsNode, "Must be a singleton node"); } [Conditional("DEBUG")] - public void CheckNodeSet(QilNode n) + public static void CheckNodeSet(QilNode n) { Debug.Assert(n != null && n.XmlType!.IsNode, "Must be a node-set"); } [Conditional("DEBUG")] - public void CheckNodeNotRtf(QilNode n) + public static void CheckNodeNotRtf(QilNode n) { Debug.Assert(n != null && n.XmlType!.IsSingleton && n.XmlType.IsNode && n.XmlType.IsNotRtf, "Must be a singleton node and not an Rtf"); } [Conditional("DEBUG")] - public void CheckString(QilNode n) + public static void CheckString(QilNode n) { Debug.Assert(n != null && n.XmlType!.IsSubtypeOf(T.StringX), "Must be a singleton string"); } [Conditional("DEBUG")] - public void CheckStringS(QilNode n) + public static void CheckStringS(QilNode n) { Debug.Assert(n != null && n.XmlType!.IsSubtypeOf(T.StringXS), "Must be a sequence of strings"); } [Conditional("DEBUG")] - public void CheckDouble(QilNode n) + public static void CheckDouble(QilNode n) { Debug.Assert(n != null && n.XmlType!.IsSubtypeOf(T.DoubleX), "Must be a singleton Double"); } [Conditional("DEBUG")] - public void CheckBool(QilNode n) + public static void CheckBool(QilNode n) { Debug.Assert(n != null && n.XmlType!.IsSubtypeOf(T.BooleanX), "Must be a singleton Bool"); } // Return true if inferred type of the given expression is never a subtype of T.NodeS - public bool CannotBeNodeSet(QilNode n) + public static bool CannotBeNodeSet(QilNode n) { XmlQueryType xt = n.XmlType!; // Do not report compile error if n is a VarPar, whose inferred type forbids nodes (SQLBUDT 339398) @@ -166,7 +166,7 @@ public QilNode InvokeRelationalOperator(QilNodeType op, QilNode left, QilNode ri #region Type Conversions [Conditional("DEBUG")] - private void ExpectAny(QilNode n) + private static void ExpectAny(QilNode n) { Debug.Assert(IsAnyType(n), $"Unexpected expression type: {n.XmlType}"); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathScanner.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathScanner.cs index 119f76a1b1201..ad7d59e03f435 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathScanner.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathScanner.cs @@ -566,7 +566,7 @@ public void CheckToken(LexKind t) } // May be called for the following tokens: Name, String, Eof, Comma, LParens, RParens, LBracket, RBracket, RBrace - private string LexKindToString(LexKind t) + private static string LexKindToString(LexKind t) { Debug.Assert(LexKind.FirstStringable <= t); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Compiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Compiler.cs index 7377607cbb0d5..8b637b57b773b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Compiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Compiler.cs @@ -230,7 +230,7 @@ public bool ParseNameTest(string nameTest, out string? prefix, out string? local } } - public void ValidatePiName(string name, IErrorHelper errorHelper) + public static void ValidatePiName(string name, IErrorHelper errorHelper) { Debug.Assert(name != null); try @@ -255,12 +255,12 @@ public string CreatePhantomNamespace() return $"\0namespace{_phantomNsCounter++}"; } - public bool IsPhantomNamespace(string namespaceName) + public static bool IsPhantomNamespace(string namespaceName) { return namespaceName.Length > 0 && namespaceName[0] == '\0'; } - public bool IsPhantomName(QilName qname) + public static bool IsPhantomName(QilName qname) { string nsUri = qname.NamespaceUri; return nsUri.Length > 0 && nsUri[0] == '\0'; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/InvokeGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/InvokeGenerator.cs index 9cd4c14dc1334..3925e60fe18d9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/InvokeGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/InvokeGenerator.cs @@ -99,7 +99,7 @@ public QilNode GenerateInvoke(QilFunction func, IList actualArgs) return invoke; } - private QilNode? FindActualArg(QilParameter formalArg, IList actualArgs) + private static QilNode? FindActualArg(QilParameter formalArg, IList actualArgs) { QilName? argName = formalArg.Name; Debug.Assert(argName != null); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs index 8595d37ff3d5e..517f6815ee1cf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs @@ -416,7 +416,7 @@ private QilNode MatchPatterns(QilIterator it, XmlQueryType xt, List pat return _f.Conditional(_f.IsType(it, xt), MatchPatterns(it, patternList), otherwise); } - private bool IsNoMatch(QilNode matcher) + private static bool IsNoMatch(QilNode matcher) { if (matcher.NodeType == QilNodeType.LiteralInt32) { 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 4b4a5c508615f..a3635fd2b348e 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 @@ -1106,7 +1106,7 @@ private QilNode CompilePI(XslNode node) if (qilName.NodeType == QilNodeType.LiteralString) { string name = (string)(QilLiteral)qilName; - _compiler.ValidatePiName(name, (IErrorHelper)this); + Compiler.ValidatePiName(name, (IErrorHelper)this); } return _f.PICtor(qilName, CompileInstructions(node.Content)); } @@ -1249,7 +1249,7 @@ private QilNode CompileCallTemplate(XslNodeEx node) } else { - if (!_compiler.IsPhantomName(node.Name!)) + if (!Compiler.IsPhantomName(node.Name!)) { _compiler.ReportError(/*[XT0710]*/node.SourceLine!, SR.Xslt_InvalidCallTemplate, node.Name!.QualifiedName); } @@ -1284,7 +1284,7 @@ private QilNode CompileUseAttributeSet(XslNode node) } else { - if (!_compiler.IsPhantomName(node.Name!)) + if (!Compiler.IsPhantomName(node.Name!)) { _compiler.ReportError(/*[XT0710]*/node.SourceLine!, SR.Xslt_NoAttributeSet, node.Name!.QualifiedName); } @@ -1297,7 +1297,7 @@ private QilNode CompileUseAttributeSet(XslNode node) private QilNode CompileCopy(XslNode copy) { QilNode node = GetCurrentNode(); - _f.CheckNodeNotRtf(node); + XPathQilFactory.CheckNodeNotRtf(node); if ((node.XmlType!.NodeKinds & InvalidatingNodes) != XmlNodeKindFlags.None) { _outputScope.InvalidateAllPrefixes(); @@ -1825,7 +1825,7 @@ private QilNode MatchPattern(QilNode pattern, QilIterator testNode) for (int i = list.Count - 1; 0 <= i; i--) { QilLoop filter = (QilLoop)list[i]; - _ptrnBuilder.AssertFilter(filter); + XPathPatternBuilder.AssertFilter(filter); result = _f.Or( _refReplacer.Replace(filter.Body, filter.Variable, testNode), result @@ -2486,7 +2486,7 @@ private QilNode CompileKeyUse(Key key) private QilNode ResolveQNameDynamic(bool ignoreDefaultNs, QilNode qilName) { - _f.CheckString(qilName); + XPathQilFactory.CheckString(qilName); QilList nsDecls = _f.BaseFactory.Sequence(); if (ignoreDefaultNs) { @@ -2525,7 +2525,7 @@ private QilNode GenerateApply(StylesheetLevel sheet, XslNode node) return InvokeApplyFunction(sheet, /*mode:*/node.Name!, node.Content); } - private void SetArg(IList args, int pos, QilName name, QilNode value) + private static void SetArg(IList args, int pos, QilName name, QilNode value) { VarPar varPar; if (args.Count <= pos || args[pos].Name != name) @@ -2564,7 +2564,7 @@ private void SetArg(IList args, int pos, QilName name, QilNode value) // Returns true if formalArgs maps 1:1 with actual args. // Formaly this is n*n algorithm. We can optimize it by calculationg "signature" // of the function as sum of all hashes of its args names. - private bool FillupInvokeArgs(IList formalArgs, IList actualArgs, QilList invokeArgs) + private static bool FillupInvokeArgs(IList formalArgs, IList actualArgs, QilList invokeArgs) { if (actualArgs.Count != formalArgs.Count) { @@ -2752,7 +2752,7 @@ public void ReportWarning(string res, params string?[]? args) private void VerifyXPathQName(QilName qname) { Debug.Assert( - _compiler.IsPhantomName(qname) || + Compiler.IsPhantomName(qname) || qname.NamespaceUri == ResolvePrefix(/*ignoreDefaultNs:*/true, qname.Prefix), "QilGenerator must resolve the prefix to the same namespace as XsltLoader" ); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGeneratorEnv.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGeneratorEnv.cs index a873617549be4..af39a230b3478 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGeneratorEnv.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGeneratorEnv.cs @@ -530,7 +530,7 @@ private QilNode CompileFnDocument(QilNode uris, QilNode? baseNode) private QilNode CompileSingleDocument(QilNode uri, QilNode? baseNode) { - _f.CheckString(uri); + XPathQilFactory.CheckString(uri); QilNode baseUri; if (baseNode == null) @@ -539,7 +539,7 @@ private QilNode CompileSingleDocument(QilNode uri, QilNode? baseNode) } else { - _f.CheckNodeSet(baseNode); + XPathQilFactory.CheckNodeSet(baseNode); if (baseNode.XmlType!.IsSingleton) { baseUri = _f.InvokeBaseUri(baseNode); @@ -554,14 +554,14 @@ private QilNode CompileSingleDocument(QilNode uri, QilNode? baseNode) } } - _f.CheckString(baseUri); + XPathQilFactory.CheckString(baseUri); return _f.DataSource(uri, baseUri); } private QilNode CompileFormatNumber(QilNode value, QilNode formatPicture, QilNode? formatName) { - _f.CheckDouble(value); - _f.CheckString(formatPicture); + XPathQilFactory.CheckDouble(value); + XPathQilFactory.CheckString(formatPicture); XmlQualifiedName? resolvedName; if (formatName == null) @@ -572,7 +572,7 @@ private QilNode CompileFormatNumber(QilNode value, QilNode formatPicture, QilNod } else { - _f.CheckString(formatName); + XPathQilFactory.CheckString(formatName); if (formatName.NodeType == QilNodeType.LiteralString) { resolvedName = ResolveQNameThrow(/*ignoreDefaultNs:*/true, formatName); @@ -626,13 +626,13 @@ private QilNode CompileFormatNumber(QilNode value, QilNode formatPicture, QilNod private QilNode CompileUnparsedEntityUri(QilNode n) { - _f.CheckString(n); + XPathQilFactory.CheckString(n); return _f.Error(_lastScope!.SourceLine, SR.Xslt_UnsupportedXsltFunction, "unparsed-entity-uri"); } private QilNode CompileGenerateId(QilNode n) { - _f.CheckNodeSet(n); + XPathQilFactory.CheckNodeSet(n); if (n.XmlType!.IsSingleton) { return _f.XsltGenerateId(n); @@ -655,7 +655,7 @@ private XmlQualifiedName ResolveQNameThrow(bool ignoreDefaultNs, QilNode qilName private QilNode CompileSystemProperty(QilNode name) { - _f.CheckString(name); + XPathQilFactory.CheckString(name); if (name.NodeType == QilNodeType.LiteralString) { XmlQualifiedName qname = ResolveQNameThrow(/*ignoreDefaultNs:*/true, name); @@ -683,7 +683,7 @@ private QilNode CompileSystemProperty(QilNode name) private QilNode CompileElementAvailable(QilNode name) { - _f.CheckString(name); + XPathQilFactory.CheckString(name); if (name.NodeType == QilNodeType.LiteralString) { XmlQualifiedName qname = ResolveQNameThrow(/*ignoreDefaultNs:*/false, name); @@ -702,7 +702,7 @@ private QilNode CompileElementAvailable(QilNode name) private QilNode CompileFunctionAvailable(QilNode name) { - _f.CheckString(name); + XPathQilFactory.CheckString(name); if (name.NodeType == QilNodeType.LiteralString) { XmlQualifiedName qname = ResolveQNameThrow(/*ignoreDefaultNs:*/true, name); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XPathPatternBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XPathPatternBuilder.cs index e60c3ce827c8c..66ddbc2a6f7c9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XPathPatternBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XPathPatternBuilder.cs @@ -48,7 +48,7 @@ public void StartBuild() } [Conditional("DEBUG")] - public void AssertFilter(QilLoop filter) + public static void AssertFilter(QilLoop filter) { Debug.Assert(filter.NodeType == QilNodeType.Filter, "XPathPatternBuilder expected to generate list of Filters on top level"); Debug.Assert(filter.Variable.XmlType!.IsSubtypeOf(T.NodeNotRtf)); @@ -56,7 +56,7 @@ public void AssertFilter(QilLoop filter) Debug.Assert(filter.Body.XmlType!.IsSubtypeOf(T.Boolean)); } - private void FixupFilterBinding(QilLoop filter, QilNode newBinding) + private static void FixupFilterBinding(QilLoop filter, QilNode newBinding) { AssertFilter(filter); filter.Variable.Binding = newBinding; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAst.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAst.cs index 9c94a48a2cd77..f23646770dbe1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAst.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAst.cs @@ -136,51 +136,6 @@ public void InsertContent(IEnumerable collection) _content.InsertRange(0, collection); } } - - internal string? TraceName - { - get - { -#if DEBUG - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - string nodeTypeName = NodeType switch - { - XslNodeType.AttributeSet => "attribute-set", - XslNodeType.Template => "template", - XslNodeType.Param => "param", - XslNodeType.Variable => "variable", - XslNodeType.WithParam => "with-param", - _ => NodeType.ToString(), - }; - sb.Append(nodeTypeName); - if (Name != null) - { - sb.Append(' '); - sb.Append(Name.QualifiedName); - } - - ISourceLineInfo? lineInfo = SourceLine; - if (lineInfo == null && NodeType == XslNodeType.AttributeSet) - { - lineInfo = Content[0].SourceLine; - Debug.Assert(lineInfo != null); - } - if (lineInfo != null) - { - string fileName = SourceLineInfo.GetFileName(lineInfo.Uri!); - int idx = fileName.LastIndexOf(System.IO.Path.DirectorySeparatorChar) + 1; - sb.Append(" ("); - sb.Append(fileName, idx, fileName.Length - idx); - sb.Append(':'); - sb.Append(lineInfo.Start.Line); - sb.Append(')'); - } - return sb.ToString(); -#else - return null; -#endif - } - } } internal abstract class ProtoTemplate : XslNode diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAstAnalyzer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAstAnalyzer.cs index b3ecb042a8690..315035919808c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAstAnalyzer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XslAstAnalyzer.cs @@ -1435,7 +1435,7 @@ private void Refactor(XslNode parent, int split) { // The scope record is either a namespace declaration or an exclusion namespace Debug.Assert(scoperecord.IsNamespace || scoperecord.ncName == null); - Debug.Assert(!_compiler.IsPhantomNamespace(scoperecord.nsUri!)); + Debug.Assert(!Compiler.IsPhantomNamespace(scoperecord.nsUri!)); newtemplate.Namespaces = new NsDecl(newtemplate.Namespaces, scoperecord.ncName, scoperecord.nsUri); } else @@ -1444,7 +1444,7 @@ private void Refactor(XslNode parent, int split) var variable = scoperecord.value; // Skip variables generated during errors - if (_compiler.IsPhantomNamespace(variable.Name!.NamespaceUri)) + if (Compiler.IsPhantomNamespace(variable.Name!.NamespaceUri)) { continue; } 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 a9e764763c5b4..7abe2cb1c3d66 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 @@ -2876,7 +2876,7 @@ private void ParseWhitespaceRules(string elements, bool preserveSpace) ResolveQName(/*ignoreDefaultNs:*/true, attValue, out localName, out namespaceName, out prefix); method = XmlOutputMethod.AutoDetect; - if (_compiler.IsPhantomNamespace(namespaceName)) + if (Compiler.IsPhantomNamespace(namespaceName)) { return null; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltQilFactory.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltQilFactory.cs index d923e086c9bec..670bac0d06b7f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltQilFactory.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/XsltQilFactory.cs @@ -41,7 +41,7 @@ public void CheckXsltType(QilNode n) } [Conditional("DEBUG")] - public void CheckQName(QilNode n) + public static void CheckQName(QilNode n) { Debug.Assert(n != null && n.XmlType!.IsSubtypeOf(T.QNameX), "Must be a singleton QName"); } 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 e0357b481bcf9..e84929703ea88 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 @@ -66,7 +66,7 @@ public void CompileAttributes(Compiler compiler) return result; } - public void CheckEmpty(Compiler compiler) + public static void CheckEmpty(Compiler compiler) { // Really EMPTY means no content at all, but the sake of compatibility with MSXML we allow whitespace string elementName = compiler.Input.Name; @@ -90,12 +90,12 @@ public void CheckEmpty(Compiler compiler) } } - public void CheckRequiredAttribute(Compiler compiler, object? attrValue, string attrName) + public static void CheckRequiredAttribute(Compiler compiler, object? attrValue, string attrName) { CheckRequiredAttribute(compiler, attrValue != null, attrName); } - public void CheckRequiredAttribute(Compiler compiler, bool attr, string attrName) + public static void CheckRequiredAttribute(Compiler compiler, 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 b38aec5b1267d..92deedfc9d972 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 @@ -309,7 +309,6 @@ protected InputScopeManager ScopeManager internal virtual void PopScope() { - _currentTemplate!.ReleaseVariableSlots(_scopeManager.CurrentScope!.GetVeriablesCount()); _scopeManager.PopScope(); } 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 b9aa4d89e25b8..d311e7bb8991c 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 @@ -44,7 +44,7 @@ internal override void Compile(Compiler compiler) throw new NotImplementedException(); } - internal void CompileStylesheetAttributes(Compiler compiler) + internal static void CompileStylesheetAttributes(Compiler compiler) { NavigatorInput input = compiler.Input; string element = input.LocalName; @@ -109,7 +109,7 @@ internal void CompileStylesheetAttributes(Compiler compiler) } } - internal void CompileSingleTemplate(Compiler compiler) + internal static void CompileSingleTemplate(Compiler compiler) { NavigatorInput input = compiler.Input; @@ -266,7 +266,7 @@ private void CompileInclude(Compiler compiler) CheckEmpty(compiler); } - internal void CompileNamespaceAlias(Compiler compiler) + internal static void CompileNamespaceAlias(Compiler compiler) { NavigatorInput input = compiler.Input; string element = input.LocalName; @@ -311,7 +311,7 @@ internal void CompileNamespaceAlias(Compiler compiler) compiler.AddNamespaceAlias(namespace1!, new NamespaceInfo(prefix2, namespace2, compiler.Stylesheetid)); } - internal void CompileKey(Compiler compiler) + internal static void CompileKey(Compiler compiler) { NavigatorInput input = compiler.Input; string element = input.LocalName; @@ -362,7 +362,7 @@ internal void CompileKey(Compiler compiler) compiler.InsertKey(Name!, MatchKey, UseKey); } - protected void CompileDecimalFormat(Compiler compiler) + protected static void CompileDecimalFormat(Compiler compiler) { NumberFormatInfo info = new NumberFormatInfo(); DecimalFormat format = new DecimalFormat(info, '#', '0', ';'); @@ -443,7 +443,7 @@ protected void CompileDecimalFormat(Compiler compiler) CheckEmpty(compiler); } - internal bool CheckAttribute(bool valid, Compiler compiler) + internal static bool CheckAttribute(bool valid, Compiler compiler) { if (!valid) { @@ -456,7 +456,7 @@ internal bool CheckAttribute(bool valid, Compiler compiler) return true; } - protected void CompileSpace(Compiler compiler, bool preserve) + protected static void CompileSpace(Compiler compiler, bool preserve) { string value = compiler.GetSingleAttribute(compiler.Input.Atoms.Elements); string[] elements = XmlConvert.SplitString(value); @@ -468,7 +468,7 @@ protected void CompileSpace(Compiler compiler, bool preserve) CheckEmpty(compiler); } - private double NameTest(string name) + private static double NameTest(string name) { if (name == "*") { @@ -891,7 +891,7 @@ protected void AddEvents(ArrayList copyEvents) lastCopyCodeAction.AddEvents(copyEvents); } - private void AddScript(Compiler compiler) + private static void AddScript(Compiler compiler) { NavigatorInput input = compiler.Input; 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 7c38c5269e1a6..bc031f66362f6 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 @@ -471,7 +471,7 @@ private bool MatchCountKey(Processor processor, XPathNavigator contextNode, XPat return false; } - private XPathNodeType BasicNodeType(XPathNodeType type) + private static XPathNodeType BasicNodeType(XPathNodeType type) { if (type == XPathNodeType.SignificantWhitespace || type == XPathNodeType.Whitespace) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutKeywords.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutKeywords.cs index 4ec228d48d16c..7abb4d093cd51 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutKeywords.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/OutKeywords.cs @@ -107,6 +107,7 @@ internal string XmlnsNamespace } } +#pragma warning disable CA1822 [System.Diagnostics.Conditional("DEBUG")] private void CheckKeyword(string keyword) { @@ -115,5 +116,6 @@ private void CheckKeyword(string keyword) Debug.Assert((object)keyword == (object?)_NameTable.Get(keyword)); #endif } +#pragma warning restore CA1822 } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs index 28610ebc78174..d6e1167a0b6b4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/Processor.cs @@ -293,6 +293,7 @@ internal StringBuilder GetSharedStringBuilder() return _sharedStringBuilder; } +#pragma warning disable CA1822 internal void ReleaseSharedStringBuilder() { // don't clean stringBuilderLocked here. ToString() will happen after this call @@ -300,6 +301,7 @@ internal void ReleaseSharedStringBuilder() _stringBuilderLocked = false; #endif } +#pragma warning restore CA1822 internal ArrayList NumberList { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ReaderOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ReaderOutput.cs index 4bfe6cdf71d29..dd263bf263be3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ReaderOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/ReaderOutput.cs @@ -157,7 +157,7 @@ public override bool IsEmptyElement public override char QuoteChar { - get { return _encoder.QuoteChar; } + get { return XmlEncoder.QuoteChar; } } public override bool IsDefault @@ -732,10 +732,7 @@ public string AttributeOuterXml(string name, string value) return _buffer.ToString(); } - public char QuoteChar - { - get { return '"'; } - } + public const char QuoteChar = '"'; } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateBaseAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateBaseAction.cs index a716f37c340c0..20035ea3538e3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateBaseAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/TemplateBaseAction.cs @@ -29,13 +29,5 @@ public int AllocateVariableSlot() } return thisSlot; } - - public void ReleaseVariableSlots(int n) - { - // This code does optimisation of variable placement. Commented out for this version - // Reuse of the variable disable the check that variable was assigned before the actual use - // this check has to be done in compile time n future. - // this.variableFreeSlot -= n; - } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltCompileContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltCompileContext.cs index abff50de6c97a..1d97be00d4028 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltCompileContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XsltOld/XsltCompileContext.cs @@ -108,7 +108,7 @@ public override bool PreserveWhitespace(XPathNavigator node) return _processor!.Stylesheet.PreserveWhiteSpace(_processor, node); } - private MethodInfo? FindBestMethod(MethodInfo[] methods, bool ignoreCase, bool publicOnly, string name, XPathResultType[]? argTypes) + private static MethodInfo? FindBestMethod(MethodInfo[] methods, bool ignoreCase, bool publicOnly, string name, XPathResultType[]? argTypes) { int length = methods.Length; int free = 0; diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingType.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingType.cs index a23c02cef220d..47b624dc89e33 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingType.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/ProjectingType.cs @@ -68,7 +68,7 @@ public override Type GetEnumUnderlyingType() public override object[] GetCustomAttributes(Type attributeType, bool inherit) { - attributeType = _projector.Unproject(attributeType); + attributeType = Projector.Unproject(attributeType); return base.GetCustomAttributes(attributeType, inherit); } @@ -100,7 +100,7 @@ public override Type GetGenericTypeDefinition() public override InterfaceMapping GetInterfaceMap(Type interfaceType) { - interfaceType = _projector.Unproject(interfaceType); + interfaceType = Projector.Unproject(interfaceType); return _projector.ProjectInterfaceMapping(base.GetInterfaceMap(interfaceType)); } @@ -146,7 +146,7 @@ public override bool IsAssignableFrom([NotNullWhen(true)] Type? c) public override bool IsDefined(Type attributeType, bool inherit) { - attributeType = _projector.Unproject(attributeType); + attributeType = Projector.Unproject(attributeType); return base.IsDefined(attributeType, inherit); } @@ -181,7 +181,7 @@ public override bool IsSubclassOf(Type c) protected override ConstructorInfo? GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { - types = _projector.Unproject(types); + types = Projector.Unproject(types); return _projector.ProjectConstructor(base.GetConstructorImpl(bindingAttr, binder, callConvention, types, modifiers)); } @@ -259,7 +259,7 @@ public override MemberInfo[] GetMembers(BindingFlags bindingAttr) protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { - types = _projector.Unproject(types); + types = Projector.Unproject(types); return _projector.ProjectMethod(base.GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers)); } @@ -286,8 +286,8 @@ public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) protected override PropertyInfo? GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { - returnType = _projector.Unproject(returnType); - types = _projector.Unproject(types); + returnType = Projector.Unproject(returnType); + types = Projector.Unproject(types); return _projector.ProjectProperty(base.GetPropertyImpl(name, bindingAttr, binder, returnType, types, modifiers)); } @@ -310,7 +310,7 @@ public override Type MakePointerType() [RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] public override Type MakeGenericType(params Type[] typeArguments) { - typeArguments = _projector.Unproject(typeArguments); + typeArguments = Projector.Unproject(typeArguments); return _projector.ProjectType(base.MakeGenericType(typeArguments)); } diff --git a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/Projector.cs b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/Projector.cs index 8e4772e19062d..6ffc69bed0530 100644 --- a/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/Projector.cs +++ b/src/libraries/System.Reflection.Context/src/System/Reflection/Context/Projection/Projector.cs @@ -79,7 +79,7 @@ public T Project(T value, Func project) public abstract MemberInfo? ProjectMember(MemberInfo? value); [return: NotNullIfNotNull("values")] - public Type[]? Unproject(Type[]? values) + public static Type[]? Unproject(Type[]? values) { if (values == null) return null; @@ -94,7 +94,7 @@ public T Project(T value, Func project) } [return: NotNullIfNotNull("value")] - public Type? Unproject(Type? value) + public static Type? Unproject(Type? value) { if (value is ProjectingType projectingType) return projectingType.UnderlyingType; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobBuilder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobBuilder.cs index 6a641f97092bd..3235d1c3cc215 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobBuilder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/BlobBuilder.cs @@ -119,9 +119,9 @@ internal void ClearChunk() _nextOrPrevious = this; } + [Conditional("DEBUG")] private void CheckInvariants() { -#if DEBUG Debug.Assert(_buffer != null); Debug.Assert(Length >= 0 && Length <= _buffer.Length); Debug.Assert(_nextOrPrevious != null); @@ -140,7 +140,6 @@ private void CheckInvariants() Debug.Assert(totalLength == Count); } -#endif } public int Count => _previousLengthOrFrozenSuffixLengthDelta + Length; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Heaps.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Heaps.cs index a77cffc3ae9a1..796dd46aa1716 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Heaps.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Heaps.cs @@ -175,10 +175,10 @@ public void SetCapacity(HeapIndex heap, int byteCount) } // internal for testing - internal int SerializeHandle(ImmutableArray map, StringHandle handle) => map[handle.GetWriterVirtualIndex()]; - internal int SerializeHandle(BlobHandle handle) => handle.GetHeapOffset(); - internal int SerializeHandle(GuidHandle handle) => handle.Index; - internal int SerializeHandle(UserStringHandle handle) => handle.GetHeapOffset(); + internal static int SerializeHandle(ImmutableArray map, StringHandle handle) => map[handle.GetWriterVirtualIndex()]; + internal static int SerializeHandle(BlobHandle handle) => handle.GetHeapOffset(); + internal static int SerializeHandle(GuidHandle handle) => handle.Index; + internal static int SerializeHandle(UserStringHandle handle) => handle.GetHeapOffset(); /// /// Adds specified blob to Blob heap, if it's not there already. diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Tables.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Tables.cs index 9339113b87a19..04062e9316aea 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Tables.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/MetadataBuilder.Tables.cs @@ -1862,7 +1862,7 @@ internal void SerializeMetadataTables( Debug.Assert(metadataSizes.MetadataTableStreamSize == endPosition - startPosition); } - private void SerializeTablesHeader(BlobBuilder writer, MetadataSizes metadataSizes) + private static void SerializeTablesHeader(BlobBuilder writer, MetadataSizes metadataSizes) { int startPosition = writer.Count; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/SignatureDecoder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/SignatureDecoder.cs index ca5b24d6e9187..8cdf85ab43e43 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/SignatureDecoder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Ecma335/SignatureDecoder.cs @@ -323,7 +323,7 @@ private TType DecodeTypeHandle(ref BlobReader blobReader, byte rawTypeKind, bool throw new BadImageFormatException(SR.NotTypeDefOrRefOrSpecHandle); } - private void CheckHeader(SignatureHeader header, SignatureKind expectedKind) + private static void CheckHeader(SignatureHeader header, SignatureKind expectedKind) { if (header.Kind != expectedKind) { @@ -331,7 +331,7 @@ private void CheckHeader(SignatureHeader header, SignatureKind expectedKind) } } - private void CheckMethodOrPropertyHeader(SignatureHeader header) + private static void CheckMethodOrPropertyHeader(SignatureHeader header) { SignatureKind kind = header.Kind; if (kind != SignatureKind.Method && kind != SignatureKind.Property) diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/BlobHeap.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/BlobHeap.cs index abd9cf514babf..efa817e70240e 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/BlobHeap.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/BlobHeap.cs @@ -158,7 +158,7 @@ internal BlobHandle GetNextHandle(BlobHandle handle) return BlobHandle.FromOffset(nextIndex); } - internal byte[] GetVirtualBlobBytes(BlobHandle handle, bool unique) + internal static byte[] GetVirtualBlobBytes(BlobHandle handle, bool unique) { BlobHandle.VirtualIndex index = handle.GetVirtualIndex(); byte[] result = s_virtualValues![(int)index]; diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/NamespaceCache.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/NamespaceCache.cs index 6aa8c6eae8dcc..30f2027290dc5 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/NamespaceCache.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/Internal/NamespaceCache.cs @@ -164,7 +164,7 @@ private void PopulateNamespaceTable() /// namespace. It has to create 'stringTable' as an intermediate dictionary, so it will hand it /// back to the caller should the caller want to use it. /// - private void MergeDuplicateNamespaces(Dictionary table, out Dictionary stringTable) + private static void MergeDuplicateNamespaces(Dictionary table, out Dictionary stringTable) { var namespaces = new Dictionary(); List>? remaps = null; @@ -227,7 +227,7 @@ private NamespaceDataBuilder SynthesizeNamespaceData(string fullName, NamespaceD /// /// Quick convenience method that handles linking together child + parent /// - private void LinkChildDataToParentData(NamespaceDataBuilder child, NamespaceDataBuilder parent) + private static void LinkChildDataToParentData(NamespaceDataBuilder child, NamespaceDataBuilder parent) { Debug.Assert(child != null && parent != null); Debug.Assert(!child.Handle.IsNil); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs index b1e1b01c64302..7c9f08054e8da 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs @@ -234,7 +234,7 @@ private MetadataKind GetMetadataKind(string versionString) /// /// Reads stream headers described in ECMA-335 24.2.2 Stream header /// - private StreamHeader[] ReadStreamHeaders(ref BlobReader memReader) + private static StreamHeader[] ReadStreamHeaders(ref BlobReader memReader) { // storage header: memReader.ReadUInt16(); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.netstandard.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.netstandard.cs index 0679b389d61af..e2c99399421f9 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.netstandard.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.netstandard.cs @@ -84,7 +84,7 @@ internal static unsafe AssemblyName GetAssemblyName(string assemblyFile!!) } } - private AssemblyNameFlags GetAssemblyNameFlags(AssemblyFlags flags) + private static AssemblyNameFlags GetAssemblyNameFlags(AssemblyFlags flags) { AssemblyNameFlags assemblyNameFlags = AssemblyNameFlags.None; @@ -103,7 +103,7 @@ private AssemblyNameFlags GetAssemblyNameFlags(AssemblyFlags flags) return assemblyNameFlags; } - private AssemblyContentType GetContentTypeFromAssemblyFlags(AssemblyFlags flags) + private static AssemblyContentType GetContentTypeFromAssemblyFlags(AssemblyFlags flags) { return (AssemblyContentType)(((int)flags & (int)AssemblyFlags.ContentTypeMask) >> 9); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/SequencePointCollection.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/SequencePointCollection.cs index 1e2699dfdf892..9312e0ac00fc1 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/SequencePointCollection.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/PortablePdb/SequencePointCollection.cs @@ -145,7 +145,7 @@ private ushort ReadColumn() return (ushort)column; } - private int AddOffsets(int value, int delta) + private static int AddOffsets(int value, int delta) { int result = unchecked(value + delta); if (result < 0) @@ -156,7 +156,7 @@ private int AddOffsets(int value, int delta) return result; } - private int AddLines(int value, int delta) + private static int AddLines(int value, int delta) { int result = unchecked(value + delta); if (result < 0 || result >= SequencePoint.HiddenLine) @@ -167,7 +167,7 @@ private int AddLines(int value, int delta) return result; } - private ushort AddColumns(ushort value, int delta) + private static ushort AddColumns(ushort value, int delta) { int result = unchecked(value + delta); if (result < 0 || result >= ushort.MaxValue) diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyReference.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyReference.cs index f621279549a54..b3b9a5bd5f68f 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyReference.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyReference.cs @@ -132,7 +132,7 @@ public CustomAttributeHandleCollection GetCustomAttributes() } #region Virtual Rows - private Version GetVirtualVersion() + private static Version GetVirtualVersion() { // currently all projected assembly references have version 4.0.0.0 return s_version_4_0_0_0; @@ -149,7 +149,7 @@ private StringHandle GetVirtualName() return StringHandle.FromVirtualIndex(GetVirtualNameIndex((AssemblyReferenceHandle.VirtualIndex)RowId)); } - private StringHandle.VirtualIndex GetVirtualNameIndex(AssemblyReferenceHandle.VirtualIndex index) + private static StringHandle.VirtualIndex GetVirtualNameIndex(AssemblyReferenceHandle.VirtualIndex index) { switch (index) { @@ -176,7 +176,7 @@ private StringHandle.VirtualIndex GetVirtualNameIndex(AssemblyReferenceHandle.Vi return 0; } - private StringHandle GetVirtualCulture() + private static StringHandle GetVirtualCulture() { return default(StringHandle); } @@ -197,7 +197,7 @@ private BlobHandle GetVirtualPublicKeyOrToken() } } - private BlobHandle GetVirtualHashValue() + private static BlobHandle GetVirtualHashValue() { return default(BlobHandle); } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodDefinition.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodDefinition.cs index b9017ecd21494..ec812439f4b38 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodDefinition.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/MethodDefinition.cs @@ -208,7 +208,7 @@ private BlobHandle GetProjectedSignature() return _reader.MethodDefTable.GetSignature(Handle); } - private int GetProjectedRelativeVirtualAddress() + private static int GetProjectedRelativeVirtualAddress() { return 0; } diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEBuilder.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEBuilder.cs index 12741bba3ed2a..7222ca86fc1d4 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEBuilder.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEBuilder.cs @@ -140,7 +140,7 @@ private ImmutableArray SerializeSections() return result.MoveToImmutable(); } - private void WritePESignature(BlobBuilder builder) + private static void WritePESignature(BlobBuilder builder) { // MS-DOS stub (128 bytes) builder.WriteBytes(s_dosHeader); @@ -327,7 +327,7 @@ private void WritePEHeader(BlobBuilder builder, PEDirectoriesBuilder directories builder.WriteUInt64(0); } - private void WriteSectionHeaders(BlobBuilder builder, ImmutableArray serializedSections) + private static void WriteSectionHeaders(BlobBuilder builder, ImmutableArray serializedSections) { foreach (var serializedSection in serializedSections) { 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 b84652be12392..795a45d6a8741 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 @@ -241,7 +241,7 @@ private bool TryCalculateCorHeaderOffset(long peStreamSize, out int startOffset) return true; } - private void SkipDosHeader(ref PEBinaryReader reader, out bool isCOFFOnly) + private static void SkipDosHeader(ref PEBinaryReader reader, out bool isCOFFOnly) { // Look for DOS Signature "MZ" ushort dosSig = reader.ReadUInt16(); diff --git a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEReader.cs b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEReader.cs index 24cc3cf5ccb97..4e5dedd718a16 100644 --- a/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEReader.cs +++ b/src/libraries/System.Reflection.Metadata/src/System/Reflection/PortableExecutable/PEReader.cs @@ -766,7 +766,7 @@ private bool TryOpenCodeViewPortablePdb(DebugDirectoryEntry codeViewEntry, strin return false; } - private bool TryOpenPortablePdbFile(string path, BlobContentId id, Func pdbFileStreamProvider, out MetadataReaderProvider? provider, ref Exception? errorToReport) + private static bool TryOpenPortablePdbFile(string path, BlobContentId id, Func pdbFileStreamProvider, out MetadataReaderProvider? provider, ref Exception? errorToReport) { provider = null; MetadataReaderProvider? candidate = null; diff --git a/src/libraries/System.Reflection.Metadata/tests/Metadata/Ecma335/MetadataBuilderTests.cs b/src/libraries/System.Reflection.Metadata/tests/Metadata/Ecma335/MetadataBuilderTests.cs index 924c061c8a787..58089ec0d573c 100644 --- a/src/libraries/System.Reflection.Metadata/tests/Metadata/Ecma335/MetadataBuilderTests.cs +++ b/src/libraries/System.Reflection.Metadata/tests/Metadata/Ecma335/MetadataBuilderTests.cs @@ -342,14 +342,14 @@ public void Heaps() var serialized = mdBuilder.GetSerializedMetadata(MetadataRootBuilder.EmptyRowCounts, 12, isStandaloneDebugMetadata: false); - Assert.Equal(0, mdBuilder.SerializeHandle(g0)); - Assert.Equal(1, mdBuilder.SerializeHandle(g1)); - Assert.Equal(0, mdBuilder.SerializeHandle(serialized.StringMap, s0)); - Assert.Equal(1, mdBuilder.SerializeHandle(serialized.StringMap, s1)); - Assert.Equal(1, mdBuilder.SerializeHandle(us0)); - Assert.Equal(3, mdBuilder.SerializeHandle(us1)); - Assert.Equal(0, mdBuilder.SerializeHandle(b0)); - Assert.Equal(1, mdBuilder.SerializeHandle(b1)); + Assert.Equal(0, MetadataBuilder.SerializeHandle(g0)); + Assert.Equal(1, MetadataBuilder.SerializeHandle(g1)); + Assert.Equal(0, MetadataBuilder.SerializeHandle(serialized.StringMap, s0)); + Assert.Equal(1, MetadataBuilder.SerializeHandle(serialized.StringMap, s1)); + Assert.Equal(1, MetadataBuilder.SerializeHandle(us0)); + Assert.Equal(3, MetadataBuilder.SerializeHandle(us1)); + Assert.Equal(0, MetadataBuilder.SerializeHandle(b0)); + Assert.Equal(1, MetadataBuilder.SerializeHandle(b1)); var heaps = new BlobBuilder(); mdBuilder.WriteHeapsTo(heaps, serialized.StringHeap); @@ -539,13 +539,13 @@ public void Heaps_StartOffsets() var serialized = mdBuilder.GetSerializedMetadata(MetadataRootBuilder.EmptyRowCounts, 12, isStandaloneDebugMetadata: false); - Assert.Equal(5, mdBuilder.SerializeHandle(g)); - Assert.Equal(0, mdBuilder.SerializeHandle(serialized.StringMap, s0)); - Assert.Equal(0x21, mdBuilder.SerializeHandle(serialized.StringMap, s1)); - Assert.Equal(0x11, mdBuilder.SerializeHandle(us0)); - Assert.Equal(0x13, mdBuilder.SerializeHandle(us1)); - Assert.Equal(0, mdBuilder.SerializeHandle(b0)); - Assert.Equal(0x31, mdBuilder.SerializeHandle(b1)); + Assert.Equal(5, MetadataBuilder.SerializeHandle(g)); + Assert.Equal(0, MetadataBuilder.SerializeHandle(serialized.StringMap, s0)); + Assert.Equal(0x21, MetadataBuilder.SerializeHandle(serialized.StringMap, s1)); + Assert.Equal(0x11, MetadataBuilder.SerializeHandle(us0)); + Assert.Equal(0x13, MetadataBuilder.SerializeHandle(us1)); + Assert.Equal(0, MetadataBuilder.SerializeHandle(b0)); + Assert.Equal(0x31, MetadataBuilder.SerializeHandle(b1)); var heaps = new BlobBuilder(); mdBuilder.WriteHeapsTo(heaps, serialized.StringHeap); diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/EventPolicies.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/EventPolicies.cs index 7af6ddf38d11d..b0013a7f6d9c7 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/EventPolicies.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/EventPolicies.cs @@ -71,7 +71,7 @@ public sealed override bool OkToIgnoreAmbiguity(EventInfo m1, EventInfo m2) return false; } - private MethodInfo? GetAccessorMethod(EventInfo e) + private static MethodInfo? GetAccessorMethod(EventInfo e) { MethodInfo? accessor = e.AddMethod; return accessor; diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/PropertyPolicies.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/PropertyPolicies.cs index 72a630110cd6e..98808e15b5ba0 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/PropertyPolicies.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/PropertyPolicies.cs @@ -81,7 +81,7 @@ public sealed override bool OkToIgnoreAmbiguity(PropertyInfo m1, PropertyInfo m2 return false; } - private MethodInfo? GetAccessorMethod(PropertyInfo property) + private static MethodInfo? GetAccessorMethod(PropertyInfo property) { MethodInfo? accessor = property.GetMethod; if (accessor == null) diff --git a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Modules/GetTypeCoreCache.cs b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Modules/GetTypeCoreCache.cs index c3a0661f9936b..af8f4f99fbe37 100644 --- a/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Modules/GetTypeCoreCache.cs +++ b/src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/TypeLoading/Modules/GetTypeCoreCache.cs @@ -170,7 +170,6 @@ private static int ComputeBucket(int hashCode, int numBuckets) [Conditional("DEBUG")] public void VerifyUnifierConsistency() { -#if DEBUG // There's a point at which this check becomes gluttonous, even by checked build standards... if (_nextFreeEntry >= 5000 && (0 != (_nextFreeEntry % 100))) return; @@ -201,7 +200,6 @@ public void VerifyUnifierConsistency() // The assertion is "<=" rather than "==" because we allow an entry to "leak" until the next resize if // a thread died between the time between we allocated the entry and the time we link it into the bucket stack. Debug.Assert(numEntriesEncountered <= _nextFreeEntry); -#endif //DEBUG } private readonly int[] _buckets; diff --git a/src/libraries/System.Resources.Writer/src/System/Resources/ResourceWriter.core.cs b/src/libraries/System.Resources.Writer/src/System/Resources/ResourceWriter.core.cs index 1bb99eb30ed9b..fe18e14e7e7e4 100644 --- a/src/libraries/System.Resources.Writer/src/System/Resources/ResourceWriter.core.cs +++ b/src/libraries/System.Resources.Writer/src/System/Resources/ResourceWriter.core.cs @@ -35,10 +35,10 @@ public void AddResourceData(string name!!, string typeName!!, byte[] serializedD AddResourceData(name, typeName, (object)serializedData); } - private string ResourceReaderTypeName { get => ResourceReaderFullyQualifiedName; } - private string ResourceSetTypeName { get => ResSetTypeName; } + private static string ResourceReaderTypeName => ResourceReaderFullyQualifiedName; + private static string ResourceSetTypeName => ResSetTypeName; - private void WriteData(BinaryWriter writer, object dataContext) + private static void WriteData(BinaryWriter writer, object dataContext) { byte[]? data = dataContext as byte[]; diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheExpires.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheExpires.cs index f9cc0fd36dadf..1e7f98f3bdd04 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheExpires.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/CacheExpires.cs @@ -784,7 +784,7 @@ internal CacheExpires(MemoryCacheStore cacheStore) } } - private int UtcCalcExpiresBucket(DateTime utcDate) + private static int UtcCalcExpiresBucket(DateTime utcDate) { long ticksFromCycleStart = utcDate.Ticks % s_tsPerCycle.Ticks; int bucket = (int)(((ticksFromCycleStart / _tsPerBucket.Ticks) + 1) % NUMBUCKETS); 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 f89fede21f848..589dd3d97f9e8 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 @@ -106,6 +106,7 @@ internal void Decrement(CounterName name) Interlocked.Decrement(ref _counterValues[idx]); } #else +#pragma warning disable CA1822 internal Counters(string cacheName) { } @@ -121,6 +122,7 @@ internal void IncrementBy(CounterName name, long value) internal void Decrement(CounterName name) { } +#pragma warning restore CA1822 #endif } } diff --git a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs index 225bbef0e6c69..408cacb1e6a1c 100644 --- a/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs +++ b/src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/MemoryCache.cs @@ -251,7 +251,7 @@ private void OnUnhandledException(object sender, UnhandledExceptionEventArgs eve } } - private void ValidatePolicy(CacheItemPolicy policy) + private static void ValidatePolicy(CacheItemPolicy policy) { if (policy.AbsoluteExpiration != ObjectCache.InfiniteAbsoluteExpiration && policy.SlidingExpiration != ObjectCache.NoSlidingExpiration) 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 b002740316335..118fe1f9c9190 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 @@ -16,10 +16,13 @@ internal sealed class SRefMultiple internal SRefMultiple(object[] targets) { } + +#pragma warning disable CA1822 internal long ApproximateSize => 0; internal void Dispose() { } +#pragma warning restore CA1822 } internal sealed class GCHandleRef : IDisposable diff --git a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/CustomTypeMarshallerAnalyzer.cs b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/CustomTypeMarshallerAnalyzer.cs index d9889c941c838..d2a7ed517689b 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/CustomTypeMarshallerAnalyzer.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/CustomTypeMarshallerAnalyzer.cs @@ -404,9 +404,9 @@ private void PrepareForAnalysis(CompilationStartAnalysisContext context) var perCompilationAnalyzer = new PerCompilationAnalyzer(spanOfT, spanOfByte, readOnlySpanOfT, readOnlySpanOfByte); // Analyze NativeMarshalling/MarshalUsing for correctness - context.RegisterSymbolAction(perCompilationAnalyzer.AnalyzeTypeDefinition, SymbolKind.NamedType); - context.RegisterSymbolAction(perCompilationAnalyzer.AnalyzeElement, SymbolKind.Parameter, SymbolKind.Field); - context.RegisterSymbolAction(perCompilationAnalyzer.AnalyzeReturnType, SymbolKind.Method); + context.RegisterSymbolAction(PerCompilationAnalyzer.AnalyzeTypeDefinition, SymbolKind.NamedType); + context.RegisterSymbolAction(PerCompilationAnalyzer.AnalyzeElement, SymbolKind.Parameter, SymbolKind.Field); + context.RegisterSymbolAction(PerCompilationAnalyzer.AnalyzeReturnType, SymbolKind.Method); // Analyze marshaller type to validate shape. context.RegisterSymbolAction(perCompilationAnalyzer.AnalyzeMarshallerType, SymbolKind.NamedType); @@ -428,7 +428,7 @@ public PerCompilationAnalyzer(INamedTypeSymbol spanOfT, INamedTypeSymbol? spanOf _readOnlySpanOfByte = readOnlySpanOfByte; } - public void AnalyzeTypeDefinition(SymbolAnalysisContext context) + public static void AnalyzeTypeDefinition(SymbolAnalysisContext context) { INamedTypeSymbol type = (INamedTypeSymbol)context.Symbol; @@ -442,7 +442,7 @@ public void AnalyzeTypeDefinition(SymbolAnalysisContext context) AnalyzeManagedTypeMarshallingInfo(context, type, attributeData, marshallerType); } - public void AnalyzeElement(SymbolAnalysisContext context) + public static void AnalyzeElement(SymbolAnalysisContext context) { ITypeSymbol managedType = context.Symbol switch { @@ -458,7 +458,7 @@ public void AnalyzeElement(SymbolAnalysisContext context) AnalyzeManagedTypeMarshallingInfo(context, managedType, attributeData, attributeData.ConstructorArguments[0].Value as INamedTypeSymbol); } - public void AnalyzeReturnType(SymbolAnalysisContext context) + public static void AnalyzeReturnType(SymbolAnalysisContext context) { IMethodSymbol method = (IMethodSymbol)context.Symbol; ITypeSymbol managedType = method.ReturnType; @@ -880,25 +880,25 @@ IPointerTypeSymbol or } } - private DiagnosticDescriptor GetInConstructorShapeRule(CustomTypeMarshallerKind kind) => kind switch + private static DiagnosticDescriptor GetInConstructorShapeRule(CustomTypeMarshallerKind kind) => kind switch { CustomTypeMarshallerKind.Value => ValueInRequiresOneParameterConstructorRule, CustomTypeMarshallerKind.LinearCollection => LinearCollectionInRequiresTwoParameterConstructorRule, _ => throw new UnreachableException() }; - private string GetInConstructorMissingMemberName(CustomTypeMarshallerKind kind) => kind switch + private static string GetInConstructorMissingMemberName(CustomTypeMarshallerKind kind) => kind switch { CustomTypeMarshallerKind.Value => MissingMemberNames.ValueManagedToNativeConstructor, CustomTypeMarshallerKind.LinearCollection => MissingMemberNames.CollectionManagedToNativeConstructor, _ => throw new UnreachableException() }; - private DiagnosticDescriptor GetCallerAllocatedBufferConstructorShapeRule(CustomTypeMarshallerKind kind) => kind switch + private static DiagnosticDescriptor GetCallerAllocatedBufferConstructorShapeRule(CustomTypeMarshallerKind kind) => kind switch { CustomTypeMarshallerKind.Value => ValueInCallerAllocatedBufferRequiresSpanConstructorRule, CustomTypeMarshallerKind.LinearCollection => LinearCollectionInCallerAllocatedBufferRequiresSpanConstructorRule, _ => throw new UnreachableException() }; - private string GetCallerAllocatedBufferConstructorMissingMemberName(CustomTypeMarshallerKind kind) => kind switch + private static string GetCallerAllocatedBufferConstructorMissingMemberName(CustomTypeMarshallerKind kind) => kind switch { CustomTypeMarshallerKind.Value => MissingMemberNames.ValueCallerAllocatedBufferConstructor, CustomTypeMarshallerKind.LinearCollection => MissingMemberNames.CollectionCallerAllocatedBufferConstructor, diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/AttributedMarshallingModelGeneratorFactory.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/AttributedMarshallingModelGeneratorFactory.cs index f3aac5de6a729..d8e685f88ae95 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/AttributedMarshallingModelGeneratorFactory.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/AttributedMarshallingModelGeneratorFactory.cs @@ -193,7 +193,7 @@ private IMarshallingGenerator CreateCustomNativeTypeMarshaller(TypePositionInfo return marshallingGenerator; } - private void ValidateCustomNativeTypeMarshallingSupported(TypePositionInfo info, StubCodeContext context, NativeMarshallingAttributeInfo marshalInfo) + private static void ValidateCustomNativeTypeMarshallingSupported(TypePositionInfo info, StubCodeContext context, NativeMarshallingAttributeInfo marshalInfo) { // The marshalling method for this type doesn't support marshalling from native to managed, // but our scenario requires marshalling from native to managed. @@ -244,7 +244,7 @@ private void ValidateCustomNativeTypeMarshallingSupported(TypePositionInfo info, } } - private ICustomNativeTypeMarshallingStrategy DecorateWithTwoStageMarshallingStrategy(NativeMarshallingAttributeInfo marshalInfo, ICustomNativeTypeMarshallingStrategy nativeTypeMarshaller) + private static ICustomNativeTypeMarshallingStrategy DecorateWithTwoStageMarshallingStrategy(NativeMarshallingAttributeInfo marshalInfo, ICustomNativeTypeMarshallingStrategy nativeTypeMarshaller) { TypeSyntax valuePropertyTypeSyntax = marshalInfo.NativeValueType!.Syntax; diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/CharMarshaller.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/CharMarshaller.cs index 0421c1d6da557..def4ae4686a0c 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/CharMarshaller.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/CharMarshaller.cs @@ -123,7 +123,7 @@ public bool UsesNativeIdentifier(TypePositionInfo info, StubCodeContext context) public bool SupportsByValueMarshalKind(ByValueContentsMarshalKind marshalKind, StubCodeContext context) => false; - private bool IsPinningPathSupported(TypePositionInfo info, StubCodeContext context) + private static bool IsPinningPathSupported(TypePositionInfo info, StubCodeContext context) { return context.SingleFrameSpansNativeContext && !info.IsManagedReturnPosition diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/ConditionalStackallocMarshallingGenerator.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/ConditionalStackallocMarshallingGenerator.cs index 970e8da3d2216..27655f3e30549 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/ConditionalStackallocMarshallingGenerator.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/ConditionalStackallocMarshallingGenerator.cs @@ -18,7 +18,7 @@ public abstract class ConditionalStackallocMarshallingGenerator : IMarshallingGe private static string GetStackAllocIdentifier(TypePositionInfo info, StubCodeContext context) => context.GetAdditionalIdentifier(info, "stackptr"); - protected bool UsesConditionalStackAlloc(TypePositionInfo info, StubCodeContext context) + protected static bool UsesConditionalStackAlloc(TypePositionInfo info, StubCodeContext context) { return context.SingleFrameSpansNativeContext && (!info.IsByRef || info.RefKind == RefKind.In) @@ -26,7 +26,7 @@ protected bool UsesConditionalStackAlloc(TypePositionInfo info, StubCodeContext && context.AdditionalTemporaryStateLivesAcrossStages; } - protected bool TryGenerateSetupSyntax(TypePositionInfo info, StubCodeContext context, out StatementSyntax statement) + protected static bool TryGenerateSetupSyntax(TypePositionInfo info, StubCodeContext context, out StatementSyntax statement) { statement = EmptyStatement(); diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/ICustomNativeTypeMarshallingStrategy.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/ICustomNativeTypeMarshallingStrategy.cs index cb617994e3b69..41fb36247c94e 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/ICustomNativeTypeMarshallingStrategy.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/ICustomNativeTypeMarshallingStrategy.cs @@ -191,7 +191,7 @@ public IEnumerable GenerateMarshalStatements(TypePositionInfo i ArgumentList()))); } - private StatementSyntax GenerateFromNativeValueInvocation(TypePositionInfo info, StubCodeContext context, CustomNativeTypeWithToFromNativeValueContext subContext) + private static StatementSyntax GenerateFromNativeValueInvocation(TypePositionInfo info, StubCodeContext context, CustomNativeTypeWithToFromNativeValueContext subContext) { // .FromNativeValue(); return ExpressionStatement( @@ -425,7 +425,7 @@ public PinnableMarshallerTypeMarshalling(ICustomNativeTypeMarshallingStrategy in _nativeValueType = nativeValueType; } - private bool CanPinMarshaller(TypePositionInfo info, StubCodeContext context) + private static bool CanPinMarshaller(TypePositionInfo info, StubCodeContext context) { return context.SingleFrameSpansNativeContext && !info.IsManagedReturnPosition && !info.IsByRef || info.RefKind == RefKind.In; } @@ -508,7 +508,7 @@ public IEnumerable GenerateSetupStatements(TypePositionInfo inf } } - private StatementSyntax GenerateFromNativeValueInvocation(TypePositionInfo info, StubCodeContext context, CustomNativeTypeWithToFromNativeValueContext subContext) + private static StatementSyntax GenerateFromNativeValueInvocation(TypePositionInfo info, StubCodeContext context, CustomNativeTypeWithToFromNativeValueContext subContext) { // .FromNativeValue(); return ExpressionStatement( diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshalAsMarshallingGeneratorFactory.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshalAsMarshallingGeneratorFactory.cs index 4355feac8a193..06d0258d23bac 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshalAsMarshallingGeneratorFactory.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshalAsMarshallingGeneratorFactory.cs @@ -118,7 +118,7 @@ public IMarshallingGenerator Create( } } - private IMarshallingGenerator CreateCharMarshaller(TypePositionInfo info, StubCodeContext context) + private static IMarshallingGenerator CreateCharMarshaller(TypePositionInfo info, StubCodeContext context) { MarshallingInfo marshalInfo = info.MarshallingAttributeInfo; if (marshalInfo is NoMarshallingInfo) @@ -157,7 +157,7 @@ private IMarshallingGenerator CreateCharMarshaller(TypePositionInfo info, StubCo throw new MarshallingNotSupportedException(info, context); } - private IMarshallingGenerator CreateStringMarshaller(TypePositionInfo info, StubCodeContext context) + private static IMarshallingGenerator CreateStringMarshaller(TypePositionInfo info, StubCodeContext context) { MarshallingInfo marshalInfo = info.MarshallingAttributeInfo; if (marshalInfo is NoMarshallingInfo) 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 bea8001a1e94f..035391be5446c 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,6 +10,7 @@ $(TargetFramework.SubString($([MSBuild]::Add($(TargetFramework.IndexOf('-')), 1)))) $(NoWarn);CS0649 + $(NoWarn);CA1822 diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs index 781c63202b4c2..900191323067e 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACE.cs @@ -1088,7 +1088,7 @@ public abstract class QualifiedAce : KnownAce #region Private Methods - private AceQualifier QualifierFromType(AceType type, out bool isCallback) + private static AceQualifier QualifierFromType(AceType type, out bool isCallback) { // // Better performance might be achieved by using a hard-coded table diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs index dabcef119438f..6651ab55b9525 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/ACL.cs @@ -1239,7 +1239,7 @@ private void Canonicalize(bool compact, bool isDacl) // This method determines whether the object type and inherited object type from the original ace // should be retained or not based on access mask and aceflags for a given split // - private void GetObjectTypesForSplit(ObjectAce originalAce, int accessMask, AceFlags aceFlags, out ObjectAceFlags objectFlags, out Guid objectType, out Guid inheritedObjectType) + private static void GetObjectTypesForSplit(ObjectAce originalAce, int accessMask, AceFlags aceFlags, out ObjectAceFlags objectFlags, out Guid objectType, out Guid inheritedObjectType) { objectFlags = 0; @@ -1267,7 +1267,7 @@ private void GetObjectTypesForSplit(ObjectAce originalAce, int accessMask, AceFl } } - private bool ObjectTypesMatch(QualifiedAce ace, QualifiedAce newAce) + private static bool ObjectTypesMatch(QualifiedAce ace, QualifiedAce newAce) { Guid objectType = (ace is ObjectAce) ? ((ObjectAce)ace).ObjectAceType : Guid.Empty; Guid newObjectType = (newAce is ObjectAce) ? ((ObjectAce)newAce).ObjectAceType : Guid.Empty; @@ -1275,7 +1275,7 @@ private bool ObjectTypesMatch(QualifiedAce ace, QualifiedAce newAce) return objectType.Equals(newObjectType); } - private bool InheritedObjectTypesMatch(QualifiedAce ace, QualifiedAce newAce) + private static bool InheritedObjectTypesMatch(QualifiedAce ace, QualifiedAce newAce) { Guid inheritedObjectType = (ace is ObjectAce) ? ((ObjectAce)ace).InheritedObjectAceType : Guid.Empty; Guid newInheritedObjectType = (newAce is ObjectAce) ? ((ObjectAce)newAce).InheritedObjectAceType : Guid.Empty; @@ -1283,7 +1283,7 @@ private bool InheritedObjectTypesMatch(QualifiedAce ace, QualifiedAce newAce) return inheritedObjectType.Equals(newInheritedObjectType); } - private bool AccessMasksAreMergeable(QualifiedAce ace, QualifiedAce newAce) + private static bool AccessMasksAreMergeable(QualifiedAce ace, QualifiedAce newAce) { // // The access masks are mergeable in any of the following conditions @@ -1309,7 +1309,7 @@ private bool AccessMasksAreMergeable(QualifiedAce ace, QualifiedAce newAce) return false; } - private bool AceFlagsAreMergeable(QualifiedAce ace, QualifiedAce newAce) + private static bool AceFlagsAreMergeable(QualifiedAce ace, QualifiedAce newAce) { // // The ace flags can be considered for merge in any of the following conditions @@ -1340,7 +1340,7 @@ private bool AceFlagsAreMergeable(QualifiedAce ace, QualifiedAce newAce) return false; } - private bool GetAccessMaskForRemoval(QualifiedAce ace, ObjectAceFlags objectFlags, Guid objectType, ref int accessMask) + private static bool GetAccessMaskForRemoval(QualifiedAce ace, ObjectAceFlags objectFlags, Guid objectType, ref int accessMask) { if ((ace.AccessMask & accessMask & ObjectAce.AccessMaskWithObjectType) != 0) { @@ -1394,7 +1394,7 @@ private bool GetAccessMaskForRemoval(QualifiedAce ace, ObjectAceFlags objectFlag } - private bool GetInheritanceFlagsForRemoval(QualifiedAce ace, ObjectAceFlags objectFlags, Guid inheritedObjectType, ref AceFlags aceFlags) + private static bool GetInheritanceFlagsForRemoval(QualifiedAce ace, ObjectAceFlags objectFlags, Guid inheritedObjectType, ref AceFlags aceFlags) { if (((ace.AceFlags & AceFlags.ContainerInherit) != 0) && ((aceFlags & AceFlags.ContainerInherit) != 0)) { @@ -1909,7 +1909,7 @@ internal RawAcl RawAcl #region Protected Methods - internal void CheckAccessType(AccessControlType accessType) + internal static void CheckAccessType(AccessControlType accessType) { if (accessType != AccessControlType.Allow && accessType != AccessControlType.Deny) diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs index 1c60bdc45dbe2..84ca62537f540 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs @@ -181,7 +181,7 @@ private AuthorizationRuleCollection GetRules(bool access, bool includeExplicit, } } - private bool AceNeedsTranslation([NotNullWhen(true)] CommonAce? ace, bool isAccessAce, bool includeExplicit, bool includeInherited) + private static bool AceNeedsTranslation([NotNullWhen(true)] CommonAce? ace, bool isAccessAce, bool includeExplicit, bool includeInherited) { if (ace == null) { diff --git a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderMap.cs b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderMap.cs index 3f596a7fb6246..798d62885910e 100644 --- a/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderMap.cs +++ b/src/libraries/System.Security.Cryptography.Cose/src/System/Security/Cryptography/Cose/CoseHeaderMap.cs @@ -117,7 +117,7 @@ private void ValidateIsReadOnly() } } - private void ValidateHeaderValue(CoseHeaderLabel label, CborReaderState? state, ReadOnlyMemory? encodedValue) + private static void ValidateHeaderValue(CoseHeaderLabel label, CborReaderState? state, ReadOnlyMemory? encodedValue) { if (state != null) { diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Encrypt.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Encrypt.cs index c5b544d8cd3cf..538a5485174c1 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Encrypt.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.Encrypt.cs @@ -146,7 +146,7 @@ private byte[] Encrypt( return PkcsHelpers.EncodeContentInfo(writer.Encode(), Oids.Pkcs7Enveloped); } - private byte[] EncryptContent( + private static byte[] EncryptContent( ContentInfo contentInfo, AlgorithmIdentifier contentEncryptionAlgorithm, out byte[] cek, diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.cs index 5d681632368f4..37ed52b63948a 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/AnyOS/ManagedPal.cs @@ -78,7 +78,7 @@ public override byte[] GetSubjectKeyIdentifier(X509Certificate2 certificate) return GetPrivateKey(certificate); } - private T? GetPrivateKey(X509Certificate2 certificate) where T : AsymmetricAlgorithm + private static T? GetPrivateKey(X509Certificate2 certificate) where T : AsymmetricAlgorithm { if (typeof(T) == typeof(RSA)) return (T?)(object?)certificate.GetRSAPrivateKey(); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.cs index a5ec578a291b7..0c988dedf8bf9 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Internal/Cryptography/Pal/Windows/PkcsPalWindows.cs @@ -101,7 +101,7 @@ public sealed override byte[] GetSubjectKeyIdentifier(X509Certificate2 certifica return GetPrivateKey(certificate, silent, preferNCrypt: false); } - private T? GetPrivateKey(X509Certificate2 certificate, bool silent, bool preferNCrypt) where T : AsymmetricAlgorithm + private static T? GetPrivateKey(X509Certificate2 certificate, bool silent, bool preferNCrypt) where T : AsymmetricAlgorithm { if (!certificate.HasPrivateKey) { diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.RSA.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.RSA.cs index 2f26c108e8087..1ac9a248d35e7 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.RSA.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.RSA.cs @@ -91,7 +91,7 @@ protected abstract RSASignaturePadding GetSignaturePadding( HashAlgorithmName digestAlgorithmName, int digestValueLength); - private protected bool SignCore( + private protected static bool SignCore( #if NETCOREAPP || NETSTANDARD2_1 ReadOnlySpan dataHash, #else diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesCcm.NotSupported.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesCcm.NotSupported.cs index 6469f5a8ad375..1b38098e975dd 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesCcm.NotSupported.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesCcm.NotSupported.cs @@ -9,6 +9,7 @@ public partial class AesCcm { public static bool IsSupported => false; +#pragma warning disable CA1822 private void ImportKey(ReadOnlySpan key) { Debug.Fail("Instance ctor should fail before we reach this point."); @@ -42,5 +43,6 @@ public void Dispose() Debug.Fail("Instance ctor should fail before we reach this point."); // no-op } +#pragma warning restore CA1822 } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesGcm.NotSupported.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesGcm.NotSupported.cs index e8a82787e8ee3..3e7c4b641397a 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesGcm.NotSupported.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AesGcm.NotSupported.cs @@ -9,6 +9,7 @@ public partial class AesGcm { public static bool IsSupported => false; +#pragma warning disable CA1822 private void ImportKey(ReadOnlySpan key) { Debug.Fail("Instance ctor should fail before we reach this point."); @@ -42,5 +43,6 @@ public void Dispose() Debug.Fail("Instance ctor should fail before we reach this point."); // no-op } +#pragma warning restore CA1822 } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AppleCCCryptorLite.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AppleCCCryptorLite.cs index f4bb6969361f8..779af66e7e705 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AppleCCCryptorLite.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AppleCCCryptorLite.cs @@ -171,7 +171,7 @@ private unsafe int CipherUpdate(ReadOnlySpan input, Span output) return bytesWritten; } - private PAL_ChainingMode GetPalChainMode(PAL_SymmetricAlgorithm algorithm, CipherMode cipherMode, int feedbackSizeInBytes) + private static PAL_ChainingMode GetPalChainMode(PAL_SymmetricAlgorithm algorithm, CipherMode cipherMode, int feedbackSizeInBytes) { return cipherMode switch { diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsnFormatter.Managed.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsnFormatter.Managed.cs index 37205d7a73b30..8ec718a407be3 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsnFormatter.Managed.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/AsnFormatter.Managed.cs @@ -30,7 +30,7 @@ internal sealed class ManagedAsnFormatter : AsnFormatter return null; } - private string? FormatSubjectAlternativeName(byte[] rawData) + private static string? FormatSubjectAlternativeName(byte[] rawData) { // Because SubjectAlternativeName is a commonly parsed structure, we'll // specifically format this one. And we'll match the OpenSSL format, which diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Base64Transforms.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Base64Transforms.cs index 6ee832397df63..126f758005f2b 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Base64Transforms.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/Base64Transforms.cs @@ -255,7 +255,7 @@ private static bool IsWhitespace(byte value) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private int GetOutputSize(int bytesToTransform, Span tmpBuffer) + private static int GetOutputSize(int bytesToTransform, Span tmpBuffer) { int outputSize = Base64.GetMaxDecodedFromUtf8Length(bytesToTransform); @@ -316,7 +316,7 @@ private void ConvertFromBase64(Span tmpBuffer, Span outputBuffer, ou ReturnToCryptoPool(transformBufferArray, transformBuffer.Length); } - private void ReturnToCryptoPool(byte[]? array, int clearSize) + private static void ReturnToCryptoPool(byte[]? array, int clearSize) { if (array != null) { diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ChaCha20Poly1305.NotSupported.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ChaCha20Poly1305.NotSupported.cs index 6e4c1536e6611..1fe190eca50eb 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ChaCha20Poly1305.NotSupported.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/ChaCha20Poly1305.NotSupported.cs @@ -9,6 +9,7 @@ public partial class ChaCha20Poly1305 { public static bool IsSupported => false; +#pragma warning disable CA1822 private void ImportKey(ReadOnlySpan key) { Debug.Fail("Instance ctor should fail before we reach this point."); @@ -42,5 +43,6 @@ public void Dispose() Debug.Fail("Instance ctor should fail before we reach this point."); // no-op } +#pragma warning restore CA1822 } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs index afbfb5500c7b0..8b65b63b6c69d 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/DSACryptoServiceProvider.Windows.cs @@ -322,7 +322,7 @@ public override DSAParameters ExportParameters(bool includePrivateParameters) /// This method helps Acquire the default CSP and avoids the need for static SafeProvHandle /// in CapiHelper class /// - private SafeProvHandle AcquireSafeProviderHandle() + private static SafeProvHandle AcquireSafeProviderHandle() { SafeProvHandle safeProvHandle; CapiHelper.AcquireCsp(new CspParameters(CapiHelper.DefaultDssProviderType), out safeProvHandle); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs index ba10764a98a22..50697f05e10b6 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RSACryptoServiceProvider.Windows.cs @@ -360,7 +360,7 @@ public override RSAParameters ExportParameters(bool includePrivateParameters) /// This method helps Acquire the default CSP and avoids the need for static SafeProvHandle /// in CapiHelper class /// - private SafeProvHandle AcquireSafeProviderHandle() + private static SafeProvHandle AcquireSafeProviderHandle() { SafeProvHandle safeProvHandle; CapiHelper.AcquireCsp(new CspParameters(CapiHelper.DefaultRsaProviderType), out safeProvHandle); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGenerator.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGenerator.cs index b6d0c097b7913..88b0afdf970a2 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGenerator.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/RandomNumberGenerator.cs @@ -163,7 +163,7 @@ public static byte[] GetBytes(int count) return ret; } - internal void VerifyGetBytes(byte[] data!!, int offset, int count) + internal static void VerifyGetBytes(byte[] data!!, int offset, int count) { if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AppleCertificatePal.ImportExport.iOS.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AppleCertificatePal.ImportExport.iOS.cs index 26fbe98478b54..d042ade14b0be 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AppleCertificatePal.ImportExport.iOS.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/AppleCertificatePal.ImportExport.iOS.cs @@ -158,9 +158,7 @@ public static ICertificatePal FromBlob( return result ?? FromDerBlob(rawData, GetDerCertContentType(rawData), password, keyStorageFlags); } - public void DisposeTempKeychain() - { - // No temporary keychain on iOS - } + // No temporary keychain on iOS + partial void DisposeTempKeychain(); } } diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateRequest.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateRequest.cs index cf72e2f6239cb..27003867981b0 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateRequest.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/CertificateRequest.cs @@ -672,7 +672,7 @@ public X509Certificate2 Create( return ret; } - private ArraySegment NormalizeSerialNumber(ReadOnlySpan serialNumber) + private static ArraySegment NormalizeSerialNumber(ReadOnlySpan serialNumber) { byte[] newSerialNumber; 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 81e9b3678b540..e52360bd27eb0 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 @@ -306,7 +306,7 @@ private static (X509Certificate2, int)[] ParseResults( return elements; } - private bool IsPolicyMatch( + private static bool IsPolicyMatch( (X509Certificate2, int)[] elements, OidCollection? applicationPolicy, OidCollection? certificatePolicy) diff --git a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate.cs b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate.cs index 6d9f3ad07d11b..23ad47853233f 100644 --- a/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate.cs +++ b/src/libraries/System.Security.Cryptography/src/System/Security/Cryptography/X509Certificates/X509Certificate.cs @@ -690,7 +690,7 @@ internal static void ValidateKeyStorageFlags(X509KeyStorageFlags keyStorageFlags } } - private void VerifyContentType(X509ContentType contentType) + private static void VerifyContentType(X509ContentType contentType) { if (!(contentType == X509ContentType.Cert || contentType == X509ContentType.SerializedCert || contentType == X509ContentType.Pkcs12)) throw new CryptographicException(SR.Cryptography_X509_InvalidContentType); diff --git a/src/libraries/System.Security.Permissions/src/System/Security/HostProtectionException.cs b/src/libraries/System.Security.Permissions/src/System/Security/HostProtectionException.cs index 19eb4b55ce944..d1c1ac56d4fdd 100644 --- a/src/libraries/System.Security.Permissions/src/System/Security/HostProtectionException.cs +++ b/src/libraries/System.Security.Permissions/src/System/Security/HostProtectionException.cs @@ -55,7 +55,7 @@ protected HostProtectionException(SerializationInfo info, StreamingContext conte public HostProtectionResource ProtectedResources { get; } - private void AppendResourceString(string resourceString, object attr, StringBuilder sb) + private static void AppendResourceString(string resourceString, object attr, StringBuilder sb) { if (attr == null) return; diff --git a/src/libraries/System.Security.Permissions/src/System/Security/Permissions/KeyContainerPermission.cs b/src/libraries/System.Security.Permissions/src/System/Security/Permissions/KeyContainerPermission.cs index c72339da8c51d..0f6a490160057 100644 --- a/src/libraries/System.Security.Permissions/src/System/Security/Permissions/KeyContainerPermission.cs +++ b/src/libraries/System.Security.Permissions/src/System/Security/Permissions/KeyContainerPermission.cs @@ -14,7 +14,6 @@ public KeyContainerPermission(KeyContainerPermissionFlags flags, KeyContainerPer public KeyContainerPermissionFlags Flags { get; } public KeyContainerPermissionAccessEntryCollection AccessEntries { get; } public bool IsUnrestricted() { return false; } - private bool IsEmpty() { return false; } public override bool IsSubsetOf(IPermission target) { return false; } public override IPermission Intersect(IPermission target) { return null; } public override IPermission Union(IPermission target) { return null; } diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs index 149119c8202c6..abd8eec43ec10 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs @@ -354,7 +354,7 @@ internal bool TryParseItemElementFrom(XmlReader reader, SyndicationItem result) return true; } - internal void WriteContentTo(XmlWriter writer, string elementName, SyndicationContent content) + internal static void WriteContentTo(XmlWriter writer, string elementName, SyndicationContent content) { if (content != null) { @@ -362,7 +362,7 @@ internal void WriteContentTo(XmlWriter writer, string elementName, SyndicationCo } } - internal void WriteElement(XmlWriter writer, string elementName, string value) + internal static void WriteElement(XmlWriter writer, string elementName, string value) { if (value != null) { @@ -388,7 +388,7 @@ internal void WriteFeedContributorsTo(XmlWriter writer, Collection } } - private string AsString(DateTimeOffset dateTime) + private static string AsString(DateTimeOffset dateTime) { if (dateTime.Offset == TimeSpan.Zero) { @@ -756,7 +756,7 @@ private void ReadXml(XmlReader reader, SyndicationFeed result) } } - private void WriteAlternateLink(XmlWriter writer, SyndicationLink link, Uri baseUri) + private static void WriteAlternateLink(XmlWriter writer, SyndicationLink link, Uri baseUri) { writer.WriteStartElement(Rss20Constants.LinkTag, Rss20Constants.Rss20Namespace); Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, link.BaseUri); @@ -928,7 +928,7 @@ private void WriteFeed(XmlWriter writer) if (SerializeExtensionsAsAtom) { - _atomSerializer.WriteElement(writer, Atom10Constants.IdTag, Feed.Id); + Atom10FeedFormatter.WriteElement(writer, Atom10Constants.IdTag, Feed.Id); // dont write out the 1st alternate link since that would have been written out anyway bool isFirstAlternateLink = true; @@ -939,7 +939,7 @@ private void WriteFeed(XmlWriter writer) isFirstAlternateLink = false; continue; } - _atomSerializer.WriteLink(writer, Feed.Links[i], Feed.BaseUri); + Atom10FeedFormatter.WriteLink(writer, Feed.Links[i], Feed.BaseUri); } } @@ -1085,7 +1085,7 @@ private void WriteItemContents(XmlWriter writer, SyndicationItem item, Uri feedB } if (SerializeExtensionsAsAtom) { - _atomSerializer.WriteLink(writer, item.Links[i], item.BaseUri); + Atom10FeedFormatter.WriteLink(writer, item.Links[i], item.BaseUri); } } @@ -1093,20 +1093,20 @@ private void WriteItemContents(XmlWriter writer, SyndicationItem item, Uri feedB { if (SerializeExtensionsAsAtom) { - _atomSerializer.WriteItemLastUpdatedTimeTo(writer, item.LastUpdatedTime); + Atom10FeedFormatter.WriteItemLastUpdatedTimeTo(writer, item.LastUpdatedTime); } } if (SerializeExtensionsAsAtom) { - _atomSerializer.WriteContentTo(writer, Atom10Constants.RightsTag, item.Copyright); + Atom10FeedFormatter.WriteContentTo(writer, Atom10Constants.RightsTag, item.Copyright); } if (!serializedContentAsDescription) { if (SerializeExtensionsAsAtom) { - _atomSerializer.WriteContentTo(writer, Atom10Constants.ContentTag, item.Content); + Atom10FeedFormatter.WriteContentTo(writer, Atom10Constants.ContentTag, item.Content); } } @@ -1121,7 +1121,7 @@ private void WriteItemContents(XmlWriter writer, SyndicationItem item, Uri feedB WriteElementExtensions(writer, item, Version); } - private void WriteMediaEnclosure(XmlWriter writer, SyndicationLink link, Uri baseUri) + private static void WriteMediaEnclosure(XmlWriter writer, SyndicationLink link, Uri baseUri) { writer.WriteStartElement(Rss20Constants.EnclosureTag, Rss20Constants.Rss20Namespace); Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, link.BaseUri); diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs index 0a8391f8916c6..eec10c931bd98 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs @@ -251,7 +251,7 @@ private SyndicationLink TryReadDocumentationFromExtension(SyndicationElementExte } } - private TimeSpan? TryReadTimeToLiveFromExtension(SyndicationElementExtensionCollection elementExtensions) + private static TimeSpan? TryReadTimeToLiveFromExtension(SyndicationElementExtensionCollection elementExtensions) { SyndicationElementExtension timeToLiveElement = elementExtensions .FirstOrDefault(e => e.OuterName == Rss20Constants.TimeToLiveTag && e.OuterNamespace == Rss20Constants.Rss20Namespace); @@ -280,7 +280,7 @@ private SyndicationLink TryReadDocumentationFromExtension(SyndicationElementExte } } - private void TryReadSkipHoursFromExtension(SyndicationElementExtensionCollection elementExtensions, Collection skipHours) + private static void TryReadSkipHoursFromExtension(SyndicationElementExtensionCollection elementExtensions, Collection skipHours) { SyndicationElementExtension skipHoursElement = elementExtensions .FirstOrDefault(e => e.OuterName == Rss20Constants.SkipHoursTag && e.OuterNamespace == Rss20Constants.Rss20Namespace); @@ -314,7 +314,7 @@ private void TryReadSkipHoursFromExtension(SyndicationElementExtensionCollection } } - private void TryReadSkipDaysFromExtension(SyndicationElementExtensionCollection elementExtensions, Collection skipDays) + private static void TryReadSkipDaysFromExtension(SyndicationElementExtensionCollection elementExtensions, Collection skipDays) { SyndicationElementExtension skipDaysElement = elementExtensions .FirstOrDefault(e => e.OuterName == Rss20Constants.SkipDaysTag && e.OuterNamespace == Rss20Constants.Rss20Namespace); @@ -350,7 +350,7 @@ private void TryReadSkipDaysFromExtension(SyndicationElementExtensionCollection private static bool IsValidDay(string day) => s_acceptedDays.Contains(day); - private SyndicationTextInput TryReadTextInputFromExtension(SyndicationElementExtensionCollection elementExtensions) + private static SyndicationTextInput TryReadTextInputFromExtension(SyndicationElementExtensionCollection elementExtensions) { SyndicationElementExtension textInputElement = elementExtensions .FirstOrDefault(e => e.OuterName == Rss20Constants.TextInputTag && e.OuterNamespace == Rss20Constants.Rss20Namespace); diff --git a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/XmlBuffer.cs b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/XmlBuffer.cs index 08f68ba039aca..0505eae102f8a 100644 --- a/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/XmlBuffer.cs +++ b/src/libraries/System.ServiceModel.Syndication/src/System/ServiceModel/XmlBuffer.cs @@ -92,7 +92,7 @@ public void Close() _stream = null; } - private Exception CreateInvalidStateException() => new InvalidOperationException(SR.XmlBufferInInvalidState); + private static Exception CreateInvalidStateException() => new InvalidOperationException(SR.XmlBufferInInvalidState); public XmlDictionaryReader GetReader(int sectionIndex) { diff --git a/src/libraries/System.Speech/src/System.Speech.csproj b/src/libraries/System.Speech/src/System.Speech.csproj index 46d903e4a7792..67cf6f7781f4b 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 + $(NoWarn);CS0649;SA1129;CA1846;CA1847;IDE0059;CA1822 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 be1e202b05779..846da4c5aa13d 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 @@ -142,7 +142,7 @@ public override unsafe void Reset() } // This version just counts the fallback and doesn't actually copy anything. - internal unsafe int InternalFallback(byte[] bytes, byte* pBytes) + 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* { diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderFallbackBufferHelper.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderFallbackBufferHelper.cs index 30a8329f34266..c38cba2d999e8 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderFallbackBufferHelper.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/EncoderFallbackBufferHelper.cs @@ -127,7 +127,7 @@ internal unsafe bool InternalFallback(char ch, ref char* chars) } // private helper methods - internal void ThrowLastCharRecursive(int charRecursive) + internal static void ThrowLastCharRecursive(int charRecursive) { // Throw it, using our complete character throw new ArgumentException(SR.Format(SR.Argument_RecursiveFallback, charRecursive), "chars"); diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/GB18030Encoding.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/GB18030Encoding.cs index 7a27288fd4ed2..d4d9f5284e8b8 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/GB18030Encoding.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/GB18030Encoding.cs @@ -360,26 +360,26 @@ public override unsafe int GetBytes(char* chars, int charCount, } // Helper methods - internal bool IsGBLeadByte(short ch) + internal static bool IsGBLeadByte(short ch) { // return true if we're in the lead byte range return ((ch) >= 0x81 && (ch) <= 0xfe); } - internal bool IsGBTwoByteTrailing(short ch) + internal static bool IsGBTwoByteTrailing(short ch) { // Return true if we are in range for the trailing byte of a 2 byte sequence return (((ch) >= 0x40 && (ch) <= 0x7e) || ((ch) >= 0x80 && (ch) <= 0xfe)); } - internal bool IsGBFourByteTrailing(short ch) + internal static bool IsGBFourByteTrailing(short ch) { // Return true if we are in range for the trailing byte of a 4 byte sequence return ((ch) >= 0x30 && (ch) <= 0x39); } - internal int GetFourBytesOffset(short offset1, short offset2, short offset3, short offset4) + internal static int GetFourBytesOffset(short offset1, short offset2, short offset3, short offset4) { return ((offset1 - 0x81) * 0x0a * 0x7e * 0x0a + (offset2 - 0x30) * 0x7e * 0x0a + diff --git a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISO2022Encoding.cs b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISO2022Encoding.cs index 84e61cb5620c4..602212497b433 100644 --- a/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISO2022Encoding.cs +++ b/src/libraries/System.Text.Encoding.CodePages/src/System/Text/ISO2022Encoding.cs @@ -1110,7 +1110,7 @@ private unsafe int GetCharsCP5022xJP(byte* bytes, int byteCount, } // We know we have an escape sequence, so check it starting with the byte after the escape - private ISO2022Modes CheckEscapeSequenceJP(byte[] bytes, int escapeCount) + private static ISO2022Modes CheckEscapeSequenceJP(byte[] bytes, int escapeCount) { // Have an escape sequence if (bytes[0] != ESCAPE) @@ -1175,7 +1175,7 @@ private ISO2022Modes CheckEscapeSequenceJP(byte[] bytes, int escapeCount) return ISO2022Modes.ModeInvalidEscape; } - private byte DecrementEscapeBytes(ref byte[] bytes, ref int count) + private static byte DecrementEscapeBytes(ref byte[] bytes, ref int count) { Debug.Assert(count > 0, "[ISO2022Encoding.DecrementEscapeBytes]count > 0"); @@ -1407,7 +1407,7 @@ private unsafe int GetCharsCP50225KR(byte* bytes, int byteCount, } // We know we have an escape sequence, so check it starting with the byte after the escape - private ISO2022Modes CheckEscapeSequenceKR(byte[] bytes, int escapeCount) + private static ISO2022Modes CheckEscapeSequenceKR(byte[] bytes, int escapeCount) { // Have an escape sequence if (bytes[0] != ESCAPE) diff --git a/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/OptimizedInboxTextEncoder.Ascii.cs b/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/OptimizedInboxTextEncoder.Ascii.cs index 2c3ff234b9247..03c0e7fc324bf 100644 --- a/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/OptimizedInboxTextEncoder.Ascii.cs +++ b/src/libraries/System.Text.Encodings.Web/src/System/Text/Encodings/Web/OptimizedInboxTextEncoder.Ascii.cs @@ -30,7 +30,9 @@ private unsafe partial struct AllowedAsciiCodePoints // This member shouldn't be accessed from browser-based code paths. // All call sites should be trimmed away, which will also trim this member // and the type hierarchy it links to. +#pragma warning disable CA1822 internal Vector128 AsVector => throw new PlatformNotSupportedException(); +#pragma warning restore CA1822 #endif #endif diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs index 6a2e6b88fc785..91351c459a5c6 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs @@ -1098,7 +1098,7 @@ private void CheckNotDisposed() } } - private void CheckExpectedType(JsonTokenType expected, JsonTokenType actual) + private static void CheckExpectedType(JsonTokenType expected, JsonTokenType actual) { if (expected != actual) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.IList.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.IList.cs index 9a97e4a69cfa5..6ea733160e139 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.IList.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonArray.IList.cs @@ -153,7 +153,7 @@ public void RemoveAt(int index) #endregion - private void DetachParent(JsonNode? item) + private static void DetachParent(JsonNode? item) { if (item != null) { diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.MultiSegment.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.MultiSegment.cs index ea4204f82ab12..6188bd4005aed 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.MultiSegment.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.MultiSegment.cs @@ -626,7 +626,7 @@ private bool CheckLiteralMultiSegment(ReadOnlySpan span, ReadOnlySpan span, ReadOnlySpan literal) + private static int FindMismatch(ReadOnlySpan span, ReadOnlySpan literal) { Debug.Assert(span.Length > 0); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.TryGet.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.TryGet.cs index cee0eee739859..f23d355a303b7 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.TryGet.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.TryGet.cs @@ -686,7 +686,7 @@ public bool TryGetByte(out byte value) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal bool TryGetByteCore(out byte value, ReadOnlySpan span) + internal static bool TryGetByteCore(out byte value, ReadOnlySpan span) { if (Utf8Parser.TryParse(span, out byte tmp, out int bytesConsumed) && span.Length == bytesConsumed) @@ -722,7 +722,7 @@ public bool TryGetSByte(out sbyte value) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal bool TryGetSByteCore(out sbyte value, ReadOnlySpan span) + internal static bool TryGetSByteCore(out sbyte value, ReadOnlySpan span) { if (Utf8Parser.TryParse(span, out sbyte tmp, out int bytesConsumed) && span.Length == bytesConsumed) @@ -757,7 +757,7 @@ public bool TryGetInt16(out short value) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal bool TryGetInt16Core(out short value, ReadOnlySpan span) + internal static bool TryGetInt16Core(out short value, ReadOnlySpan span) { if (Utf8Parser.TryParse(span, out short tmp, out int bytesConsumed) && span.Length == bytesConsumed) @@ -792,7 +792,7 @@ public bool TryGetInt32(out int value) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal bool TryGetInt32Core(out int value, ReadOnlySpan span) + internal static bool TryGetInt32Core(out int value, ReadOnlySpan span) { if (Utf8Parser.TryParse(span, out int tmp, out int bytesConsumed) && span.Length == bytesConsumed) @@ -827,7 +827,7 @@ public bool TryGetInt64(out long value) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal bool TryGetInt64Core(out long value, ReadOnlySpan span) + internal static bool TryGetInt64Core(out long value, ReadOnlySpan span) { if (Utf8Parser.TryParse(span, out long tmp, out int bytesConsumed) && span.Length == bytesConsumed) @@ -863,7 +863,7 @@ public bool TryGetUInt16(out ushort value) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal bool TryGetUInt16Core(out ushort value, ReadOnlySpan span) + internal static bool TryGetUInt16Core(out ushort value, ReadOnlySpan span) { if (Utf8Parser.TryParse(span, out ushort tmp, out int bytesConsumed) && span.Length == bytesConsumed) @@ -899,7 +899,7 @@ public bool TryGetUInt32(out uint value) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal bool TryGetUInt32Core(out uint value, ReadOnlySpan span) + internal static bool TryGetUInt32Core(out uint value, ReadOnlySpan span) { if (Utf8Parser.TryParse(span, out uint tmp, out int bytesConsumed) && span.Length == bytesConsumed) @@ -935,7 +935,7 @@ public bool TryGetUInt64(out ulong value) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal bool TryGetUInt64Core(out ulong value, ReadOnlySpan span) + internal static bool TryGetUInt64Core(out ulong value, ReadOnlySpan span) { if (Utf8Parser.TryParse(span, out ulong tmp, out int bytesConsumed) && span.Length == bytesConsumed) @@ -1030,7 +1030,7 @@ public bool TryGetDecimal(out decimal value) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal bool TryGetDecimalCore(out decimal value, ReadOnlySpan span) + internal static bool TryGetDecimalCore(out decimal value, ReadOnlySpan span) { if (Utf8Parser.TryParse(span, out decimal tmp, out int bytesConsumed) && span.Length == bytesConsumed) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Node/JsonArrayConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Node/JsonArrayConverter.cs index 9ade6e723c134..17b955cfe4fb2 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Node/JsonArrayConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Node/JsonArrayConverter.cs @@ -26,7 +26,7 @@ public override void Write(Utf8JsonWriter writer, JsonArray value, JsonSerialize } } - public JsonArray ReadList(ref Utf8JsonReader reader, JsonNodeOptions? options = null) + public static JsonArray ReadList(ref Utf8JsonReader reader, JsonNodeOptions? options = null) { JsonElement jElement = JsonElement.ParseValue(ref reader); return new JsonArray(jElement, options); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Node/JsonObjectConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Node/JsonObjectConverter.cs index b25f544d3c911..eeb62a1aa6f0f 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Node/JsonObjectConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Node/JsonObjectConverter.cs @@ -50,7 +50,7 @@ public override void Write(Utf8JsonWriter writer, JsonObject value, JsonSerializ } } - public JsonObject ReadObject(ref Utf8JsonReader reader, JsonNodeOptions? options) + public static JsonObject ReadObject(ref Utf8JsonReader reader, JsonNodeOptions? options) { JsonElement jElement = JsonElement.ParseValue(ref reader); JsonObject jObject = new JsonObject(jElement, options); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectConverterFactory.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectConverterFactory.cs index 346f83ba2b64d..52dc1c6dd9800 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectConverterFactory.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectConverterFactory.cs @@ -99,7 +99,7 @@ public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializer return converter; } - private JsonConverter CreateKeyValuePairConverter(Type type) + private static JsonConverter CreateKeyValuePairConverter(Type type) { Debug.Assert(type.IsKeyValuePair()); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.Small.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.Small.cs index 60614db83bb1b..9c36490f4adfb 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.Small.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Object/ObjectWithParameterizedConstructorConverter.Small.cs @@ -53,7 +53,7 @@ protected override bool ReadAndCacheConstructorArgument( return success; } - private bool TryRead( + private static bool TryRead( ref ReadStack state, ref Utf8JsonReader reader, JsonParameterInfo jsonParameterInfo, 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 6e08550d1b31f..661d224e1785a 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 @@ -380,7 +380,7 @@ private bool HandleConstructorArgumentWithContinuation( } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private bool HandlePropertyWithContinuation( + private static bool HandlePropertyWithContinuation( ref ReadStack state, ref Utf8JsonReader reader, JsonPropertyInfo jsonPropertyInfo) diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.cs index 3a48b99021724..7a83e19244cd9 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonConverter.cs @@ -94,7 +94,7 @@ internal virtual void ReadElementAndSetProperty( internal abstract object? ReadCoreAsObject(ref Utf8JsonReader reader, JsonSerializerOptions options, ref ReadStack state); - internal bool ShouldFlush(Utf8JsonWriter writer, ref WriteStack state) + internal static bool ShouldFlush(Utf8JsonWriter writer, ref WriteStack state) { // If surpassed flush threshold then return false which will flush stream. return (state.FlushThreshold > 0 && writer.BytesPending > state.FlushThreshold); diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/FSharpCoreReflectionProxy.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/FSharpCoreReflectionProxy.cs index a201c4b2fd971..6962bd011d926 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/FSharpCoreReflectionProxy.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/FSharpCoreReflectionProxy.cs @@ -217,7 +217,7 @@ private SourceConstructFlags GetSourceConstructFlags(Attribute compilationMappin private static TDelegate CreateDelegate(MethodInfo methodInfo) where TDelegate : Delegate => (TDelegate)Delegate.CreateDelegate(typeof(TDelegate), methodInfo, throwOnBindFailure: true)!; - private TMemberInfo EnsureMemberExists(TMemberInfo? memberInfo, string memberName) where TMemberInfo : MemberInfo + private static TMemberInfo EnsureMemberExists(TMemberInfo? memberInfo, string memberName) where TMemberInfo : MemberInfo { if (memberInfo is null) { diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs index b4a4cd03919b8..b3dfa8d120c27 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs @@ -28,9 +28,9 @@ internal abstract class RegexCompiler private static readonly MethodInfo s_isMatchedMethod = RegexRunnerMethod("IsMatched"); private static readonly MethodInfo s_matchLengthMethod = RegexRunnerMethod("MatchLength"); private static readonly MethodInfo s_matchIndexMethod = RegexRunnerMethod("MatchIndex"); - private static readonly MethodInfo s_isBoundaryMethod = typeof(RegexRunner).GetMethod("IsBoundary", BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(ReadOnlySpan), typeof(int) })!; + private static readonly MethodInfo s_isBoundaryMethod = typeof(RegexRunner).GetMethod("IsBoundary", BindingFlags.NonPublic | BindingFlags.Static, new[] { typeof(ReadOnlySpan), typeof(int) })!; private static readonly MethodInfo s_isWordCharMethod = RegexRunnerMethod("IsWordChar"); - private static readonly MethodInfo s_isECMABoundaryMethod = typeof(RegexRunner).GetMethod("IsECMABoundary", BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(ReadOnlySpan), typeof(int) })!; + private static readonly MethodInfo s_isECMABoundaryMethod = typeof(RegexRunner).GetMethod("IsECMABoundary", BindingFlags.NonPublic | BindingFlags.Static, new[] { typeof(ReadOnlySpan), typeof(int) })!; private static readonly MethodInfo s_crawlposMethod = RegexRunnerMethod("Crawlpos"); private static readonly MethodInfo s_charInClassMethod = RegexRunnerMethod("CharInClass"); private static readonly MethodInfo s_checkTimeoutMethod = RegexRunnerMethod("CheckTimeout"); @@ -2717,7 +2717,6 @@ void EmitBoundary(RegexNode node) } // if (!IsBoundary(inputSpan, pos + sliceStaticPos)) goto doneLabel; - Ldthis(); Ldloc(inputSpan); Ldloc(pos); if (sliceStaticPos > 0) diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexRunner.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexRunner.cs index bd25addf504df..bd92699835de4 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexRunner.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexRunner.cs @@ -408,7 +408,7 @@ protected bool IsBoundary(int index, int startpos, int endpos) (index < endpos && RegexCharClass.IsBoundaryWordChar(runtext![index])); } - internal bool IsBoundary(ReadOnlySpan inputSpan, int index) + internal static bool IsBoundary(ReadOnlySpan inputSpan, int index) { int indexM1 = index - 1; return ((uint)indexM1 < (uint)inputSpan.Length && RegexCharClass.IsBoundaryWordChar(inputSpan[indexM1])) != @@ -424,7 +424,7 @@ protected bool IsECMABoundary(int index, int startpos, int endpos) (index < endpos && RegexCharClass.IsECMAWordChar(runtext![index])); } - internal bool IsECMABoundary(ReadOnlySpan inputSpan, int index) + internal static bool IsECMABoundary(ReadOnlySpan inputSpan, int index) { int indexM1 = index - 1; return ((uint)indexM1 < (uint)inputSpan.Length && RegexCharClass.IsECMAWordChar(inputSpan[indexM1])) != diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/BDDRangeConverter.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/BDDRangeConverter.cs index d6ff1d2b6aa30..f882a63ffd1d5 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/BDDRangeConverter.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/BDDRangeConverter.cs @@ -33,7 +33,7 @@ public static (uint, uint)[] ToRanges(BDD set, int maxBit) return new[] { (0u, ((uint)1 << maxBit << 1) - 1) }; //note: maxBit could be 31 var rc = new BDDRangeConverter(); - return rc.LiftRanges(maxBit + 1, maxBit - set.Ordinal, rc.ToRangesFromOrdinal(set)); + return LiftRanges(maxBit + 1, maxBit - set.Ordinal, rc.ToRangesFromOrdinal(set)); } /// @@ -43,7 +43,7 @@ public static (uint, uint)[] ToRanges(BDD set, int maxBit) /// then res = {[0000 1010, 0000 1110], [0001 1010, 0001 1110], /// [0010 1010, 0010 1110], [0011 1010, 0011 1110]}, /// - private (uint, uint)[] LiftRanges(int toBits, int newBits, (uint, uint)[] ranges) + private static (uint, uint)[] LiftRanges(int toBits, int newBits, (uint, uint)[] ranges) { // nothing happens if no new bits are added if (newBits == 0) diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/CharSetSolver.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/CharSetSolver.cs index 2bdd6adea2717..80e0932c79915 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/CharSetSolver.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/CharSetSolver.cs @@ -111,7 +111,7 @@ internal BDD CreateBddForIntRanges(List ranges) /// /// Convert the set into an equivalent array of ranges. The ranges are nonoverlapping and ordered. /// - public (uint, uint)[] ToRanges(BDD set) => BDDRangeConverter.ToRanges(set, 15); + public static (uint, uint)[] ToRanges(BDD set) => BDDRangeConverter.ToRanges(set, 15); public BDD ConvertToCharSet(BDD pred) => pred; @@ -269,7 +269,7 @@ public string PrettyPrint(BDD pred) return ranges_repr.Length <= ranges_compl_repr.Length ? ranges_repr : ranges_compl_repr; } - private string RepresentSet(BDD set) => + private static string RepresentSet(BDD set) => set.IsEmpty ? "" : RepresentRanges(ToRanges(set)); private static string RepresentRanges((uint, uint)[] ranges, bool checkSingletonComlement = true) diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicNFA.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicNFA.cs index 8e168a9695f2c..e2cac9fbb8630 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicNFA.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicNFA.cs @@ -164,7 +164,7 @@ public IEnumerable EnumerateTargetStates(int sourceState, S input, uint con /// /// TODO: Explore an unexplored state on transition further. /// - public void ExploreState(int state) => new NotImplementedException(); + public static void ExploreState(int state) => new NotImplementedException(); public static SymbolicNFA Explore(SymbolicRegexNode root, int bound) { diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexBuilder.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexBuilder.cs index 25d1fe7d02db9..94e1c7e76b727 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexBuilder.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexBuilder.cs @@ -291,7 +291,7 @@ internal SymbolicRegexNode CreateConcat(SymbolicRegexNode[] internal SymbolicRegexNode CreateConcat(SymbolicRegexNode left, SymbolicRegexNode right) => SymbolicRegexNode.CreateConcat(this, left, right); - private int CalculateFixedLength(SymbolicRegexNode[] nodes) + private static int CalculateFixedLength(SymbolicRegexNode[] nodes) { int length = 0; foreach (SymbolicRegexNode node in nodes) diff --git a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexSampler.cs b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexSampler.cs index e2d627355b35d..e1149d513908e 100644 --- a/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexSampler.cs +++ b/src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Symbolic/SymbolicRegexSampler.cs @@ -157,7 +157,7 @@ public IEnumerable GenerateRandomMembers(int k) } } - private IEnumerable> Step(List> states, S pred, uint context) + private static IEnumerable> Step(List> states, S pred, uint context) { HashSet> seen = new(); foreach (SymbolicRegexNode state in states) @@ -188,13 +188,13 @@ private char ChooseChar(BDD bdd) Debug.Assert(!bdd.IsEmpty); // Select characters from the visible ASCII range whenever possible BDD bdd1 = CharSetSolver.Instance.And(bdd, _ascii); - return ChooseChar(Choose(CharSetSolver.Instance.ToRanges(bdd1.IsEmpty ? bdd : bdd1))); + return ChooseChar(Choose(CharSetSolver.ToRanges(bdd1.IsEmpty ? bdd : bdd1))); } private bool ChooseRandomlyTrueOrFalse() => _random.Next(100) < 50; /// Returns true if some state is unconditionally final - private bool IsFinal(List> states) + private static bool IsFinal(List> states) { foreach (SymbolicRegexNode state in states) { @@ -207,7 +207,7 @@ private bool IsFinal(List> states) } /// Returns true if some state is final in the given context - private bool IsFinal(List> states, uint context) + private static bool IsFinal(List> states, uint context) { foreach (SymbolicRegexNode state in states) { @@ -220,7 +220,7 @@ private bool IsFinal(List> states, uint context) } /// Returns true if some state can be final - private bool CanBeFinal(List> states) + private static bool CanBeFinal(List> states) { foreach (SymbolicRegexNode state in states) { diff --git a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/AsyncOperation.netcoreapp.cs b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/AsyncOperation.netcoreapp.cs index 85ed3d886f336..8c2e512f8be3c 100644 --- a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/AsyncOperation.netcoreapp.cs +++ b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/AsyncOperation.netcoreapp.cs @@ -10,7 +10,7 @@ internal partial class AsyncOperation : IThreadPoolWorkItem private void UnsafeQueueSetCompletionAndInvokeContinuation() => ThreadPool.UnsafeQueueUserWorkItem(this, preferLocal: false); - private void UnsafeQueueUserWorkItem(Action action, object? state) => + private static void UnsafeQueueUserWorkItem(Action action, object? state) => ThreadPool.UnsafeQueueUserWorkItem(action, state, preferLocal: false); private static void QueueUserWorkItem(Action action, object? state) => diff --git a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/AsyncOperation.netstandard.cs b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/AsyncOperation.netstandard.cs index 99693d8defcca..276616efb4a25 100644 --- a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/AsyncOperation.netstandard.cs +++ b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/AsyncOperation.netstandard.cs @@ -10,7 +10,7 @@ internal partial class AsyncOperation private void UnsafeQueueSetCompletionAndInvokeContinuation() => ThreadPool.UnsafeQueueUserWorkItem(static s => ((AsyncOperation)s).SetCompletionAndInvokeContinuation(), this); - private void UnsafeQueueUserWorkItem(Action action, object? state) => + private static void UnsafeQueueUserWorkItem(Action action, object? state) => QueueUserWorkItem(action, state); private static void QueueUserWorkItem(Action action, object? state) => diff --git a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/UnboundedChannel.cs b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/UnboundedChannel.cs index 62c7a86f177a1..2485cba6bcab3 100644 --- a/src/libraries/System.Threading.Channels/src/System/Threading/Channels/UnboundedChannel.cs +++ b/src/libraries/System.Threading.Channels/src/System/Threading/Channels/UnboundedChannel.cs @@ -128,7 +128,7 @@ public override bool TryRead([MaybeNullWhen(false)] out T item) public override bool TryPeek([MaybeNullWhen(false)] out T item) => _parent._items.TryPeek(out item); - private void CompleteIfDone(UnboundedChannel parent) + private static void CompleteIfDone(UnboundedChannel parent) { if (parent._doneWriting != null && parent._items.IsEmpty) { diff --git a/src/libraries/System.Threading/src/System/Threading/Barrier.cs b/src/libraries/System.Threading/src/System/Threading/Barrier.cs index 5e1f6ff96f104..0e4df8e52b0cb 100644 --- a/src/libraries/System.Threading/src/System/Threading/Barrier.cs +++ b/src/libraries/System.Threading/src/System/Threading/Barrier.cs @@ -243,7 +243,7 @@ public Barrier(int participantCount, Action? postPhaseAction) /// The current participant count /// The total participants count /// The sense flag - private void GetCurrentTotal(int currentTotal, out int current, out int total, out bool sense) + private static void GetCurrentTotal(int currentTotal, out int current, out int total, out bool sense) { total = (int)(currentTotal & TOTAL_MASK); current = (int)((currentTotal & CURRENT_MASK) >> 16); diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/Configuration/DefaultSettingsSection.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/Configuration/DefaultSettingsSection.cs index db262667440e2..464577f226bd7 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/Configuration/DefaultSettingsSection.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/Configuration/DefaultSettingsSection.cs @@ -10,9 +10,9 @@ internal sealed class DefaultSettingsSection // ConfigurationSection internal static DefaultSettingsSection GetSection() => s_section; - public string DistributedTransactionManagerName { get; set; } = ConfigurationStrings.DefaultDistributedTransactionManagerName; + public static string DistributedTransactionManagerName { get; set; } = ConfigurationStrings.DefaultDistributedTransactionManagerName; - public TimeSpan Timeout + public static TimeSpan Timeout { get { return s_timeout; } } diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/Configuration/MachineSettingsSection.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/Configuration/MachineSettingsSection.cs index 3e7fa1b9f9637..2989617ae2849 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/Configuration/MachineSettingsSection.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/Configuration/MachineSettingsSection.cs @@ -10,7 +10,7 @@ internal sealed class MachineSettingsSection // ConfigurationSection internal static MachineSettingsSection GetSection() => s_section; - public TimeSpan MaxTimeout + public static TimeSpan MaxTimeout { get { return s_maxTimeout; } } diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/DistributedTransaction.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/DistributedTransaction.cs index fecc85d70f984..59d7fea1829f7 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/DistributedTransaction.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/DistributedTransaction.cs @@ -9,22 +9,22 @@ internal sealed class DistributedTransactionManager { internal object? NodeName { get; set; } - internal IPromotedEnlistment ReenlistTransaction(Guid resourceManagerIdentifier, byte[] resourceManagerRecoveryInformation, RecoveringInternalEnlistment internalEnlistment) + internal static IPromotedEnlistment ReenlistTransaction(Guid resourceManagerIdentifier, byte[] resourceManagerRecoveryInformation, RecoveringInternalEnlistment internalEnlistment) { throw DistributedTransaction.NotSupported(); } - internal DistributedCommittableTransaction CreateTransaction(TransactionOptions options) + internal static DistributedCommittableTransaction CreateTransaction(TransactionOptions options) { throw DistributedTransaction.NotSupported(); } - internal void ResourceManagerRecoveryComplete(Guid resourceManagerIdentifier) + internal static void ResourceManagerRecoveryComplete(Guid resourceManagerIdentifier) { throw DistributedTransaction.NotSupported(); } - internal byte[] GetWhereabouts() + internal static byte[] GetWhereabouts() { throw DistributedTransaction.NotSupported(); } @@ -80,36 +80,32 @@ protected DistributedTransaction(SerializationInfo serializationInfo, StreamingC internal IsolationLevel IsolationLevel { get; set; } internal Transaction? SavedLtmPromotedTransaction { get; set; } - internal void Dispose() - { - } - - internal IPromotedEnlistment EnlistVolatile(InternalEnlistment internalEnlistment, EnlistmentOptions enlistmentOptions) + internal static IPromotedEnlistment EnlistVolatile(InternalEnlistment internalEnlistment, EnlistmentOptions enlistmentOptions) { throw NotSupported(); } - internal IPromotedEnlistment EnlistDurable(Guid resourceManagerIdentifier, DurableInternalEnlistment internalEnlistment, bool v, EnlistmentOptions enlistmentOptions) + internal static IPromotedEnlistment EnlistDurable(Guid resourceManagerIdentifier, DurableInternalEnlistment internalEnlistment, bool v, EnlistmentOptions enlistmentOptions) { throw NotSupported(); } - internal void Rollback() + internal static void Rollback() { throw NotSupported(); } - internal DistributedDependentTransaction DependentClone(bool v) + internal static DistributedDependentTransaction DependentClone(bool v) { throw NotSupported(); } - internal IPromotedEnlistment EnlistVolatile(VolatileDemultiplexer volatileDemux, EnlistmentOptions enlistmentOptions) + internal static IPromotedEnlistment EnlistVolatile(VolatileDemultiplexer volatileDemux, EnlistmentOptions enlistmentOptions) { throw NotSupported(); } - internal byte[] GetExportCookie(byte[] whereaboutsCopy) + internal static byte[] GetExportCookie(byte[] whereaboutsCopy) { throw NotSupported(); } @@ -119,12 +115,12 @@ public object GetRealObject(StreamingContext context) throw NotSupported(); } - internal byte[] GetTransmitterPropagationToken() + internal static byte[] GetTransmitterPropagationToken() { throw NotSupported(); } - internal IDtcTransaction GetDtcTransaction() + internal static IDtcTransaction GetDtcTransaction() { throw NotSupported(); } @@ -154,7 +150,7 @@ internal sealed class RealDistributedTransaction internal sealed class DistributedDependentTransaction : DistributedTransaction { - internal void Complete() + internal static void Complete() { throw NotSupported(); } @@ -162,7 +158,7 @@ internal void Complete() internal sealed class DistributedCommittableTransaction : DistributedTransaction { - internal void BeginCommit(InternalTransaction tx) + internal static void BeginCommit(InternalTransaction tx) { throw NotSupported(); } diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/InternalTransaction.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/InternalTransaction.cs index 56873516ed748..6503d9ea412a9 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/InternalTransaction.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/InternalTransaction.cs @@ -389,11 +389,6 @@ internal void FireCompletion() public void Dispose() { - if (_promotedTransaction != null) - { - // If there is a promoted transaction dispose it. - _promotedTransaction.Dispose(); - } } #endregion 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 e257b16257781..5634d5e109761 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionInterop.cs @@ -72,8 +72,8 @@ public static byte[] GetExportCookie(Transaction transaction!!, byte[] whereabou var whereaboutsCopy = new byte[whereabouts.Length]; Buffer.BlockCopy(whereabouts, 0, whereaboutsCopy, 0, whereabouts.Length); - DistributedTransaction dTx = ConvertToDistributedTransaction(transaction); - byte[] cookie = dTx.GetExportCookie(whereaboutsCopy); + ConvertToDistributedTransaction(transaction); + byte[] cookie = DistributedTransaction.GetExportCookie(whereaboutsCopy); if (etwLog.IsEnabled()) { @@ -143,8 +143,8 @@ public static byte[] GetTransmitterPropagationToken(Transaction transaction) etwLog.MethodEnter(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetTransmitterPropagationToken"); } - DistributedTransaction dTx = ConvertToDistributedTransaction(transaction); - byte[] token = dTx.GetTransmitterPropagationToken(); + ConvertToDistributedTransaction(transaction); + byte[] token = DistributedTransaction.GetTransmitterPropagationToken(); if (etwLog.IsEnabled()) { @@ -209,8 +209,8 @@ public static IDtcTransaction GetDtcTransaction(Transaction transaction) etwLog.MethodEnter(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetDtcTransaction"); } - DistributedTransaction dTx = ConvertToDistributedTransaction(transaction); - IDtcTransaction transactionNative = dTx.GetDtcTransaction(); + ConvertToDistributedTransaction(transaction); + IDtcTransaction transactionNative = DistributedTransaction.GetDtcTransaction(); if (etwLog.IsEnabled()) { @@ -245,8 +245,7 @@ public static byte[] GetWhereabouts() etwLog.MethodEnter(TraceSourceType.TraceSourceDistributed, "TransactionInterop.GetWhereabouts"); } - DistributedTransactionManager dTm = TransactionManager.DistributedTransactionManager; - byte[] returnValue = dTm.GetWhereabouts(); + byte[] returnValue = DistributedTransactionManager.GetWhereabouts(); if (etwLog.IsEnabled()) { diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs index 456c7f9fe82bd..3bbca6b204f1c 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionManager.cs @@ -155,7 +155,7 @@ public static Enlistment Reenlist( // Put the recovery information into a stream. MemoryStream stream = new MemoryStream(recoveryInformation); int recoveryInformationVersion; - string? nodeName = null; + string? nodeName; byte[]? resourceManagerRecoveryInformation = null; try @@ -200,15 +200,13 @@ public static Enlistment Reenlist( stream.Dispose(); } - DistributedTransactionManager transactionManager = CheckTransactionManager(nodeName); - // Now ask the Transaction Manager to reenlist. object syncRoot = new object(); Enlistment returnValue = new Enlistment(enlistmentNotification, syncRoot); EnlistmentState.EnlistmentStatePromoted.EnterState(returnValue.InternalEnlistment); returnValue.InternalEnlistment.PromotedEnlistment = - transactionManager.ReenlistTransaction( + DistributedTransactionManager.ReenlistTransaction( resourceManagerIdentifier, resourceManagerRecoveryInformation, (RecoveringInternalEnlistment)returnValue.InternalEnlistment @@ -322,9 +320,9 @@ public static TimeSpan DefaultTimeout if (!s_defaultTimeoutValidated) { - s_defaultTimeout = ValidateTimeout(DefaultSettings.Timeout); + s_defaultTimeout = ValidateTimeout(DefaultSettingsSection.Timeout); // If the timeout value got adjusted, it must have been greater than MaximumTimeout. - if (s_defaultTimeout != DefaultSettings.Timeout) + if (s_defaultTimeout != DefaultSettingsSection.Timeout) { if (etwLog.IsEnabled()) { @@ -355,7 +353,7 @@ public static TimeSpan MaximumTimeout etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "TransactionManager.get_DefaultMaximumTimeout"); } - LazyInitializer.EnsureInitialized(ref s_maximumTimeout, ref s_cachedMaxTimeout, ref s_classSyncObject, () => MachineSettings.MaxTimeout); + LazyInitializer.EnsureInitialized(ref s_maximumTimeout, ref s_cachedMaxTimeout, ref s_classSyncObject, () => DefaultSettingsSection.Timeout); if (etwLog.IsEnabled()) { @@ -451,7 +449,6 @@ internal static Transaction FindOrCreatePromotedTransaction(Guid transactionIden if (null != tx) { // If we found a transaction then dispose it - dtx.Dispose(); return tx.InternalClone(); } else 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 a022034d2dd72..026f9e840212c 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs @@ -1131,7 +1131,7 @@ private void RestoreCurrent() // ValidateInteropOption // // Validate a given interop Option - private void ValidateInteropOption(EnterpriseServicesInteropOption interopOption) + private static void ValidateInteropOption(EnterpriseServicesInteropOption interopOption) { if (interopOption < EnterpriseServicesInteropOption.None || interopOption > EnterpriseServicesInteropOption.Full) { @@ -1143,7 +1143,7 @@ private void ValidateInteropOption(EnterpriseServicesInteropOption interopOption // ValidateScopeTimeout // // Scope timeouts are not governed by MaxTimeout and therefore need a special validate function - private void ValidateScopeTimeout(string? paramName, TimeSpan scopeTimeout) + private static void ValidateScopeTimeout(string? paramName, TimeSpan scopeTimeout) { if (scopeTimeout < TimeSpan.Zero) { diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs index 67c53ef9a3aec..ee42f6d163d14 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionState.cs @@ -479,7 +479,7 @@ internal virtual bool IsCompleted(InternalTransaction tx) return false; } - protected void AddVolatileEnlistment(ref VolatileEnlistmentSet enlistments, Enlistment enlistment) + protected static void AddVolatileEnlistment(ref VolatileEnlistmentSet enlistments, Enlistment enlistment) { // Grow the enlistment array if necessary. if (enlistments._volatileEnlistmentCount == enlistments._volatileEnlistmentSize) @@ -1417,7 +1417,7 @@ internal override void EnterState(InternalTransaction tx) } // Remove this from the timeout list - TransactionManager.TransactionTable.Remove(tx); + TransactionTable.Remove(tx); TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) @@ -1514,7 +1514,7 @@ internal override void CheckForFinishedTransaction(InternalTransaction tx) throw CreateTransactionAbortedException(tx); } - private TransactionException CreateTransactionAbortedException(InternalTransaction tx) + private static TransactionException CreateTransactionAbortedException(InternalTransaction tx) { return TransactionAbortedException.Create(SR.TransactionAborted, tx._innerException, tx.DistributedTxId); } @@ -1548,7 +1548,7 @@ internal override void EnterState(InternalTransaction tx) } // Remove this from the timeout list - TransactionManager.TransactionTable.Remove(tx); + TransactionTable.Remove(tx); TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) @@ -1611,7 +1611,7 @@ internal override void EnterState(InternalTransaction tx) } // Remove this from the timeout list - TransactionManager.TransactionTable.Remove(tx); + TransactionTable.Remove(tx); TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) @@ -1697,7 +1697,7 @@ Transaction atomicTransaction EnlistmentState.EnlistmentStatePromoted.EnterState(en.InternalEnlistment); en.InternalEnlistment.PromotedEnlistment = - tx.PromotedTransaction.EnlistVolatile( + DistributedTransaction.EnlistVolatile( en.InternalEnlistment, enlistmentOptions); return en; } @@ -1726,7 +1726,7 @@ Transaction atomicTransaction EnlistmentState.EnlistmentStatePromoted.EnterState(en.InternalEnlistment); en.InternalEnlistment.PromotedEnlistment = - tx.PromotedTransaction.EnlistVolatile( + DistributedTransaction.EnlistVolatile( en.InternalEnlistment, enlistmentOptions); return en; } @@ -1763,7 +1763,7 @@ Transaction atomicTransaction EnlistmentState.EnlistmentStatePromoted.EnterState(en.InternalEnlistment); en.InternalEnlistment.PromotedEnlistment = - tx.PromotedTransaction.EnlistDurable( + DistributedTransaction.EnlistDurable( resourceManagerIdentifier, (DurableInternalEnlistment)en.InternalEnlistment, false, @@ -1804,7 +1804,7 @@ Transaction atomicTransaction EnlistmentState.EnlistmentStatePromoted.EnterState(en.InternalEnlistment); en.InternalEnlistment.PromotedEnlistment = - tx.PromotedTransaction.EnlistDurable( + DistributedTransaction.EnlistDurable( resourceManagerIdentifier, (DurableInternalEnlistment)en.InternalEnlistment, true, @@ -1833,7 +1833,7 @@ internal override void Rollback(InternalTransaction tx, Exception? e) Monitor.Exit(tx); try { - tx.PromotedTransaction.Rollback(); + DistributedTransaction.Rollback(); } finally { @@ -1918,20 +1918,12 @@ internal override void CompleteBlockingClone(InternalTransaction tx) Debug.Assert(tx._phase0WaveDependentCloneCount >= 0); if (tx._phase0WaveDependentCloneCount == 0) { - DistributedDependentTransaction dtx = tx._phase0WaveDependentClone!; tx._phase0WaveDependentClone = null; Monitor.Exit(tx); try { - try - { - dtx.Complete(); - } - finally - { - dtx.Dispose(); - } + DistributedDependentTransaction.Complete(); } finally { @@ -1962,20 +1954,12 @@ internal override void CompleteAbortingClone(InternalTransaction tx) { // We need to complete our dependent clone on the promoted transaction and null it out // so if we get a new one, a new one will be created on the promoted transaction. - DistributedDependentTransaction dtx = tx._abortingDependentClone!; tx._abortingDependentClone = null; Monitor.Exit(tx); try { - try - { - dtx.Complete(); - } - finally - { - dtx.Dispose(); - } + DistributedDependentTransaction.Complete(); } finally { @@ -1994,7 +1978,7 @@ internal override void CreateBlockingClone(InternalTransaction tx) if (tx._phase0WaveDependentClone == null) { Debug.Assert(tx.PromotedTransaction != null); - tx._phase0WaveDependentClone = tx.PromotedTransaction.DependentClone(true); + tx._phase0WaveDependentClone = DistributedTransaction.DependentClone(true); } tx._phase0WaveDependentCloneCount++; @@ -2016,7 +2000,7 @@ internal override void CreateAbortingClone(InternalTransaction tx) if (null == tx._abortingDependentClone) { Debug.Assert(tx.PromotedTransaction != null); - tx._abortingDependentClone = tx.PromotedTransaction.DependentClone(false); + tx._abortingDependentClone = DistributedTransaction.DependentClone(false); } tx._abortingDependentCloneCount++; } @@ -2093,7 +2077,7 @@ internal override void Timeout(InternalTransaction tx) tx._innerException = new TimeoutException(SR.TraceTransactionTimeout); } Debug.Assert(tx.PromotedTransaction != null); - tx.PromotedTransaction.Rollback(); + DistributedTransaction.Rollback(); TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; if (etwLog.IsEnabled()) @@ -2212,7 +2196,7 @@ internal override void EnterState(InternalTransaction tx) // Create a new distributed transaction. distributedTx = - TransactionManager.DistributedTransactionManager.CreateTransaction(options); + DistributedTransactionManager.CreateTransaction(options); distributedTx.SavedLtmPromotedTransaction = tx._outcomeSource; TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log; @@ -2264,7 +2248,7 @@ internal override void EnterState(InternalTransaction tx) } - protected bool PromotePhaseVolatiles( + protected static bool PromotePhaseVolatiles( InternalTransaction tx, ref VolatileEnlistmentSet volatiles, bool phase0) @@ -2283,7 +2267,7 @@ protected bool PromotePhaseVolatiles( } Debug.Assert(tx.PromotedTransaction != null); - volatiles.VolatileDemux._promotedEnlistment = tx.PromotedTransaction.EnlistVolatile(volatiles.VolatileDemux, + volatiles.VolatileDemux._promotedEnlistment = DistributedTransaction.EnlistVolatile(volatiles.VolatileDemux, phase0 ? EnlistmentOptions.EnlistDuringPrepareRequired : EnlistmentOptions.None); } @@ -2299,7 +2283,7 @@ internal virtual bool PromoteDurable(InternalTransaction tx) // Directly enlist the durable enlistment with the resource manager. InternalEnlistment enlistment = tx._durableEnlistment; Debug.Assert(tx.PromotedTransaction != null); - IPromotedEnlistment promotedEnlistment = tx.PromotedTransaction.EnlistDurable( + IPromotedEnlistment promotedEnlistment = DistributedTransaction.EnlistDurable( enlistment.ResourceManagerIdentifier, (DurableInternalEnlistment)enlistment, enlistment.SinglePhaseNotification != null, @@ -2349,7 +2333,7 @@ internal virtual void PromoteEnlistmentsAndOutcome(InternalTransaction tx) { if (!enlistmentsPromoted) { - tx.PromotedTransaction.Rollback(); + DistributedTransaction.Rollback(); // Now abort this transaction. tx.State.ChangeStateAbortedDuringPromotion(tx); @@ -2378,7 +2362,7 @@ internal virtual void PromoteEnlistmentsAndOutcome(InternalTransaction tx) { if (!enlistmentsPromoted) { - tx.PromotedTransaction.Rollback(); + DistributedTransaction.Rollback(); // Now abort this transaction. tx.State.ChangeStateAbortedDuringPromotion(tx); @@ -2408,7 +2392,7 @@ internal virtual void PromoteEnlistmentsAndOutcome(InternalTransaction tx) { if (!enlistmentsPromoted) { - tx.PromotedTransaction.Rollback(); + DistributedTransaction.Rollback(); // Now abort this transaction. tx.State.ChangeStateAbortedDuringPromotion(tx); @@ -2499,8 +2483,7 @@ internal override void EnterState(InternalTransaction tx) CommonEnterState(tx); // Use the asynchronous commit provided by the promoted transaction - var ctx = (DistributedCommittableTransaction)tx.PromotedTransaction!; - ctx.BeginCommit(tx); + DistributedCommittableTransaction.BeginCommit(tx); } @@ -2818,7 +2801,7 @@ internal override void EnterState(InternalTransaction tx) { Debug.Assert(tx.PromotedTransaction != null); // Otherwise make sure that the transaction rolls back. - tx.PromotedTransaction.Rollback(); + DistributedTransaction.Rollback(); } } @@ -2954,7 +2937,7 @@ private static void SignalCallback(object state) lock (tx) { tx.SignalAsyncCompletion(); - TransactionManager.TransactionTable.Remove(tx); + TransactionTable.Remove(tx); } } } @@ -2973,12 +2956,12 @@ internal override void EnterState(InternalTransaction tx) // Tell all the enlistments the outcome. if (tx._phase1Volatiles.VolatileDemux != null) { - tx._phase1Volatiles.VolatileDemux.BroadcastRollback(ref tx._phase1Volatiles); + VolatileDemultiplexer.BroadcastRollback(ref tx._phase1Volatiles); } if (tx._phase0Volatiles.VolatileDemux != null) { - tx._phase0Volatiles.VolatileDemux.BroadcastRollback(ref tx._phase0Volatiles); + VolatileDemultiplexer.BroadcastRollback(ref tx._phase0Volatiles); } // Fire Completion for anyone listening @@ -3117,12 +3100,12 @@ internal override void EnterState(InternalTransaction tx) // Tell all the enlistments the outcome. if (tx._phase1Volatiles.VolatileDemux != null) { - tx._phase1Volatiles.VolatileDemux.BroadcastCommitted(ref tx._phase1Volatiles); + VolatileDemultiplexer.BroadcastCommitted(ref tx._phase1Volatiles); } if (tx._phase0Volatiles.VolatileDemux != null) { - tx._phase0Volatiles.VolatileDemux.BroadcastCommitted(ref tx._phase0Volatiles); + VolatileDemultiplexer.BroadcastCommitted(ref tx._phase0Volatiles); } // Fire Completion for anyone listening @@ -3187,12 +3170,12 @@ internal override void EnterState(InternalTransaction tx) // Tell all the enlistments the outcome. if (tx._phase1Volatiles.VolatileDemux != null) { - tx._phase1Volatiles.VolatileDemux.BroadcastInDoubt(ref tx._phase1Volatiles); + VolatileDemultiplexer.BroadcastInDoubt(ref tx._phase1Volatiles); } if (tx._phase0Volatiles.VolatileDemux != null) { - tx._phase0Volatiles.VolatileDemux.BroadcastInDoubt(ref tx._phase0Volatiles); + VolatileDemultiplexer.BroadcastInDoubt(ref tx._phase0Volatiles); } // Fire Completion for anyone listening @@ -3904,7 +3887,7 @@ internal override void EnterState(InternalTransaction tx) // We are about to tell the PSPE to do the SinglePhaseCommit. It is too late for us to timeout the transaction. // Remove this from the timeout list - TransactionManager.TransactionTable.Remove(tx); + TransactionTable.Remove(tx); tx._durableEnlistment.State.ChangeStateCommitting(tx._durableEnlistment); } @@ -4365,7 +4348,7 @@ internal override void Rollback(InternalTransaction tx, Exception? e) } Debug.Assert(tx.PromotedTransaction != null); - tx.PromotedTransaction.Rollback(); + DistributedTransaction.Rollback(); TransactionStatePromotedAborted.EnterState(tx); } @@ -4549,7 +4532,6 @@ internal void Phase0PSPEInitialize( if (TransactionManager.FindPromotedTransaction(distributedTx.Identifier) != null) { // If there is already a promoted transaction then someone has committed an error. - distributedTx.Dispose(); throw TransactionException.CreateInvalidOperationException( TraceSourceType.TraceSourceLtm, SR.PromotedTransactionExists, diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionTable.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionTable.cs index a36d3836827bc..326a006f61db4 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionTable.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionTable.cs @@ -372,7 +372,7 @@ private void AddIter(InternalTransaction txNew) // Remove a transaction from the table. - internal void Remove(InternalTransaction tx) + internal static void Remove(InternalTransaction tx) { Debug.Assert(tx._tableBucket != null); tx._tableBucket.Remove(tx); diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionsEtwProvider.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionsEtwProvider.cs index 5da12d241967d..1aa565fbb2a78 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionsEtwProvider.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionsEtwProvider.cs @@ -1160,7 +1160,7 @@ public static class Keywords public const EventKeywords TraceDistributed = (EventKeywords)0x0004; } - private void SetActivityId(string str) + private static void SetActivityId(string str) { Guid guid = Guid.Empty; diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/VolatileEnlistmentMultiplexing.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/VolatileEnlistmentMultiplexing.cs index 5394b20677155..c75840c9b15d3 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/VolatileEnlistmentMultiplexing.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/VolatileEnlistmentMultiplexing.cs @@ -26,7 +26,7 @@ public VolatileDemultiplexer(InternalTransaction transaction) _transaction = transaction; } - internal void BroadcastCommitted(ref VolatileEnlistmentSet volatiles) + internal static void BroadcastCommitted(ref VolatileEnlistmentSet volatiles) { // Broadcast preprepare to the volatile subordinates for (int i = 0; i < volatiles._volatileEnlistmentCount; i++) @@ -37,7 +37,7 @@ internal void BroadcastCommitted(ref VolatileEnlistmentSet volatiles) } // This broadcast is used by the state machines and therefore must be internal. - internal void BroadcastRollback(ref VolatileEnlistmentSet volatiles) + internal static void BroadcastRollback(ref VolatileEnlistmentSet volatiles) { // Broadcast preprepare to the volatile subordinates for (int i = 0; i < volatiles._volatileEnlistmentCount; i++) @@ -47,7 +47,7 @@ internal void BroadcastRollback(ref VolatileEnlistmentSet volatiles) } } - internal void BroadcastInDoubt(ref VolatileEnlistmentSet volatiles) + internal static void BroadcastInDoubt(ref VolatileEnlistmentSet volatiles) { // Broadcast preprepare to the volatile subordinates for (int i = 0; i < volatiles._volatileEnlistmentCount; i++) diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs index ab27187ce0b82..d2385bb8eecaa 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/Emit/ModuleBuilder.Mono.cs @@ -532,7 +532,7 @@ public override Type[] GetTypes() return copy; } - internal int GetMethodToken(MethodInfo method) + internal static int GetMethodToken(MethodInfo method) { if (method == null) throw new ArgumentNullException(nameof(method)); @@ -546,7 +546,7 @@ internal int GetArrayMethodToken(Type arrayClass, string methodName, CallingConv } [ComVisible(true)] - internal int GetConstructorToken(ConstructorInfo con) + internal static int GetConstructorToken(ConstructorInfo con) { if (con == null) throw new ArgumentNullException(nameof(con)); @@ -554,7 +554,7 @@ internal int GetConstructorToken(ConstructorInfo con) return con.MetadataToken; } - internal int GetFieldToken(FieldInfo field) + internal static int GetFieldToken(FieldInfo field) { if (field == null) throw new ArgumentNullException(nameof(field)); @@ -582,7 +582,7 @@ internal int GetStringConstant(string str) return GetToken(str); } - internal int GetTypeToken(Type type) + internal static int GetTypeToken(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); diff --git a/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.Mono.cs b/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.Mono.cs index b375ae9af1248..8abf748f94b4c 100644 --- a/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.Mono.cs +++ b/src/mono/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.Mono.cs @@ -854,7 +854,7 @@ private RuntimeType[] ArgumentTypes } } - private void InvokeClassConstructor() + private static void InvokeClassConstructor() { // [TODO] Mechanism for invoking class constructor // See https://github.com/dotnet/runtime/issues/40351 diff --git a/src/mono/wasm/debugger/BrowserDebugHost/Startup.cs b/src/mono/wasm/debugger/BrowserDebugHost/Startup.cs index b4e116e81485d..e95e9a28e62db 100644 --- a/src/mono/wasm/debugger/BrowserDebugHost/Startup.cs +++ b/src/mono/wasm/debugger/BrowserDebugHost/Startup.cs @@ -34,6 +34,7 @@ public Startup(IConfiguration configuration) => public IConfiguration Configuration { get; } +#pragma warning disable CA1822 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IOptionsMonitor optionsAccessor, IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime) { @@ -56,6 +57,7 @@ public void Configure(IApplicationBuilder app, IOptionsMonitor opt .UseWebSockets() .UseDebugProxy(options); } +#pragma warning restore CA1822 } internal static class DebugExtensions diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs b/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs index 0edf43669eae1..a283bccf60188 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/DebugStore.cs @@ -1210,7 +1210,7 @@ private class DebugItem public Task Data { get; set; } } - public IEnumerable EnC(AssemblyInfo asm, byte[] meta_data, byte[] pdb_data) + public static IEnumerable EnC(AssemblyInfo asm, byte[] meta_data, byte[] pdb_data) { asm.EnC(meta_data, pdb_data); foreach (var method in asm.Methods) @@ -1365,7 +1365,7 @@ public List FindPossibleBreakpoints(SourceLocation start, Source return res; } - public IEnumerable FindBreakpointLocations(SourceLocation start, SourceLocation end, MethodInfo method) + public static IEnumerable FindBreakpointLocations(SourceLocation start, SourceLocation end, MethodInfo method) { if (!method.HasSequencePoints) yield break; diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/EvaluateExpression.cs b/src/mono/wasm/debugger/BrowserDebugProxy/EvaluateExpression.cs index 54b175b7796fa..8cf07abe24884 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/EvaluateExpression.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/EvaluateExpression.cs @@ -213,7 +213,7 @@ void AddLocalVariableWithValue(string idName, JObject value) } } - private string ConvertJSToCSharpLocalVariableAssignment(string idName, JToken variable) + private static string ConvertJSToCSharpLocalVariableAssignment(string idName, JToken variable) { string typeRet; object valueRet; diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/MonoProxy.cs b/src/mono/wasm/debugger/BrowserDebugProxy/MonoProxy.cs index b0e5961a1d14c..52f3f65cafb19 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/MonoProxy.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/MonoProxy.cs @@ -837,7 +837,7 @@ private async Task ProcessEnC(SessionId sessionId, ExecutionContext contex var assemblyName = await context.SdbAgent.GetAssemblyNameFromModule(moduleId, token); DebugStore store = await LoadStore(sessionId, token); AssemblyInfo asm = store.GetAssemblyByName(assemblyName); - foreach (var method in store.EnC(asm, meta_buf, pdb_buf)) + foreach (var method in DebugStore.EnC(asm, meta_buf, pdb_buf)) await ResetBreakpoint(sessionId, method, token); return true; } @@ -1549,7 +1549,7 @@ private static bool IsNestedMethod(DebugStore store, Frame scope, SourceLocation continue; if (method.IsLexicallyContainedInMethod(scope.Method.Info)) continue; - SourceLocation newFoundLocation = store.FindBreakpointLocations(targetLocation, targetLocation, scope.Method.Info) + SourceLocation newFoundLocation = DebugStore.FindBreakpointLocations(targetLocation, targetLocation, scope.Method.Info) .FirstOrDefault(); if (!(newFoundLocation is null)) return true; @@ -1564,7 +1564,7 @@ private async Task OnSetNextIP(MessageId sessionId, SourceLocation targetL ExecutionContext context = GetContext(sessionId); Frame scope = context.CallStack.First(); - SourceLocation foundLocation = store.FindBreakpointLocations(targetLocation, targetLocation, scope.Method.Info) + SourceLocation foundLocation = DebugStore.FindBreakpointLocations(targetLocation, targetLocation, scope.Method.Info) .FirstOrDefault(); if (foundLocation is null) diff --git a/src/mono/wasm/debugger/BrowserDebugProxy/MonoSDBHelper.cs b/src/mono/wasm/debugger/BrowserDebugProxy/MonoSDBHelper.cs index be8a074b35ec7..82d81aa0d28b9 100644 --- a/src/mono/wasm/debugger/BrowserDebugProxy/MonoSDBHelper.cs +++ b/src/mono/wasm/debugger/BrowserDebugProxy/MonoSDBHelper.cs @@ -909,7 +909,7 @@ public async Task EnableReceiveRequests(EventKind eventKind, CancellationT internal async Task SendDebuggerAgentCommand(T command, MonoBinaryWriter arguments, CancellationToken token) => MonoBinaryReader.From (await proxy.SendMonoCommand(sessionId, MonoCommands.SendDebuggerAgentCommand(proxy.RuntimeId, GetNewId(), (int)GetCommandSetForCommand(command), (int)(object)command, arguments?.ToBase64().data ?? string.Empty), token)); - internal CommandSet GetCommandSetForCommand(T command) => + private static CommandSet GetCommandSetForCommand(T command) => command switch { CmdVM => CommandSet.Vm, CmdObject => CommandSet.ObjectRef, @@ -1311,7 +1311,7 @@ public async Task> GetTypeFields(int typeId, CancellationTo return ret; } - public string ReplaceCommonClassNames(string className) => + private static string ReplaceCommonClassNames(string className) => new StringBuilder(className) .Replace("System.String", "string") .Replace("System.Boolean", "bool") @@ -1707,7 +1707,7 @@ public async Task GetPropertiesValuesOfValueType(int valueTypeId, Cancel return ret; } - public bool AutoExpandable(string className) { + private static bool AutoExpandable(string className) { if (className == "System.DateTime" || className == "System.DateTimeOffset" || className == "System.TimeSpan") @@ -1715,7 +1715,7 @@ public bool AutoExpandable(string className) { return false; } - public bool AutoInvokeToString(string className) { + private static bool AutoInvokeToString(string className) { if (className == "System.DateTime" || className == "System.DateTimeOffset" || className == "System.TimeSpan" || @@ -1725,7 +1725,7 @@ public bool AutoInvokeToString(string className) { return false; } - public JObject CreateJObject(T value, string type, string description, bool writable, string className = null, string objectId = null, string __custom_type = null, string subtype = null, bool isValueType = false, bool expanded = false, bool isEnum = false) + private static JObject CreateJObject(T value, string type, string description, bool writable, string className = null, string objectId = null, string __custom_type = null, string subtype = null, bool isValueType = false, bool expanded = false, bool isEnum = false) { var ret = JObject.FromObject(new { value = new @@ -1753,17 +1753,18 @@ public JObject CreateJObject(T value, string type, string description, bool w return ret; } - public JObject CreateJObjectForBoolean(int value) + + private static JObject CreateJObjectForBoolean(int value) { return CreateJObject(value == 0 ? false : true, "boolean", value == 0 ? "false" : "true", true); } - public JObject CreateJObjectForNumber(T value) + private static JObject CreateJObjectForNumber(T value) { return CreateJObject(value, "number", value.ToString(), true); } - public JObject CreateJObjectForChar(int value) + private static JObject CreateJObjectForChar(int value) { char charValue = Convert.ToChar(value); var description = $"{value} '{charValue}'"; @@ -2086,7 +2087,7 @@ public async Task IsAsyncMethod(int methodId, CancellationToken token) return methodInfo.Info.IsAsync == 1; } - private bool IsClosureReferenceField (string fieldName) + private static bool IsClosureReferenceField (string fieldName) { // mcs is "$locvar" // old mcs is "<>f__ref" diff --git a/src/tasks/AotCompilerTask/MonoAOTCompiler.cs b/src/tasks/AotCompilerTask/MonoAOTCompiler.cs index b428348beb5ee..6e6d75248cfed 100644 --- a/src/tasks/AotCompilerTask/MonoAOTCompiler.cs +++ b/src/tasks/AotCompilerTask/MonoAOTCompiler.cs @@ -440,7 +440,7 @@ private bool ExecuteInternal() return !Log.HasLoggedErrors; } - private bool CheckAllUpToDate(IList argsList) + private static bool CheckAllUpToDate(IList argsList) { foreach (var args in argsList) { diff --git a/src/tasks/MonoTargetsTasks/RuntimeConfigParser/RuntimeConfigParser.cs b/src/tasks/MonoTargetsTasks/RuntimeConfigParser/RuntimeConfigParser.cs index f82708c742649..f77f6f604fab9 100644 --- a/src/tasks/MonoTargetsTasks/RuntimeConfigParser/RuntimeConfigParser.cs +++ b/src/tasks/MonoTargetsTasks/RuntimeConfigParser/RuntimeConfigParser.cs @@ -106,7 +106,7 @@ private bool TryConvertInputToDictionary(string inputFilePath, [NotNullWhen(true /// Just write the dictionary out to a blob as a count followed by /// a length-prefixed UTF8 encoding of each key and value - private void ConvertDictionaryToBlob(IReadOnlyDictionary properties, BlobBuilder builder) + private static void ConvertDictionaryToBlob(IReadOnlyDictionary properties, BlobBuilder builder) { int count = properties.Count; diff --git a/src/tasks/WasmAppBuilder/PInvokeTableGenerator.cs b/src/tasks/WasmAppBuilder/PInvokeTableGenerator.cs index 34b42e2db3ad6..2d4ca8ee0c07f 100644 --- a/src/tasks/WasmAppBuilder/PInvokeTableGenerator.cs +++ b/src/tasks/WasmAppBuilder/PInvokeTableGenerator.cs @@ -270,7 +270,7 @@ private static string SymbolNameForMethod(MethodInfo method) return FixupSymbolName(sb.ToString()); } - private string MapType (Type t) + private static string MapType (Type t) { string name = t.Name; if (name == "Void") @@ -341,7 +341,7 @@ private static bool TryIsMethodGetParametersUnsupported(MethodInfo method, [NotN return sb.ToString(); } - private void EmitNativeToInterp(StreamWriter w, List callbacks) + private static void EmitNativeToInterp(StreamWriter w, List callbacks) { // Generate native->interp entry functions // These are called by native code, so they need to obtain