diff --git a/src/coreclr/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs index 7fbb594a1844de..f604f951911121 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Attribute.CoreCLR.cs @@ -301,7 +301,7 @@ private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, count = 0; for (int i = 0; i < objAttr.Length; i++) { - if (objAttr[i] is object attr) + if (objAttr[i] is { } attr) { attributes[count] = (Attribute)attr; count++; diff --git a/src/coreclr/System.Private.CoreLib/src/System/MulticastDelegate.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/MulticastDelegate.CoreCLR.cs index 0846f7060ce38f..703fd01bbc7cf5 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/MulticastDelegate.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/MulticastDelegate.CoreCLR.cs @@ -149,7 +149,7 @@ private static bool TrySetSlot(object?[] a, int index, object o) // The slot may be already set because we have added and removed the same method before. // Optimize this case, because it's cheaper than copying the array. - if (a[index] is object ai) + if (a[index] is { } ai) { MulticastDelegate d = (MulticastDelegate)o; MulticastDelegate dd = (MulticastDelegate)ai; diff --git a/src/coreclr/System.Private.CoreLib/src/System/Runtime/ControlledExecution.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/Runtime/ControlledExecution.CoreCLR.cs index 67971b90caa1b6..2c824aa7922ce3 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/Runtime/ControlledExecution.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/Runtime/ControlledExecution.CoreCLR.cs @@ -99,7 +99,7 @@ public static void Run(Action action, CancellationToken cancellationToken) // an OperationCanceledException, preserving stack trace details from the ThreadAbortException in // order to aid in diagnostics and debugging. OperationCanceledException e = cancellationToken.IsCancellationRequested ? new(cancellationToken) : new(); - if (tae.StackTrace is string stackTrace) + if (tae.StackTrace is { } stackTrace) { ExceptionDispatchInfo.SetRemoteStackTrace(e, stackTrace); } diff --git a/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs b/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs index a1907fd90df765..0bbb1929ce9aaf 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/RuntimeHandles.cs @@ -215,7 +215,7 @@ internal static object CreateInstanceForAnotherGenericParameter( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] RuntimeType type, RuntimeType genericParameter) { - Debug.Assert(type.GetConstructor(Type.EmptyTypes) is ConstructorInfo c && c.IsPublic, + Debug.Assert(type.GetConstructor(Type.EmptyTypes) is { } c && c.IsPublic, $"CreateInstanceForAnotherGenericParameter requires {nameof(type)} to have a public parameterless constructor so it can be annotated for trimming without preserving private constructors."); object? instantiatedObject = null; @@ -239,7 +239,7 @@ internal static object CreateInstanceForAnotherGenericParameter( RuntimeType genericParameter1, RuntimeType genericParameter2) { - Debug.Assert(type.GetConstructor(Type.EmptyTypes) is ConstructorInfo c && c.IsPublic, + Debug.Assert(type.GetConstructor(Type.EmptyTypes) is { } c && c.IsPublic, $"CreateInstanceForAnotherGenericParameter requires {nameof(type)} to have a public parameterless constructor so it can be annotated for trimming without preserving private constructors."); object? instantiatedObject = null; diff --git a/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs b/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs index d1591d88036b28..2e86e9b4ca15f0 100644 --- a/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs +++ b/src/coreclr/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs @@ -2383,7 +2383,7 @@ private static bool FilterApplyMethodBase( for (int i = 0; i < parameterInfos.Length; i++) { // a null argument type implies a null arg which is always a perfect match - if (argumentTypes[i] is Type t && !t.MatchesParameterTypeExactly(parameterInfos[i])) + if (argumentTypes[i] is { } t && !t.MatchesParameterTypeExactly(parameterInfos[i])) return false; } } @@ -3899,7 +3899,7 @@ private void CreateInstanceCheckThis() Type[] argsType = args.Length != 0 ? new Type[args.Length] : EmptyTypes; for (int i = 0; i < args.Length; i++) { - if (args[i] is object arg) + if (args[i] is { } arg) { argsType[i] = arg.GetType(); } diff --git a/src/libraries/Common/src/Roslyn/GetBestTypeByMetadataName.cs b/src/libraries/Common/src/Roslyn/GetBestTypeByMetadataName.cs index e78668b97956c9..f82d6e510f1412 100644 --- a/src/libraries/Common/src/Roslyn/GetBestTypeByMetadataName.cs +++ b/src/libraries/Common/src/Roslyn/GetBestTypeByMetadataName.cs @@ -64,7 +64,7 @@ internal static class RoslynExtensions continue; } - if (type is object) + if (type is not null) { // Multiple visible types with the same metadata name are present return null; diff --git a/src/libraries/Common/src/System/Threading/Tasks/TaskToAsyncResult.cs b/src/libraries/Common/src/System/Threading/Tasks/TaskToAsyncResult.cs index 8ffe3ad042fbaf..7ea9c21137cd65 100644 --- a/src/libraries/Common/src/System/Threading/Tasks/TaskToAsyncResult.cs +++ b/src/libraries/Common/src/System/Threading/Tasks/TaskToAsyncResult.cs @@ -79,7 +79,7 @@ public static Task Unwrap(IAsyncResult asyncResult) } #endif - if ((asyncResult as TaskAsyncResult)?._task is not Task task) + if ((asyncResult as TaskAsyncResult)?._task is not { } task) { throw new ArgumentException(null, nameof(asyncResult)); } diff --git a/src/libraries/System.Private.CoreLib/gen/IntrinsicsInSystemPrivateCoreLibAnalyzer.cs b/src/libraries/System.Private.CoreLib/gen/IntrinsicsInSystemPrivateCoreLibAnalyzer.cs index f9a5eff99648cb..a33848e06bdf87 100644 --- a/src/libraries/System.Private.CoreLib/gen/IntrinsicsInSystemPrivateCoreLibAnalyzer.cs +++ b/src/libraries/System.Private.CoreLib/gen/IntrinsicsInSystemPrivateCoreLibAnalyzer.cs @@ -291,7 +291,7 @@ private static INamedTypeSymbol[][] DecomposePropertySymbolForIsSupportedGroups_ if (propertyDefiningSyntax != null) { if (propertyDefiningSyntax is PropertyDeclarationSyntax propertyDeclaration - && propertyDeclaration.ExpressionBody is ArrowExpressionClauseSyntax arrowExpression) + && propertyDeclaration.ExpressionBody is { } arrowExpression) { if (model.SyntaxTree != arrowExpression.SyntaxTree) { 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 476af77370bd66..ea222fbec476cb 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 @@ -107,7 +107,7 @@ private static SafeFileHandle Open(string path, Interop.Sys.OpenFlags flags, int return handle; } - if (createOpenException?.Invoke(error, flags, path) is Exception ex) + if (createOpenException?.Invoke(error, flags, path) is { } ex) { throw ex; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Buffers/SharedArrayPool.cs b/src/libraries/System.Private.CoreLib/src/System/Buffers/SharedArrayPool.cs index 8c6ffe9b61c463..1450242cd1e8e8 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Buffers/SharedArrayPool.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Buffers/SharedArrayPool.cs @@ -523,7 +523,7 @@ private static bool TryGetInt32EnvironmentVariable(string variable, out int resu { // Avoid globalization stack, as it might in turn be using ArrayPool. - if (Environment.GetEnvironmentVariableCore_NoArrayPool(variable) is string envVar && + if (Environment.GetEnvironmentVariableCore_NoArrayPool(variable) is { } envVar && envVar.Length is > 0 and <= 32) // arbitrary limit that allows for some spaces around the maximum length of a non-negative Int32 (10 digits) { ReadOnlySpan value = envVar.AsSpan().Trim(' '); diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs index 7090ea8919a549..e694e25419677f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/ArrayList.cs @@ -876,7 +876,7 @@ public override int IndexOf(object? value, int startIndex, int count) else { for (int i = startIndex; i < endIndex; i++) - if (_list[i] is object o && o.Equals(value)) + if (_list[i] is { } o && o.Equals(value)) return i; return -1; } @@ -944,7 +944,7 @@ public override int LastIndexOf(object? value, int startIndex, int count) else { for (int i = startIndex; i >= endIndex; i--) - if (_list[i] is object o && o.Equals(value)) + if (_list[i] is { } o && o.Equals(value)) return i; return -1; } @@ -2268,7 +2268,7 @@ public override bool Contains(object? item) else { for (int i = 0; i < _baseSize; i++) - if (_baseList[_baseIndex + i] is object o && o.Equals(item)) + if (_baseList[_baseIndex + i] is { } o && o.Equals(item)) return true; return false; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.cs index c890bbed83c7ef..17375fb12c393c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.cs @@ -70,7 +70,7 @@ public Dictionary(int capacity, IEqualityComparer? comparer) // We use a non-randomized comparer for improved perf, falling back to a randomized comparer if the // hash buckets become unbalanced. if (typeof(TKey) == typeof(string) && - NonRandomizedStringEqualityComparer.GetStringComparer(_comparer!) is IEqualityComparer stringComparer) + NonRandomizedStringEqualityComparer.GetStringComparer(_comparer!) is { } stringComparer) { _comparer = (IEqualityComparer)stringComparer; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs index 6bc713d127f3ca..a134d505703d1c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/HashSet.cs @@ -69,7 +69,7 @@ public HashSet(IEqualityComparer? comparer) // We use a non-randomized comparer for improved perf, falling back to a randomized comparer if the // hash buckets become unbalanced. if (typeof(T) == typeof(string) && - NonRandomizedStringEqualityComparer.GetStringComparer(_comparer) is IEqualityComparer stringComparer) + NonRandomizedStringEqualityComparer.GetStringComparer(_comparer) is { } stringComparer) { _comparer = (IEqualityComparer)stringComparer; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Debug.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Debug.cs index 2ec074ebbf6a4a..f8275f6fa986da 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Debug.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Debug.cs @@ -307,7 +307,7 @@ public AssertInterpolatedStringHandler(int literalLength, int formattedCount, bo /// Extracts the built string from the handler. internal string ToStringAndClear() { - string s = _stringBuilderHandler._stringBuilder is StringBuilder sb ? + string s = _stringBuilderHandler._stringBuilder is { } sb ? sb.ToString() : string.Empty; _stringBuilderHandler = default; @@ -402,7 +402,7 @@ public WriteIfInterpolatedStringHandler(int literalLength, int formattedCount, b /// Extracts the built string from the handler. internal string ToStringAndClear() { - string s = _stringBuilderHandler._stringBuilder is StringBuilder sb ? + string s = _stringBuilderHandler._stringBuilder is { } sb ? StringBuilderCache.GetStringAndRelease(sb) : string.Empty; _stringBuilderHandler = default; diff --git a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs index d280d33c6e3b5d..313c8057e9b6c7 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Diagnostics/Tracing/EventSource.cs @@ -3376,7 +3376,7 @@ private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAt if (manifest.HasResources) { string eventKey = "event_" + eventName; - if (manifest.GetLocalizedMessage(eventKey, CultureInfo.CurrentUICulture, etwFormat: false) is string msg) + if (manifest.GetLocalizedMessage(eventKey, CultureInfo.CurrentUICulture, etwFormat: false) is { } msg) { // overwrite inline message with the localized message eventAttribute.Message = msg; @@ -5856,7 +5856,7 @@ private void WriteMessageAttrib(StringBuilder? stringBuilder, string elementName { // resource fallback: strings in the neutral culture will take precedence over inline strings key = elementName + "_" + name; - if (resources.GetString(key, CultureInfo.InvariantCulture) is string localizedString) + if (resources.GetString(key, CultureInfo.InvariantCulture) is { } localizedString) value = localizedString; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Enum.cs b/src/libraries/System.Private.CoreLib/src/System/Enum.cs index f559948df33b1b..7ac11b388962ae 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Enum.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Enum.cs @@ -1863,7 +1863,7 @@ private static bool TryFormatPrimitiveDefault(RuntimeType if (!enumInfo.HasFlagsAttribute) { - if (GetNameInlined(enumInfo, Unsafe.BitCast(value)) is string enumName) + if (GetNameInlined(enumInfo, Unsafe.BitCast(value)) is { } enumName) { if (enumName.TryCopyTo(destination)) { @@ -1967,7 +1967,7 @@ private static bool TryFormatFlagNames(EnumInfo enumInfo, TS TStorage[] values = enumInfo.Values; Debug.Assert(names.Length == values.Length); - if (GetSingleFlagsEnumNameForValue(resultValue, names, values, out int index) is string singleEnumFlagsFormat) + if (GetSingleFlagsEnumNameForValue(resultValue, names, values, out int index) is { } singleEnumFlagsFormat) { if (singleEnumFlagsFormat.TryCopyTo(destination)) { diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.Unix.cs index 3076be747961a8..ec7ab8caac6a73 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/Enumeration/FileSystemEnumerator.Unix.cs @@ -240,13 +240,13 @@ private void InternalDispose(bool disposing) CloseDirectoryHandle(); - if (_pathBuffer is char[] pathBuffer) + if (_pathBuffer is { } pathBuffer) { _pathBuffer = null; ArrayPool.Shared.Return(pathBuffer); } - if (_entryBuffer is byte[] entryBuffer) + if (_entryBuffer is { } entryBuffer) { _entryBuffer = null; ArrayPool.Shared.Return(entryBuffer); diff --git a/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs b/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs index 174fac083981be..3b5b8bd0ae5a48 100644 --- a/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs +++ b/src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.cs @@ -3987,7 +3987,7 @@ private static bool TryWrite(Span destination, IForma foreach ((string? Literal, int ArgIndex, int Alignment, string? Format) segment in format._segments) { bool appended; - if (segment.Literal is string literal) + if (segment.Literal is { } literal) { appended = handler.AppendLiteral(literal); } @@ -4548,7 +4548,7 @@ private bool AppendCustomFormatter(T value, string? format) ICustomFormatter? formatter = (ICustomFormatter?)_provider.GetFormat(typeof(ICustomFormatter)); Debug.Assert(formatter != null, "An incorrectly written provider said it implemented ICustomFormatter, and then didn't"); - if (formatter is not null && formatter.Format(format, value, _provider) is string customFormatted) + if (formatter is not null && formatter.Format(format, value, _provider) is { } customFormatted) { return AppendLiteral(customFormatted); } 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 fd279a70fbbb6c..2316b7f7a6c50e 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Reflection/NullabilityInfoContext.cs @@ -451,7 +451,7 @@ private static MemberInfo GetMemberMetadataDefinition(MemberInfo member) private static Type GetPropertyMetaType(PropertyInfo property) { - if (property.GetGetMethod(true) is MethodInfo method) + if (property.GetGetMethod(true) is { } method) { return method.ReturnType; } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncTaskMethodBuilderT.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncTaskMethodBuilderT.cs index 5a2ccb1d635493..2a64ae3d1d4cf9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncTaskMethodBuilderT.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncTaskMethodBuilderT.cs @@ -339,7 +339,7 @@ public ref ExecutionContext? Context { get { - Debug.Assert(m_stateObject is null or ExecutionContext, $"Expected {nameof(m_stateObject)} to be null or an ExecutionContext but was {(m_stateObject is object o ? o.GetType().ToString() : "(null)")}."); + Debug.Assert(m_stateObject is null or ExecutionContext, $"Expected {nameof(m_stateObject)} to be null or an ExecutionContext but was {(m_stateObject is { } o ? o.GetType().ToString() : "(null)")}."); return ref Unsafe.As(ref m_stateObject); } } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.cs index 1d47cfb2b48706..bd4284709481f8 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/DefaultInterpolatedStringHandler.cs @@ -525,7 +525,7 @@ private void AppendCustomFormatter(T value, string? format) ICustomFormatter? formatter = (ICustomFormatter?)_provider.GetFormat(typeof(ICustomFormatter)); Debug.Assert(formatter != null, "An incorrectly written provider said it implemented ICustomFormatter, and then didn't"); - if (formatter is not null && formatter.Format(format, value, _provider) is string customFormatted) + if (formatter is not null && formatter.Format(format, value, _provider) is { } customFormatted) { AppendLiteral(customFormatted); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/PosixSignalRegistration.Unix.cs b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/PosixSignalRegistration.Unix.cs index 89c2eb45ac852f..706eddd34cfe83 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/PosixSignalRegistration.Unix.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/PosixSignalRegistration.Unix.cs @@ -57,7 +57,7 @@ private void Unregister() { lock (s_registrations) { - if (_token is Token token) + if (_token is { } token) { _token = null; diff --git a/src/libraries/System.Private.CoreLib/src/System/SearchValues/Strings/Helpers/RabinKarp.cs b/src/libraries/System.Private.CoreLib/src/System/SearchValues/Strings/Helpers/RabinKarp.cs index d8970655cb31b7..50368331e3cb9d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/SearchValues/Strings/Helpers/RabinKarp.cs +++ b/src/libraries/System.Private.CoreLib/src/System/SearchValues/Strings/Helpers/RabinKarp.cs @@ -81,7 +81,7 @@ public RabinKarp(ReadOnlySpan values) // Start with a bucket containing 1 element and reallocate larger ones if needed. // As MaxValues is similar to BucketCount, we will have 1 value per bucket on average. - if (buckets[bucket] is string[] existingBucket) + if (buckets[bucket] is { } existingBucket) { newBucket = new string[existingBucket.Length + 1]; existingBucket.AsSpan().CopyTo(newBucket); @@ -132,7 +132,7 @@ private readonly int IndexOfAnyCore(ReadOnlySpan span) { ValidateReadPosition(span, ref current); - if (Unsafe.Add(ref bucketsRef, hash % BucketCount) is string[] bucket) + if (Unsafe.Add(ref bucketsRef, hash % BucketCount) is { } bucket) { int startOffset = (int)((nuint)Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref current) / sizeof(char)); diff --git a/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs b/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs index 4b66027441618e..658617c94456aa 100644 --- a/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs +++ b/src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs @@ -659,7 +659,7 @@ private static string Format(IFormatProvider? provider, Com // Format each segment. foreach ((string? Literal, int ArgIndex, int Alignment, string? Format) segment in format._segments) { - if (segment.Literal is string literal) + if (segment.Literal is { } literal) { handler.AppendLiteral(literal); } @@ -1078,7 +1078,7 @@ private static string JoinCore(ReadOnlySpan separator, ReadOnlySpan totalLength - copiedLength) diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/CompositeFormat.cs b/src/libraries/System.Private.CoreLib/src/System/Text/CompositeFormat.cs index 3ecac9036eb2e8..14d7b31b51a79c 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/CompositeFormat.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/CompositeFormat.cs @@ -45,7 +45,7 @@ private CompositeFormat(string format, (string? Literal, int ArgIndex, int Align { Debug.Assert((segment.Literal is not null) ^ (segment.ArgIndex >= 0), "The segment should represent a literal or a format hole, but not both."); - if (segment.Literal is string literal) + if (segment.Literal is { } literal) { literalLength += literal.Length; // no concern about overflow as these were parsed out of a single string } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs index 11b76d7b19568d..ed5ae7fd506e6f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs @@ -1897,7 +1897,7 @@ private StringBuilder AppendFormat(IFormatProvider? provide // Append each segment. foreach ((string? Literal, int ArgIndex, int Alignment, string? Format) segment in format._segments) { - if (segment.Literal is string literal) + if (segment.Literal is { } literal) { handler.AppendLiteral(literal); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf8.cs b/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf8.cs index 9ae33c5b08b0ab..752a91a34c6728 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf8.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf8.cs @@ -658,7 +658,7 @@ private bool AppendCustomFormatter(T value, string? format) Debug.Assert(formatter is not null, "An incorrectly written provider said it implemented ICustomFormatter, and then didn't"); if (formatter is not null && - formatter.Format(format, value, _provider) is string customFormatted) + formatter.Format(format, value, _provider) is { } customFormatted) { return AppendFormatted(customFormatted.AsSpan()); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenRegistration.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenRegistration.cs index 345b41a32acff7..ce73d9ddbd218f 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenRegistration.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/CancellationTokenRegistration.cs @@ -31,7 +31,7 @@ internal CancellationTokenRegistration(long id, CancellationTokenSource.Callback /// public void Dispose() { - if (_node is CancellationTokenSource.CallbackNode node && !node.Registrations.Unregister(_id, node)) + if (_node is { } node && !node.Registrations.Unregister(_id, node)) { WaitForCallbackIfNecessary(_id, node); @@ -68,7 +68,7 @@ static void WaitForCallbackIfNecessary(long id, CancellationTokenSource.Callback /// public ValueTask DisposeAsync() { - return _node is CancellationTokenSource.CallbackNode node && !node.Registrations.Unregister(_id, node) ? + return _node is { } node && !node.Registrations.Unregister(_id, node) ? WaitForCallbackIfNecessaryAsync(_id, node) : default; @@ -98,7 +98,7 @@ static ValueTask WaitForCallbackIfNecessaryAsync(long id, CancellationTokenSourc /// this will return a default token. /// public CancellationToken Token => - _node is CancellationTokenSource.CallbackNode node ? + _node is { } node ? new CancellationToken(node.Registrations.Source) : // avoid CTS.Token, which throws after disposal default; @@ -107,7 +107,7 @@ _node is CancellationTokenSource.CallbackNode node ? /// CancellationToken. /// public bool Unregister() => - _node is CancellationTokenSource.CallbackNode node && node.Registrations.Unregister(_id, node); + _node is { } node && node.Registrations.Unregister(_id, node); /// /// Determines whether two GetTask(int result) { - if (_task is Task task) + if (_task is { } task) { Debug.Assert(task.IsCompletedSuccessfully, "Expected that a stored last task completed successfully"); if (task.Result == result) diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs index c29c5e759f2c1d..0043b609f8341a 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Sources/ManualResetValueTaskSourceCore.cs @@ -132,7 +132,7 @@ public void OnCompleted(Action continuation, object? state, short token if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0) { - if (SynchronizationContext.Current is SynchronizationContext sc && + if (SynchronizationContext.Current is { } sc && sc.GetType() != typeof(SynchronizationContext)) { _capturedContext = _capturedContext is null ? diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs index 335ec2b55123e4..5b1ff9e0e08c7b 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs @@ -2499,7 +2499,7 @@ internal void SetContinuationForAwait( // then ignore it. This helps with performance by avoiding unnecessary posts and queueing // of work items, but more so it ensures that if code happens to publish the default context // as current, it won't prevent usage of a current task scheduler if there is one. - if (SynchronizationContext.Current is SynchronizationContext syncCtx && syncCtx.GetType() != typeof(SynchronizationContext)) + if (SynchronizationContext.Current is { } syncCtx && syncCtx.GetType() != typeof(SynchronizationContext)) { tc = new SynchronizationContextAwaitTaskContinuation(syncCtx, continuationAction, flowExecutionContext); goto HaveTaskContinuation; @@ -2507,7 +2507,7 @@ internal void SetContinuationForAwait( // If there was no SynchronizationContext, then try for the current scheduler. // We only care about it if it's not the default. - if (TaskScheduler.InternalCurrent is TaskScheduler scheduler && scheduler != TaskScheduler.Default) + if (TaskScheduler.InternalCurrent is { } scheduler && scheduler != TaskScheduler.Default) { tc = new TaskSchedulerAwaitTaskContinuation(scheduler, continuationAction, flowExecutionContext); goto HaveTaskContinuation; @@ -2572,13 +2572,13 @@ internal void UnsafeSetContinuationForAwait(IAsyncStateMachineBox stateMachineBo // fall back to using the state machine's delegate. if (continueOnCapturedContext) { - if (SynchronizationContext.Current is SynchronizationContext syncCtx && syncCtx.GetType() != typeof(SynchronizationContext)) + if (SynchronizationContext.Current is { } syncCtx && syncCtx.GetType() != typeof(SynchronizationContext)) { tc = new SynchronizationContextAwaitTaskContinuation(syncCtx, stateMachineBox.MoveNextAction, flowExecutionContext: false); goto HaveTaskContinuation; } - if (TaskScheduler.InternalCurrent is TaskScheduler scheduler && scheduler != TaskScheduler.Default) + if (TaskScheduler.InternalCurrent is { } scheduler && scheduler != TaskScheduler.Default) { tc = new TaskSchedulerAwaitTaskContinuation(scheduler, stateMachineBox.MoveNextAction, flowExecutionContext: false); goto HaveTaskContinuation; diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ValueTask.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ValueTask.cs index c8d0aec3960bbe..52b87cb7705cd4 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ValueTask.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/ValueTask.cs @@ -234,7 +234,7 @@ private sealed class ValueTaskSourceAsTask : Task private static readonly Action s_completionAction = static state => { if (state is not ValueTaskSourceAsTask vtst || - vtst._source is not IValueTaskSource source) + vtst._source is not { } source) { // This could only happen if the IValueTaskSource passed the wrong state // or if this callback were invoked multiple times such that the state @@ -641,7 +641,7 @@ private sealed class ValueTaskSourceAsTask : Task private static readonly Action s_completionAction = static state => { if (state is not ValueTaskSourceAsTask vtst || - vtst._source is not IValueTaskSource source) + vtst._source is not { } source) { // This could only happen if the IValueTaskSource passed the wrong state // or if this callback were invoked multiple times such that the state diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolWorkQueue.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolWorkQueue.cs index 411bc6c6dce611..5e1f18a90195eb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolWorkQueue.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/ThreadPoolWorkQueue.cs @@ -705,7 +705,7 @@ public void EnqueueAtHighPriority(object workItem) internal static void TransferAllLocalWorkItemsToHighPriorityGlobalQueue() { // If there's no local queue, there's nothing to transfer. - if (ThreadPoolWorkQueueThreadLocals.threadLocals is not ThreadPoolWorkQueueThreadLocals tl) + if (ThreadPoolWorkQueueThreadLocals.threadLocals is not { } tl) { return; } @@ -713,7 +713,7 @@ internal static void TransferAllLocalWorkItemsToHighPriorityGlobalQueue() // Pop each work item off the local queue and push it onto the global. This is a // bounded loop as no other thread is allowed to push into this thread's queue. ThreadPoolWorkQueue queue = ThreadPool.s_workQueue; - while (tl.workStealingQueue.LocalPop() is object workItem) + while (tl.workStealingQueue.LocalPop() is { } workItem) { queue.highPriorityWorkItems.Enqueue(workItem); } @@ -1255,7 +1255,7 @@ public ThreadPoolWorkQueueThreadLocals(ThreadPoolWorkQueue tpq) public void TransferLocalWork() { - while (workStealingQueue.LocalPop() is object cb) + while (workStealingQueue.LocalPop() is { } cb) { workQueue.Enqueue(cb, forceGlobal: true); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs index 70bbc3bd2e20e7..e1e73ef9168df9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/WaitHandle.cs @@ -346,7 +346,7 @@ private static int WaitMultiple(ReadOnlySpan waitHandles, bool waitA { for (int i = 0; i < waitHandles.Length; ++i) { - if (safeWaitHandles[i] is SafeWaitHandle swh) + if (safeWaitHandles[i] is { } swh) { swh.DangerousRelease(); safeWaitHandles[i] = null; diff --git a/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs b/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs index e508fc1027742f..6ad57d5c5ab281 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.Helpers.cs @@ -136,7 +136,7 @@ public virtual Type[] FindInterfaces(TypeFilter filter, object? filterCriteria) cnt = 0; for (int i = 0; i < c.Length; i++) { - if (c[i] is Type t) + if (c[i] is { } t) ret[cnt++] = t!; } return ret; @@ -280,7 +280,7 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin if (c != null) { for (i = 0; i < c.Length; i++) - if (c[i] is ConstructorInfo ci) + if (c[i] is { } ci) ret[cnt++] = ci; } @@ -288,7 +288,7 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin if (f != null) { for (i = 0; i < f.Length; i++) - if (f[i] is FieldInfo fi) + if (f[i] is { } fi) ret[cnt++] = fi; } @@ -296,7 +296,7 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin if (p != null) { for (i = 0; i < p.Length; i++) - if (p[i] is PropertyInfo pi) + if (p[i] is { } pi) ret[cnt++] = pi; } @@ -304,7 +304,7 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin if (e != null) { for (i = 0; i < e.Length; i++) - if (e[i] is EventInfo ei) + if (e[i] is { } ei) ret[cnt++] = ei; } @@ -312,7 +312,7 @@ public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bin if (t != null) { for (i = 0; i < t.Length; i++) - if (t[i] is Type type) + if (t[i] is { } type) ret[cnt++] = type; } diff --git a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/ConvertToLibraryImportFixer.cs b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/ConvertToLibraryImportFixer.cs index b83eb5803abffd..3e04fce4666b2b 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/ConvertToLibraryImportFixer.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/ConvertToLibraryImportFixer.cs @@ -39,7 +39,7 @@ protected override string GetDiagnosticTitle(ImmutableDictionary bool allowUnsafe = selectedOptions.TryGetValue(Option.AllowUnsafe, out Option? allowUnsafeOption) && allowUnsafeOption is Option.Bool(true); string? suffix = null; bool hasSuffix = false; - if (selectedOptions.TryGetValue(SelectedSuffixOption, out Option? suffixOption) && suffixOption is Option.String(string suffixValue)) + if (selectedOptions.TryGetValue(SelectedSuffixOption, out Option? suffixOption) && suffixOption is Option.String({ } suffixValue)) { hasSuffix = true; suffix = suffixValue; @@ -77,7 +77,7 @@ protected override IEnumerable CreateAllFixe { bool warnForAdditionalWork = options.TryGetValue(Option.MayRequireAdditionalWork, out Option mayRequireAdditionalWork) && mayRequireAdditionalWork is Option.Bool(true); - CharSet? charSet = options.TryGetValue(CharSetOption, out Option charSetOption) && charSetOption is Option.String(string charSetString) && Enum.TryParse(charSetString, out CharSet result) ? result : null; + CharSet? charSet = options.TryGetValue(CharSetOption, out Option charSetOption) && charSetOption is Option.String({ } charSetString) && Enum.TryParse(charSetString, out CharSet result) ? result : null; // We don't want the CharSet option contributing to the "selected options" set for the fix, so we remove it here. var selectedOptions = options.Remove(CharSetOption); @@ -129,7 +129,7 @@ protected override IEnumerable CreateAllFixe protected override Func CreateFixForSelectedOptions(SyntaxNode node, ImmutableDictionary selectedOptions) { bool warnForAdditionalWork = selectedOptions.TryGetValue(Option.MayRequireAdditionalWork, out Option mayRequireAdditionalWork) && mayRequireAdditionalWork is Option.Bool(true); - char? suffix = selectedOptions.TryGetValue(SelectedSuffixOption, out Option selectedSuffixOption) && selectedSuffixOption is Option.String(string selectedSuffix) ? selectedSuffix[0] : null; + char? suffix = selectedOptions.TryGetValue(SelectedSuffixOption, out Option selectedSuffixOption) && selectedSuffixOption is Option.String({ } selectedSuffix) ? selectedSuffix[0] : null; return (editor, ct) => ConvertToLibraryImport( editor, diff --git a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/ShapeBreakingDiagnosticSuppressor.cs b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/ShapeBreakingDiagnosticSuppressor.cs index e4b21ffecbcb3a..4a3c2ebda54232 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/ShapeBreakingDiagnosticSuppressor.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/LibraryImportGenerator/Analyzers/ShapeBreakingDiagnosticSuppressor.cs @@ -40,7 +40,7 @@ private static void SuppressMarkMethodsAsStaticDiagnosticIfNeeded(SuppressionAna return; } - if (FindContainingEntryPointTypeAndManagedType(diagnosedSymbol.ContainingType) is (INamedTypeSymbol entryPointMarshallerType, INamedTypeSymbol managedType)) + if (FindContainingEntryPointTypeAndManagedType(diagnosedSymbol.ContainingType) is ({ } entryPointMarshallerType, { } managedType)) { bool isLinearCollectionMarshaller = ManualTypeMarshallingHelper.IsLinearCollectionEntryPoint(entryPointMarshallerType); (MarshallerShape _, StatefulMarshallerShapeHelper.MarshallerMethods methods) = StatefulMarshallerShapeHelper.GetShapeForType(diagnosedSymbol.ContainingType, managedType, isLinearCollectionMarshaller, context.Compilation); diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/ArrayMarshallingInfoProvider.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/ArrayMarshallingInfoProvider.cs index 711886c2797e00..a5cdb85870c978 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/ArrayMarshallingInfoProvider.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/ArrayMarshallingInfoProvider.cs @@ -46,7 +46,7 @@ public static MarshallingInfo CreateArrayMarshallingInfo( { ITypeSymbol typeArgumentToInsert = elementType; INamedTypeSymbol? arrayMarshaller; - if (elementType is IPointerTypeSymbol { PointedAtType: ITypeSymbol pointedAt }) + if (elementType is IPointerTypeSymbol { PointedAtType: { } pointedAt }) { arrayMarshaller = compilation.GetTypeByMetadataName(TypeNames.System_Runtime_InteropServices_PointerArrayMarshaller_Metadata); typeArgumentToInsert = pointedAt; diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshalAsWithCustomMarshallersParser.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshalAsWithCustomMarshallersParser.cs index 863520167a0351..ec57662ef12bdb 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshalAsWithCustomMarshallersParser.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshalAsWithCustomMarshallersParser.cs @@ -50,7 +50,7 @@ public MarshalAsWithCustomMarshallersParser(Compilation compilation, GeneratorDi if (marshalAsInfo is MarshalAsArrayInfo arrayInfo) { - if (type is not IArrayTypeSymbol { ElementType: ITypeSymbol elementType }) + if (type is not IArrayTypeSymbol { ElementType: { } elementType }) { _diagnostics.ReportConfigurationNotSupported(attributeData, nameof(UnmanagedType), arrayInfo.UnmanagedType.ToString()); return NoMarshallingInfo.Instance; diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/AttributedMarshallingModelGeneratorResolver.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/AttributedMarshallingModelGeneratorResolver.cs index 771043dcb1ae52..3056c48a5747e5 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/AttributedMarshallingModelGeneratorResolver.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/AttributedMarshallingModelGeneratorResolver.cs @@ -69,8 +69,8 @@ public ExpressionOrNotSupported(GeneratorDiagnostic.NotSupported notSupportedDia { SizeAndParamIndexInfo(_, SizeAndParamIndexInfo.UnspecifiedParam) => null, ConstSizeCountInfo => null, - SizeAndParamIndexInfo(_, TypePositionInfo param) => ValidateNumElementsExpression(param, out countInfoRequiresCast), - CountElementCountInfo(TypePositionInfo elementInfo) => ValidateNumElementsExpression(elementInfo, out countInfoRequiresCast), + SizeAndParamIndexInfo(_, { } param) => ValidateNumElementsExpression(param, out countInfoRequiresCast), + CountElementCountInfo({ } elementInfo) => ValidateNumElementsExpression(elementInfo, out countInfoRequiresCast), _ => new GeneratorDiagnostic.NotSupported(info) { NotSupportedDetails = SR.ArraySizeMustBeSpecified @@ -143,7 +143,7 @@ private CustomTypeMarshallerData GetMarshallerDataForTypePositionInfo(CustomType private ResolvedGenerator CreateCustomNativeTypeMarshaller(TypePositionInfo info, StubCodeContext context, NativeMarshallingAttributeInfo marshalInfo) { - if (ValidateCustomNativeTypeMarshallingSupported(info, context, marshalInfo) is GeneratorDiagnostic.NotSupported diagnostic) + if (ValidateCustomNativeTypeMarshallingSupported(info, context, marshalInfo) is { } diagnostic) { return ResolvedGenerator.NotSupported(info, context, diagnostic); } diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/BreakingChangeDetector.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/BreakingChangeDetector.cs index 6906b9b2bcc052..20594ad63dd547 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/BreakingChangeDetector.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/BreakingChangeDetector.cs @@ -23,7 +23,7 @@ public ResolvedGenerator Create(TypePositionInfo info, StubCodeContext context) } // Breaking change: [MarshalAs(UnmanagedType.Struct)] in object in unmanaged-to-managed scenarios will not respect VT_BYREF. - if (info is { RefKind: RefKind.In or RefKind.RefReadOnlyParameter, MarshallingAttributeInfo: NativeMarshallingAttributeInfo(ManagedTypeInfo { DiagnosticFormattedName: TypeNames.ComVariantMarshaller }, _) } + if (info is { RefKind: RefKind.In or RefKind.RefReadOnlyParameter, MarshallingAttributeInfo: NativeMarshallingAttributeInfo({ DiagnosticFormattedName: TypeNames.ComVariantMarshaller }, _) } && context.Direction == MarshalDirection.UnmanagedToManaged) { gen = ResolvedGenerator.ResolvedWithDiagnostics( diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/ElementsMarshalling.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/ElementsMarshalling.cs index 6e1b1d44ba616c..08e548e47637e0 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/ElementsMarshalling.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/ElementsMarshalling.cs @@ -65,12 +65,12 @@ public static ExpressionSyntax GenerateNumElementsExpression(CountInfo count, bo { SizeAndParamIndexInfo(int size, SizeAndParamIndexInfo.UnspecifiedParam) => GetConstSizeExpression(size), ConstSizeCountInfo(int size) => GetConstSizeExpression(size), - SizeAndParamIndexInfo(SizeAndParamIndexInfo.UnspecifiedConstSize, TypePositionInfo param) => GetExpressionForParam(param), - SizeAndParamIndexInfo(int size, TypePositionInfo param) => CheckedExpression(SyntaxKind.CheckedExpression, + SizeAndParamIndexInfo(SizeAndParamIndexInfo.UnspecifiedConstSize, { } param) => GetExpressionForParam(param), + SizeAndParamIndexInfo(int size, { } param) => CheckedExpression(SyntaxKind.CheckedExpression, BinaryExpression(SyntaxKind.AddExpression, GetConstSizeExpression(size), GetExpressionForParam(param))), - CountElementCountInfo(TypePositionInfo elementInfo) => GetExpressionForParam(elementInfo), + CountElementCountInfo({ } elementInfo) => GetExpressionForParam(elementInfo), _ => throw new UnreachableException("Count info should have been verified in generator resolution") }; diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshallerHelpers.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshallerHelpers.cs index d37849547d1a21..eb30ec8f6b171f 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshallerHelpers.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/Marshalling/MarshallerHelpers.cs @@ -234,7 +234,7 @@ public static IEnumerable GetDependentElementsOfMarshallingInf { if (elementMarshallingInfo is NativeLinearCollectionMarshallingInfo nestedCollection) { - if (nestedCollection.ElementCountInfo is CountElementCountInfo { ElementInfo: TypePositionInfo nestedCountElement }) + if (nestedCollection.ElementCountInfo is CountElementCountInfo { ElementInfo: { } nestedCountElement }) { // Do not include dependent elements with no managed or native index. // These values are dummy values that are inserted earlier to avoid emitting extra diagnostics. diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshallingInfoParser.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshallingInfoParser.cs index 23457d50f85b0a..54346217b6ff95 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshallingInfoParser.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MarshallingInfoParser.cs @@ -231,7 +231,7 @@ private MarshallingInfo GetMarshallingInfo( { if (useSiteAttributes.TryGetUseSiteAttributeInfo(indirectionDepth, out UseSiteAttributeData useSiteAttribute)) { - if (GetMarshallingInfoForAttribute(useSiteAttribute.AttributeData, type, indirectionDepth, useSiteAttributes, GetMarshallingInfo) is MarshallingInfo marshallingInfo) + if (GetMarshallingInfoForAttribute(useSiteAttribute.AttributeData, type, indirectionDepth, useSiteAttributes, GetMarshallingInfo) is { } marshallingInfo) { return marshallingInfo; } @@ -241,7 +241,7 @@ private MarshallingInfo GetMarshallingInfo( // then fall back to the information on the element type itself. foreach (AttributeData typeAttribute in type.GetAttributes()) { - if (GetMarshallingInfoForAttribute(typeAttribute, type, indirectionDepth, useSiteAttributes, GetMarshallingInfo) is MarshallingInfo marshallingInfo) + if (GetMarshallingInfoForAttribute(typeAttribute, type, indirectionDepth, useSiteAttributes, GetMarshallingInfo) is { } marshallingInfo) { return marshallingInfo; } diff --git a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MethodSignatureDiagnosticLocations.cs b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MethodSignatureDiagnosticLocations.cs index 2705493f9155aa..db55baa5d8e413 100644 --- a/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MethodSignatureDiagnosticLocations.cs +++ b/src/libraries/System.Runtime.InteropServices/gen/Microsoft.Interop.SourceGeneration/MethodSignatureDiagnosticLocations.cs @@ -62,7 +62,7 @@ public DiagnosticInfo CreateDiagnosticInfo(DiagnosticDescriptor descriptor, Gene { var (location, elementName) = diagnostic.TypePositionInfo switch { - { ManagedIndex: >= 0 and int index, InstanceIdentifier: string identifier } => (ManagedParameterLocations[index], identifier), + { ManagedIndex: >= 0 and int index, InstanceIdentifier: { } identifier } => (ManagedParameterLocations[index], identifier), _ => (FallbackLocation, MethodIdentifier), }; return diagnostic.ToDiagnosticInfo(descriptor, location, elementName); diff --git a/src/tools/illink/src/ILLink.CodeFix/DynamicallyAccessedMembersCodeFixProvider.cs b/src/tools/illink/src/ILLink.CodeFix/DynamicallyAccessedMembersCodeFixProvider.cs index 28d82bafae8872..47fbbda5040395 100644 --- a/src/tools/illink/src/ILLink.CodeFix/DynamicallyAccessedMembersCodeFixProvider.cs +++ b/src/tools/illink/src/ILLink.CodeFix/DynamicallyAccessedMembersCodeFixProvider.cs @@ -100,9 +100,9 @@ public override async Task RegisterCodeFixesAsync (CodeFixContext context) return; if (diagnostic.AdditionalLocations.Count == 0) return; - if (root.FindNode (diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true) is not SyntaxNode targetNode) + if (root.FindNode (diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true) is not { } targetNode) return; - if (diagnostic.Properties["attributeArgument"] is not string stringArgs || stringArgs.Contains (",")) + if (diagnostic.Properties["attributeArgument"] is not { } stringArgs || stringArgs.Contains (",")) return; context.RegisterCodeFix (CodeAction.Create ( diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/CompilationExtensions.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/CompilationExtensions.cs index 8371225d8f1aa4..44c7f1f11e6ede 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/CompilationExtensions.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/CompilationExtensions.cs @@ -62,7 +62,7 @@ public static class CompilationExtensions continue; } - if (type is object) { + if (type is not null) { // Multiple visible types with the same metadata name are present return null; } diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/ControlFlowGraphProxy.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/ControlFlowGraphProxy.cs index 14e9a5028e5177..da026fdc2dd699 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/ControlFlowGraphProxy.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/ControlFlowGraphProxy.cs @@ -101,9 +101,9 @@ public IEnumerable GetPredecessors (BlockProxy block) public IEnumerable GetSuccessors (BlockProxy block) { - if (block.Block.ConditionalSuccessor is Microsoft.CodeAnalysis.FlowAnalysis.ControlFlowBranch conditionalSuccessor) + if (block.Block.ConditionalSuccessor is { } conditionalSuccessor) yield return CreateProxyBranch (conditionalSuccessor); - if (block.Block.FallThroughSuccessor is Microsoft.CodeAnalysis.FlowAnalysis.ControlFlowBranch fallThroughSuccessor) + if (block.Block.FallThroughSuccessor is { } fallThroughSuccessor) yield return CreateProxyBranch (fallThroughSuccessor); } diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/FeatureChecksVisitor.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/FeatureChecksVisitor.cs index f037ffdc6cde0d..f5e3171b68375a 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/FeatureChecksVisitor.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/FeatureChecksVisitor.cs @@ -107,14 +107,14 @@ public override FeatureChecksValue VisitBinaryOperator (IBinaryOperation operati return FeatureChecksValue.None; } - if (GetLiteralBool (operation.LeftOperand) is bool leftBool) { + if (GetLiteralBool (operation.LeftOperand) is { } leftBool) { FeatureChecksValue rightValue = Visit (operation.RightOperand, state); return leftBool == expectEqual ? rightValue : rightValue.Negate (); } - if (GetLiteralBool (operation.RightOperand) is bool rightBool) { + if (GetLiteralBool (operation.RightOperand) is { } rightBool) { FeatureChecksValue leftValue = Visit (operation.LeftOperand, state); return rightBool == expectEqual ? leftValue @@ -126,7 +126,7 @@ public override FeatureChecksValue VisitBinaryOperator (IBinaryOperation operati public override FeatureChecksValue VisitIsPattern (IIsPatternOperation operation, StateValue state) { - if (GetExpectedValueFromPattern (operation.Pattern) is not bool patternValue) + if (GetExpectedValueFromPattern (operation.Pattern) is not { } patternValue) return FeatureChecksValue.None; FeatureChecksValue value = Visit (operation.Value, state); diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowVisitor.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowVisitor.cs index 84065ecc25fe8f..92d48fb2d4d840 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowVisitor.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/DataFlow/LocalDataFlowVisitor.cs @@ -749,7 +749,7 @@ TValue HandleMethodCallHelper ( } foreach (var parameterProxy in calledMethod.GetParameters ()) { - if (parameterProxy.ParameterSymbol is not IParameterSymbol parameter) + if (parameterProxy.ParameterSymbol is not { } parameter) continue; if (!parameter.TryGetAttribute (nameof (DoesNotReturnIfAttribute), out var attributeData)) diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/DynamicallyAccessedMembersAnalyzer.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/DynamicallyAccessedMembersAnalyzer.cs index 1f31934d9b898b..c44d719fad3aea 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/DynamicallyAccessedMembersAnalyzer.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/DynamicallyAccessedMembersAnalyzer.cs @@ -122,7 +122,7 @@ public override void Initialize (AnalysisContext context) var location = GetPrimaryLocation (type.Locations); - if (type.BaseType is INamedTypeSymbol baseType) + if (type.BaseType is { } baseType) GenericArgumentDataFlow.ProcessGenericArgumentDataFlow (location, baseType, context.ReportDiagnostic); foreach (var interfaceType in type.Interfaces) diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/DynamicallyAccessedMembersTypeHierarchy.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/DynamicallyAccessedMembersTypeHierarchy.cs index 9b6ea59ba10459..a20a145d217b9a 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/DynamicallyAccessedMembersTypeHierarchy.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/DynamicallyAccessedMembersTypeHierarchy.cs @@ -20,7 +20,7 @@ public static void ApplyDynamicallyAccessedMembersToTypeHierarchy (Location type // But the annotations on base/interfaces may already be applied so we don't need to apply those // again (and should avoid doing so as it would produce extra warnings). var reflectionAccessAnalyzer = new ReflectionAccessAnalyzer (reportDiagnostic, type); - if (type.BaseType is INamedTypeSymbol baseType) { + if (type.BaseType is { } baseType) { var baseAnnotation = FlowAnnotations.GetTypeAnnotation (baseType); var annotationToApplyToBase = Annotations.GetMissingMemberTypes (annotation, baseAnnotation); diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/IMethodSymbolExtensions.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/IMethodSymbolExtensions.cs index c656ff0d4f93aa..646ca961f8ed13 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/IMethodSymbolExtensions.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/IMethodSymbolExtensions.cs @@ -37,7 +37,7 @@ public static ParameterProxyEnumerable GetMetadataParameters (this IMethodSymbol /// public static ParameterProxy GetParameter (this IMethodSymbol method, ParameterIndex index) { - if (method.TryGetParameter (index) is not ParameterProxy param) + if (method.TryGetParameter (index) is not { } param) throw new InvalidOperationException ($"Cannot get parameter at index {(int) index} of method {method.GetDisplayName ()} with {method.GetParametersCount ()} parameters."); return param; } diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/INamedTypeSymbolExtensions.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/INamedTypeSymbolExtensions.cs index 597329cde3d9e1..3e0bf32685785f 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/INamedTypeSymbolExtensions.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/INamedTypeSymbolExtensions.cs @@ -44,7 +44,7 @@ internal static bool HasName (this INamedTypeSymbol type, string typeName) { var members = interfaceSymbol.GetMembers (); foreach (ISymbol interfaceMember in members) { - if (implementationSymbol.FindImplementationForInterfaceMember (interfaceMember) is ISymbol implementationMember) { + if (implementationSymbol.FindImplementationForInterfaceMember (interfaceMember) is { } implementationMember) { yield return (InterfaceMember: interfaceMember, ImplementationMember: implementationMember); } } diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/ISymbolExtensions.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/ISymbolExtensions.cs index 3bed1db0f50637..87a3e071699e05 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/ISymbolExtensions.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/ISymbolExtensions.cs @@ -81,7 +81,7 @@ internal static ValueSet GetFeatureGuardAnnotations (this IPropertySymbo { HashSet featureSet = new (); foreach (var featureGuardAttribute in propertySymbol.GetAttributes (DynamicallyAccessedMembersAnalyzer.FullyQualifiedFeatureGuardAttribute)) { - if (featureGuardAttribute.ConstructorArguments is [TypedConstant { Value: INamedTypeSymbol featureType }]) + if (featureGuardAttribute.ConstructorArguments is [{ Value: INamedTypeSymbol featureType }]) featureSet.Add (featureType.GetDisplayName ()); } return featureSet.Count == 0 ? ValueSet.Empty : new ValueSet (featureSet); @@ -101,7 +101,7 @@ internal static bool TryGetReturnAttribute (this IMethodSymbol member, string at } internal static DynamicallyAccessedMemberTypes GetDynamicallyAccessedMemberTypesOnAssociatedSymbol (this IMethodSymbol methodSymbol) => - methodSymbol.AssociatedSymbol is ISymbol associatedSymbol ? GetDynamicallyAccessedMemberTypes (associatedSymbol) : DynamicallyAccessedMemberTypes.None; + methodSymbol.AssociatedSymbol is { } associatedSymbol ? GetDynamicallyAccessedMemberTypes (associatedSymbol) : DynamicallyAccessedMemberTypes.None; internal static bool TryGetOverriddenMember (this ISymbol? symbol, [NotNullWhen (returnValue: true)] out ISymbol? overriddenMember) { diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/RequiresAnalyzerBase.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/RequiresAnalyzerBase.cs index 494568e45d85d1..8f6b37a24fdca8 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/RequiresAnalyzerBase.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/RequiresAnalyzerBase.cs @@ -71,7 +71,7 @@ public override void Initialize (AnalysisContext context) context.RegisterSyntaxNodeAction (syntaxNodeAnalysisContext => { var model = syntaxNodeAnalysisContext.SemanticModel; - if (syntaxNodeAnalysisContext.ContainingSymbol is not ISymbol containingSymbol || containingSymbol.IsInRequiresScope (RequiresAttributeName, out _)) + if (syntaxNodeAnalysisContext.ContainingSymbol is not { } containingSymbol || containingSymbol.IsInRequiresScope (RequiresAttributeName, out _)) return; GenericNameSyntax genericNameSyntaxNode = (GenericNameSyntax) syntaxNodeAnalysisContext.Node; diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/RequiresAssemblyFilesAnalyzer.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/RequiresAssemblyFilesAnalyzer.cs index 2d19237b03ea2d..726c931a629b85 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/RequiresAssemblyFilesAnalyzer.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/RequiresAssemblyFilesAnalyzer.cs @@ -113,7 +113,7 @@ protected override bool CreateSpecialIncompatibleMembersDiagnostic ( diagnosticContext.AddDiagnostic (DiagnosticId.AvoidAssemblyGetFilesInSingleFile, member.GetDisplayName ()); return true; } - else if (method.AssociatedSymbol is ISymbol associatedSymbol && + else if (method.AssociatedSymbol is { } associatedSymbol && ImmutableArrayOperations.Contains (dangerousPatterns, associatedSymbol, SymbolEqualityComparer.Default)) { diagnosticContext.AddDiagnostic (DiagnosticId.AvoidAssemblyLocationInSingleFile, member.GetDisplayName ()); // The getters for CodeBase and EscapedCodeBase have RAF attribute on them diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/RequiresUnreferencedCodeAnalyzer.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/RequiresUnreferencedCodeAnalyzer.cs index ea3e914697e418..4d89852e271175 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/RequiresUnreferencedCodeAnalyzer.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/RequiresUnreferencedCodeAnalyzer.cs @@ -31,7 +31,7 @@ private Action typeDerivesFromRucBase { get { return symbolAnalysisContext => { if (symbolAnalysisContext.Symbol is INamedTypeSymbol typeSymbol && !typeSymbol.HasAttribute (RequiresUnreferencedCodeAttribute) - && typeSymbol.BaseType is INamedTypeSymbol baseType + && typeSymbol.BaseType is { } baseType && baseType.TryGetAttribute (RequiresUnreferencedCodeAttribute, out var requiresUnreferencedCodeAttribute)) { var diag = Diagnostic.Create (s_typeDerivesFromRucClassRule, typeSymbol.Locations[0], diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/TrimAnalysis/TrimAnalysisVisitor.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/TrimAnalysis/TrimAnalysisVisitor.cs index 95ab7f31e08cdd..5d665475250102 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/TrimAnalysis/TrimAnalysisVisitor.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/TrimAnalysis/TrimAnalysisVisitor.cs @@ -121,7 +121,7 @@ public override MultiValue VisitConversion (IConversionOperation operation, Stat { var value = base.VisitConversion (operation, state); - if (operation.OperatorMethod is IMethodSymbol method) + if (operation.OperatorMethod is { } method) return method.ReturnType.IsTypeInterestingForDataflow (isByRef: method.ReturnsByRef) ? new MethodReturnValue (method, isNewObj: false) : value; // TODO - is it possible to have annotation on the operator method parameters? @@ -243,7 +243,7 @@ public override void HandleAssignment (MultiValue source, MultiValue target, IOp public override MultiValue HandleArrayElementRead (MultiValue arrayValue, MultiValue indexValue, IOperation operation) { - if (indexValue.AsConstInt () is not int index) + if (indexValue.AsConstInt () is not { } index) return UnknownValue.Instance; MultiValue result = TopValue; diff --git a/src/tools/illink/src/ILLink.RoslynAnalyzer/TrimAnalysis/TrimDataFlowAnalysis.cs b/src/tools/illink/src/ILLink.RoslynAnalyzer/TrimAnalysis/TrimDataFlowAnalysis.cs index 3284176cb411b6..b052277cc78591 100644 --- a/src/tools/illink/src/ILLink.RoslynAnalyzer/TrimAnalysis/TrimDataFlowAnalysis.cs +++ b/src/tools/illink/src/ILLink.RoslynAnalyzer/TrimAnalysis/TrimDataFlowAnalysis.cs @@ -90,11 +90,11 @@ public override void TraceStart (ControlFlowGraphProxy cfg) var blocks = cfg.Blocks.ToList (); string? methodName = null; foreach (var block in blocks) { - if (block.Block.Operations.FirstOrDefault () is not IOperation op) + if (block.Block.Operations.FirstOrDefault () is not { } op) continue; var method = op.Syntax.FirstAncestorOrSelf (); - if (method is MethodDeclarationSyntax) + if (method is not null) methodName = method.Identifier.ValueText; break; @@ -112,9 +112,9 @@ public override void TraceVisitBlock (BlockProxy block) return; TraceWrite ("block " + block.Block.Ordinal + ": "); - if (block.Block.Operations.FirstOrDefault () is IOperation firstBlockOp) { + if (block.Block.Operations.FirstOrDefault () is { } firstBlockOp) { TraceWriteLine (firstBlockOp.Syntax.ToString ()); - } else if (block.Block.BranchValue is IOperation branchOp) { + } else if (block.Block.BranchValue is { } branchOp) { TraceWriteLine (branchOp.Syntax.ToString ()); } else { TraceWriteLine (""); diff --git a/src/tools/illink/src/ILLink.Shared/DataFlow/MaybeLattice.cs b/src/tools/illink/src/ILLink.Shared/DataFlow/MaybeLattice.cs index 89a5d1f98d16e4..2342e76dbcf23b 100644 --- a/src/tools/illink/src/ILLink.Shared/DataFlow/MaybeLattice.cs +++ b/src/tools/illink/src/ILLink.Shared/DataFlow/MaybeLattice.cs @@ -20,7 +20,7 @@ public struct Maybe : IEquatable>, IDeepCopyValue> public override int GetHashCode () => MaybeValue?.GetHashCode () ?? 0; public Maybe DeepCopy () { - if (MaybeValue is not T value) + if (MaybeValue is not { } value) return default; if (value is IDeepCopyValue copyValue) return new (copyValue.DeepCopy ()); @@ -44,9 +44,9 @@ public MaybeLattice (TValueLattice valueLattice) public Maybe Top { get; } public Maybe Meet (Maybe left, Maybe right) { - if (left.MaybeValue is not T leftValue) + if (left.MaybeValue is not { } leftValue) return right.DeepCopy (); - if (right.MaybeValue is not T rightValue) + if (right.MaybeValue is not { } rightValue) return left.DeepCopy (); return new Maybe (ValueLattice.Meet (leftValue, rightValue)); } diff --git a/src/tools/illink/src/ILLink.Shared/TrimAnalysis/HandleCallAction.cs b/src/tools/illink/src/ILLink.Shared/TrimAnalysis/HandleCallAction.cs index c6b8e73a93ba8c..9b8ff45110f26f 100644 --- a/src/tools/illink/src/ILLink.Shared/TrimAnalysis/HandleCallAction.cs +++ b/src/tools/illink/src/ILLink.Shared/TrimAnalysis/HandleCallAction.cs @@ -1132,7 +1132,7 @@ ValueWithDynamicallyAccessedMembers valueWithDynamicallyAccessedMembers } if (calledMethod.GetMetadataParametersCount () > 3) { - if (argumentValues[1].AsConstInt () is int constInt) + if (argumentValues[1].AsConstInt () is { } constInt) bindingFlags |= (BindingFlags) constInt; else bindingFlags |= BindingFlags.NonPublic | BindingFlags.Public; @@ -1372,7 +1372,7 @@ private void ProcessCreateInstanceByName (MethodProxy calledMethod, IReadOnlyLis if (calledMethod.HasMetadataParametersCount (8) && calledMethod.HasParameterOfType ((ParameterIndex) 2 + offset, "System.Boolean")) { parameterlessConstructor = false; bindingFlags = BindingFlags.Instance; - if (argumentValues[3].AsConstInt () is int bindingFlagsInt) + if (argumentValues[3].AsConstInt () is { } bindingFlagsInt) bindingFlags |= (BindingFlags) bindingFlagsInt; else bindingFlags |= BindingFlags.Public | BindingFlags.NonPublic; @@ -1380,7 +1380,7 @@ private void ProcessCreateInstanceByName (MethodProxy calledMethod, IReadOnlyLis foreach (var assemblyNameValue in argumentValues[0].AsEnumerable ()) { if (assemblyNameValue is KnownStringValue assemblyNameStringValue) { - if (assemblyNameStringValue.Contents is string assemblyName && assemblyName.Length == 0) { + if (assemblyNameStringValue.Contents is { } assemblyName && assemblyName.Length == 0) { // Throws exception for zero-length assembly name. continue; } diff --git a/src/tools/illink/src/ILLink.Tasks/LinkTask.cs b/src/tools/illink/src/ILLink.Tasks/LinkTask.cs index a14f775ebe4517..68b0574cdf0997 100644 --- a/src/tools/illink/src/ILLink.Tasks/LinkTask.cs +++ b/src/tools/illink/src/ILLink.Tasks/LinkTask.cs @@ -323,7 +323,7 @@ protected override string GenerateResponseFileCommands () args.AppendLine (); } - if (_singleWarn is bool generalSingleWarn) { + if (_singleWarn is { } generalSingleWarn) { if (generalSingleWarn) args.AppendLine ("--singlewarn"); else @@ -428,7 +428,7 @@ protected override string GenerateResponseFileCommands () if (Warn != null) args.Append ("--warn ").AppendLine (Quote (Warn)); - if (_treatWarningsAsErrors is bool treatWarningsAsErrors && treatWarningsAsErrors) + if (_treatWarningsAsErrors is { } treatWarningsAsErrors && treatWarningsAsErrors) args.Append ("--warnaserror "); else args.Append ("--warnaserror- "); @@ -440,22 +440,22 @@ protected override string GenerateResponseFileCommands () args.Append ("--warnaserror- ").AppendLine (Quote (WarningsNotAsErrors)); // Add global optimization arguments - if (_beforeFieldInit is bool beforeFieldInit) + if (_beforeFieldInit is { } beforeFieldInit) SetOpt (args, "beforefieldinit", beforeFieldInit); - if (_overrideRemoval is bool overrideRemoval) + if (_overrideRemoval is { } overrideRemoval) SetOpt (args, "overrideremoval", overrideRemoval); - if (_unreachableBodies is bool unreachableBodies) + if (_unreachableBodies is { } unreachableBodies) SetOpt (args, "unreachablebodies", unreachableBodies); - if (_unusedInterfaces is bool unusedInterfaces) + if (_unusedInterfaces is { } unusedInterfaces) SetOpt (args, "unusedinterfaces", unusedInterfaces); - if (_iPConstProp is bool iPConstProp) + if (_iPConstProp is { } iPConstProp) SetOpt (args, "ipconstprop", iPConstProp); - if (_sealer is bool sealer) + if (_sealer is { } sealer) SetOpt (args, "sealer", sealer); if (CustomData != null) { diff --git a/src/tools/illink/src/linker/Linker.Dataflow/CompilerGeneratedState.cs b/src/tools/illink/src/linker/Linker.Dataflow/CompilerGeneratedState.cs index d246e4a6c54e1d..8fc52a99acf0e0 100644 --- a/src/tools/illink/src/linker/Linker.Dataflow/CompilerGeneratedState.cs +++ b/src/tools/illink/src/linker/Linker.Dataflow/CompilerGeneratedState.cs @@ -74,7 +74,7 @@ public static bool IsNestedFunctionOrStateMachineMember (IMemberDefinition membe if (member is MethodDefinition method && CompilerGeneratedNames.IsLambdaOrLocalFunction (method.Name)) return true; - if (member.DeclaringType is not TypeDefinition declaringType) + if (member.DeclaringType is not { } declaringType) return false; return CompilerGeneratedNames.IsStateMachineType (declaringType.Name); diff --git a/src/tools/illink/src/linker/Linker.Dataflow/DynamicallyAccessedMembersBinder.cs b/src/tools/illink/src/linker/Linker.Dataflow/DynamicallyAccessedMembersBinder.cs index 9c2f276cb0f49c..2996b777d46311 100644 --- a/src/tools/illink/src/linker/Linker.Dataflow/DynamicallyAccessedMembersBinder.cs +++ b/src/tools/illink/src/linker/Linker.Dataflow/DynamicallyAccessedMembersBinder.cs @@ -230,7 +230,7 @@ public static IEnumerable GetFieldsOnTypeHierarchy (this TypeDe public static IEnumerable GetNestedTypesOnType (this TypeReference typeRef, LinkContext context, Func? filter, BindingFlags? bindingFlags = BindingFlags.Default) { - if (typeRef.ResolveToTypeDefinition (context) is not TypeDefinition type) + if (typeRef.ResolveToTypeDefinition (context) is not { } type) yield break; foreach (var nestedType in type.NestedTypes) { diff --git a/src/tools/illink/src/linker/Linker.Dataflow/FlowAnnotations.cs b/src/tools/illink/src/linker/Linker.Dataflow/FlowAnnotations.cs index d8cee744c9c6b4..3b2c15c4285514 100644 --- a/src/tools/illink/src/linker/Linker.Dataflow/FlowAnnotations.cs +++ b/src/tools/illink/src/linker/Linker.Dataflow/FlowAnnotations.cs @@ -29,7 +29,7 @@ public FlowAnnotations (LinkContext context) public bool RequiresDataFlowAnalysis (MethodReference methodRef) { - if (_context.TryResolve (methodRef) is not MethodDefinition method) + if (_context.TryResolve (methodRef) is not { } method) return false; return GetAnnotations (method.DeclaringType).TryGetAnnotation (method, out var methodAnnotations) @@ -47,7 +47,7 @@ public bool RequiresGenericArgumentDataFlowAnalysis (GenericParameter genericPar internal DynamicallyAccessedMemberTypes GetParameterAnnotation (ParameterProxy param) { - if (_context.TryResolve (param.Method.Method) is not MethodDefinition methodDef) + if (_context.TryResolve (param.Method.Method) is not { } methodDef) return DynamicallyAccessedMemberTypes.None; if (GetAnnotations (methodDef.DeclaringType).TryGetAnnotation (methodDef, out var annotation) && @@ -59,7 +59,7 @@ internal DynamicallyAccessedMemberTypes GetParameterAnnotation (ParameterProxy p public DynamicallyAccessedMemberTypes GetReturnParameterAnnotation (MethodReference methodRef) { - if (_context.TryResolve (methodRef) is not MethodDefinition method) + if (_context.TryResolve (methodRef) is not { } method) return DynamicallyAccessedMemberTypes.None; if (GetAnnotations (method.DeclaringType).TryGetAnnotation (method, out var annotation)) @@ -70,7 +70,7 @@ public DynamicallyAccessedMemberTypes GetReturnParameterAnnotation (MethodRefere public DynamicallyAccessedMemberTypes GetFieldAnnotation (FieldReference fieldRef) { - if (_context.TryResolve (fieldRef) is not FieldDefinition field) + if (_context.TryResolve (fieldRef) is not { } field) return DynamicallyAccessedMemberTypes.None; if (GetAnnotations (field.DeclaringType).TryGetAnnotation (field, out var annotation)) @@ -765,7 +765,7 @@ internal SingleValue GetTypeValueFromGenericArgument (TypeReference genericArgum // Technically this should be a new value node type as it's not a System.Type instance representation, but just the generic parameter // That said we only use it to perform the dynamically accessed members checks and for that purpose treating it as System.Type is perfectly valid. return GetGenericParameterValue (inputGenericParameter); - } else if (genericArgument.ResolveToTypeDefinition (_context) is TypeDefinition genericArgumentType) { + } else if (genericArgument.ResolveToTypeDefinition (_context) is { } genericArgumentType) { if (genericArgumentType.IsTypeOf (WellKnownType.System_Nullable_T)) { var innerGenericArgument = (genericArgument as IGenericInstance)?.GenericArguments.FirstOrDefault (); switch (innerGenericArgument) { @@ -773,8 +773,8 @@ internal SingleValue GetTypeValueFromGenericArgument (TypeReference genericArgum return new NullableValueWithDynamicallyAccessedMembers (new (genericArgumentType, _context), new GenericParameterValue (gp, _context.Annotations.FlowAnnotations.GetGenericParameterAnnotation (gp))); - case TypeReference underlyingType: - if (underlyingType.ResolveToTypeDefinition (_context) is TypeDefinition underlyingTypeDefinition) + case { } underlyingType: + if (underlyingType.ResolveToTypeDefinition (_context) is { } underlyingTypeDefinition) return new NullableSystemTypeValue (new (genericArgumentType, _context), new SystemTypeValue (new (underlyingTypeDefinition, _context))); else return UnknownValue.Instance; diff --git a/src/tools/illink/src/linker/Linker.Dataflow/HandleCallAction.cs b/src/tools/illink/src/linker/Linker.Dataflow/HandleCallAction.cs index cce064ff93980d..dfe3b47a92e444 100644 --- a/src/tools/illink/src/linker/Linker.Dataflow/HandleCallAction.cs +++ b/src/tools/illink/src/linker/Linker.Dataflow/HandleCallAction.cs @@ -225,7 +225,7 @@ private partial IEnumerable GetNestedTypesOnType (TypeProxy typ private partial bool TryGetBaseType (TypeProxy type, out TypeProxy? baseType) { - if (type.Type.ResolveToTypeDefinition (_context)?.BaseType is TypeReference baseTypeRef && _context.TryResolve (baseTypeRef) is TypeDefinition baseTypeDefinition) { + if (type.Type.ResolveToTypeDefinition (_context)?.BaseType is { } baseTypeRef && _context.TryResolve (baseTypeRef) is { } baseTypeDefinition) { baseType = new TypeProxy (baseTypeDefinition, _context); return true; } diff --git a/src/tools/illink/src/linker/Linker.Dataflow/InterproceduralState.cs b/src/tools/illink/src/linker/Linker.Dataflow/InterproceduralState.cs index 8ab34d80191958..1fa862f0253196 100644 --- a/src/tools/illink/src/linker/Linker.Dataflow/InterproceduralState.cs +++ b/src/tools/illink/src/linker/Linker.Dataflow/InterproceduralState.cs @@ -39,7 +39,7 @@ public InterproceduralState Clone () public void TrackMethod (MethodDefinition method) { - if (method.Body is not MethodBody methodBody) + if (method.Body is not { } methodBody) return; TrackMethod (methodBody); @@ -63,7 +63,7 @@ public void TrackMethod (MethodIL methodIL) if (CompilerGeneratedState.TryGetStateMachineType (methodIL.Method, out TypeDefinition? stateMachineType)) { foreach (var stateMachineMethod in stateMachineType.Methods) { Debug.Assert (!CompilerGeneratedNames.IsLambdaOrLocalFunction (stateMachineMethod.Name)); - if (stateMachineMethod.Body is MethodBody stateMachineMethodBody) + if (stateMachineMethod.Body is { } stateMachineMethodBody) methodsList.Add (lattice.Context.GetMethodIL (stateMachineMethodBody)); } } diff --git a/src/tools/illink/src/linker/Linker.Dataflow/MethodBodyScanner.cs b/src/tools/illink/src/linker/Linker.Dataflow/MethodBodyScanner.cs index 849342bbe395f3..e3ebee5e1178be 100644 --- a/src/tools/illink/src/linker/Linker.Dataflow/MethodBodyScanner.cs +++ b/src/tools/illink/src/linker/Linker.Dataflow/MethodBodyScanner.cs @@ -264,7 +264,7 @@ public virtual void InterproceduralScan (MethodIL startingMethodIL) void TrackNestedFunctionReference (MethodReference referencedMethod, ref InterproceduralState interproceduralState) { - if (_context.TryResolve (referencedMethod) is not MethodDefinition method) + if (_context.TryResolve (referencedMethod) is not { } method) return; if (!CompilerGeneratedNames.IsLambdaOrLocalFunction (method.Name)) @@ -786,7 +786,7 @@ void ScanLdtoken (Instruction operation, Stack currentStack) var param = new RuntimeTypeHandleForGenericParameterValue (genericParameter); currentStack.Push (new StackSlot (param)); return; - case TypeReference typeReference when ResolveToTypeDefinition (typeReference) is TypeDefinition resolvedDefinition: + case TypeReference typeReference when ResolveToTypeDefinition (typeReference) is { } resolvedDefinition: // Note that Nullable types without a generic argument (i.e. Nullable<>) will be RuntimeTypeHandleValue / SystemTypeValue if (typeReference is IGenericInstance instance && resolvedDefinition.IsTypeOf (WellKnownType.System_Nullable_T)) { switch (instance.GenericArguments[0]) { @@ -795,7 +795,7 @@ void ScanLdtoken (Instruction operation, Stack currentStack) new RuntimeTypeHandleForGenericParameterValue (genericParam)); currentStack.Push (new StackSlot (nullableDam)); return; - case TypeReference underlyingTypeReference when ResolveToTypeDefinition (underlyingTypeReference) is TypeDefinition underlyingType: + case { } underlyingTypeReference when ResolveToTypeDefinition (underlyingTypeReference) is { } underlyingType: var nullableType = new RuntimeTypeHandleForNullableSystemTypeValue (new TypeProxy (resolvedDefinition, _context), new SystemTypeValue (new (underlyingType, _context))); currentStack.Push (new StackSlot (nullableType)); return; @@ -808,7 +808,7 @@ void ScanLdtoken (Instruction operation, Stack currentStack) currentStack.Push (new StackSlot (typeHandle)); return; } - case MethodReference methodReference when _context.TryResolve (methodReference) is MethodDefinition resolvedMethod: + case MethodReference methodReference when _context.TryResolve (methodReference) is { } resolvedMethod: var method = new RuntimeMethodHandleValue (resolvedMethod); currentStack.Push (new StackSlot (method)); return; diff --git a/src/tools/illink/src/linker/Linker.Dataflow/MethodProxy.cs b/src/tools/illink/src/linker/Linker.Dataflow/MethodProxy.cs index 440d050296406b..de6b2a3f55eab0 100644 --- a/src/tools/illink/src/linker/Linker.Dataflow/MethodProxy.cs +++ b/src/tools/illink/src/linker/Linker.Dataflow/MethodProxy.cs @@ -13,7 +13,7 @@ namespace ILLink.Shared.TypeSystemProxy { public static bool TryCreate (MethodReference method, ITryResolveMetadata resolver, [NotNullWhen (true)] out MethodProxy? methodProxy) { - if (resolver.TryResolve (method) is not MethodDefinition methodDef) { + if (resolver.TryResolve (method) is not { } methodDef) { methodProxy = null; return false; } diff --git a/src/tools/illink/src/linker/Linker.Dataflow/ReflectionMarker.cs b/src/tools/illink/src/linker/Linker.Dataflow/ReflectionMarker.cs index b58b63f16f69f9..7253aaaf8239cf 100644 --- a/src/tools/illink/src/linker/Linker.Dataflow/ReflectionMarker.cs +++ b/src/tools/illink/src/linker/Linker.Dataflow/ReflectionMarker.cs @@ -29,7 +29,7 @@ internal void MarkTypeForDynamicallyAccessedMembers (in MessageOrigin origin, Ty if (!_enabled) return; - if (type.ResolveToTypeDefinition (_context) is not TypeDefinition typeDefinition) + if (type.ResolveToTypeDefinition (_context) is not { } typeDefinition) return; foreach (var member in typeDefinition.GetDynamicallyAccessedMembers (_context, requiredMemberTypes, declaredOnly)) { @@ -105,7 +105,7 @@ internal void MarkType (in MessageOrigin origin, TypeReference typeRef, Dependen if (!_enabled) return; - if (typeRef.ResolveToTypeDefinition (_context) is not TypeDefinition type) + if (typeRef.ResolveToTypeDefinition (_context) is not { } type) return; _markStep.MarkTypeVisibleToReflection (type, new DependencyInfo (dependencyKind, origin.Provider), origin); @@ -116,7 +116,7 @@ internal void MarkMethod (in MessageOrigin origin, MethodReference methodRef, De if (!_enabled) return; - if (_context.TryResolve (methodRef) is not MethodDefinition method) + if (_context.TryResolve (methodRef) is not { } method) return; _markStep.MarkMethodVisibleToReflection (method, new DependencyInfo (dependencyKind, origin.Provider), origin); @@ -159,7 +159,7 @@ internal void MarkConstructorsOnType (in MessageOrigin origin, TypeReference typ if (!_enabled) return; - if (typeRef.ResolveToTypeDefinition (_context) is not TypeDefinition type) + if (typeRef.ResolveToTypeDefinition (_context) is not { } type) return; foreach (var ctor in type.GetConstructorsOnType (filter, bindingFlags)) @@ -171,7 +171,7 @@ internal void MarkFieldsOnTypeHierarchy (in MessageOrigin origin, TypeReference if (!_enabled) return; - if (typeRef.ResolveToTypeDefinition (_context) is not TypeDefinition type) + if (typeRef.ResolveToTypeDefinition (_context) is not { } type) return; foreach (var field in type.GetFieldsOnTypeHierarchy (_context, filter, bindingFlags)) @@ -183,7 +183,7 @@ internal void MarkPropertiesOnTypeHierarchy (in MessageOrigin origin, TypeRefere if (!_enabled) return; - if (typeRef.ResolveToTypeDefinition (_context) is not TypeDefinition type) + if (typeRef.ResolveToTypeDefinition (_context) is not { } type) return; foreach (var property in type.GetPropertiesOnTypeHierarchy (_context, filter, bindingFlags)) @@ -195,7 +195,7 @@ internal void MarkEventsOnTypeHierarchy (in MessageOrigin origin, TypeReference if (!_enabled) return; - if (typeRef.ResolveToTypeDefinition (_context) is not TypeDefinition type) + if (typeRef.ResolveToTypeDefinition (_context) is not { } type) return; foreach (var @event in type.GetEventsOnTypeHierarchy (_context, filter, bindingFlags)) @@ -207,7 +207,7 @@ internal void MarkStaticConstructor (in MessageOrigin origin, TypeReference type if (!_enabled) return; - if (typeRef.ResolveToTypeDefinition (_context) is not TypeDefinition type) + if (typeRef.ResolveToTypeDefinition (_context) is not { } type) return; _markStep.MarkStaticConstructorVisibleToReflection (type, new DependencyInfo (DependencyKind.AccessedViaReflection, origin.Provider), origin); diff --git a/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs b/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs index 1309e7526d6834..dc6dd522c18557 100644 --- a/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs +++ b/src/tools/illink/src/linker/Linker.Steps/LinkAttributesParser.cs @@ -103,7 +103,7 @@ static string FormatCustomAttribute (CustomAttribute ca) { TypeDefinition? td = null; - if (_context.MarkedKnownMembers.RemoveAttributeInstancesAttributeDefinition is TypeDefinition knownTypeDef) { + if (_context.MarkedKnownMembers.RemoveAttributeInstancesAttributeDefinition is { } knownTypeDef) { return knownTypeDef; } @@ -308,7 +308,7 @@ CustomAttributeArgument[] ReadCustomAttributeArguments (XPathNavigator nav, ICus var arrayArgumentIterator = nav.SelectChildren ("argument", string.Empty); ArrayBuilder elements = default; foreach (XPathNavigator elementNav in arrayArgumentIterator) { - if (ReadCustomAttributeArgument (elementNav, provider) is CustomAttributeArgument arg) { + if (ReadCustomAttributeArgument (elementNav, provider) is { } arg) { // To match Cecil, elements of a list that are subclasses of the list type must be boxed in the base type // e.g. object[] { 73 } translates to Cecil.CAA { Type: object[] : Value: CAA{ Type: object, Value: CAA{ Type: int, Value: 73} } } if (arg.Type == elementType) { diff --git a/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs b/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs index 84a4f26a983ecd..e5f33c17f2a63b 100644 --- a/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs +++ b/src/tools/illink/src/linker/Linker.Steps/MarkStep.cs @@ -866,7 +866,7 @@ void MarkDynamicDependency (DynamicDependency dynamicDependency, IMemberDefiniti } TypeDefinition? type; - if (dynamicDependency.TypeName is string typeName) { + if (dynamicDependency.TypeName is { } typeName) { type = DocumentationSignatureParser.GetTypeByDocumentationSignature (assembly, typeName, Context); if (type == null) { Context.LogWarning (origin, DiagnosticId.UnresolvedTypeInDynamicDependencyAttribute, typeName); @@ -874,7 +874,7 @@ void MarkDynamicDependency (DynamicDependency dynamicDependency, IMemberDefiniti } MarkingHelpers.MarkMatchingExportedType (type, assembly, new DependencyInfo (DependencyKind.DynamicDependency, type), origin); - } else if (dynamicDependency.Type is TypeReference typeReference) { + } else if (dynamicDependency.Type is { } typeReference) { type = Context.TryResolve (typeReference); if (type == null) { Context.LogWarning (origin, DiagnosticId.UnresolvedTypeInDynamicDependencyAttribute, typeReference.GetDisplayName ()); @@ -889,7 +889,7 @@ void MarkDynamicDependency (DynamicDependency dynamicDependency, IMemberDefiniti } IEnumerable members; - if (dynamicDependency.MemberSignature is string memberSignature) { + if (dynamicDependency.MemberSignature is { } memberSignature) { members = DocumentationSignatureParser.GetMembersByDocumentationSignature (type, memberSignature, Context, acceptName: true); if (!members.Any ()) { Context.LogWarning (origin, DiagnosticId.NoMembersResolvedForMemberSignatureOrType, memberSignature, type.GetDisplayName ()); @@ -1810,7 +1810,7 @@ protected internal virtual void MarkTypeVisibleToReflection (TypeReference type, internal void MarkMethodVisibleToReflection (MethodReference method, in DependencyInfo reason, in MessageOrigin origin) { MarkMethod (method, reason, origin); - if (Context.Resolve (method) is MethodDefinition methodDefinition) { + if (Context.Resolve (method) is { } methodDefinition) { Annotations.MarkReflectionUsed (methodDefinition); Annotations.MarkIndirectlyCalledMethod (methodDefinition); } @@ -1961,7 +1961,7 @@ internal void MarkStaticConstructorVisibleToReflection (TypeDefinition type, in MarkCustomAttributes (type, new DependencyInfo (DependencyKind.CustomAttribute, type), typeOrigin); MarkSecurityDeclarations (type, new DependencyInfo (DependencyKind.CustomAttribute, type), typeOrigin); - if (Context.TryResolve (type.BaseType) is TypeDefinition baseType && + if (Context.TryResolve (type.BaseType) is { } baseType && !Annotations.HasLinkerAttribute (type) && Annotations.TryGetLinkerAttribute (baseType, out RequiresUnreferencedCodeAttribute? effectiveRequiresUnreferencedCode)) { @@ -2221,7 +2221,7 @@ void MarkTypeWithDebuggerDisplayAttributeValue (TypeDefinition type, CustomAttri // This can be improved: dotnet/linker/issues/1873 MarkMethodsVisibleToReflection (type, new DependencyInfo (DependencyKind.KeptForSpecialAttribute, attribute), origin); MarkFieldsVisibleToReflection (type, new DependencyInfo (DependencyKind.ReferencedBySpecialAttribute, attribute), origin); - if (Context.TryResolve (type.BaseType) is not TypeDefinition baseType) + if (Context.TryResolve (type.BaseType) is not { } baseType) break; type = baseType; } @@ -2247,7 +2247,7 @@ void MarkTypeWithDebuggerTypeProxyAttribute (TypeDefinition type, CustomAttribut Tracer.AddDirectDependency (attribute, new DependencyInfo (DependencyKind.CustomAttribute, type), marked: false); MarkType (proxyTypeReference, new DependencyInfo (DependencyKind.ReferencedBySpecialAttribute, attribute), origin); - if (Context.TryResolve (proxyTypeReference) is TypeDefinition proxyType) { + if (Context.TryResolve (proxyTypeReference) is { } proxyType) { MarkMethodsVisibleToReflection (proxyType, new DependencyInfo (DependencyKind.ReferencedBySpecialAttribute, attribute), origin); MarkFieldsVisibleToReflection (proxyType, new DependencyInfo (DependencyKind.ReferencedBySpecialAttribute, attribute), origin); } @@ -2345,7 +2345,7 @@ protected virtual bool ShouldMarkInterfaceImplementationList (TypeDefinition typ if (!Context.IsOptimizationEnabled (CodeOptimizations.UnusedInterfaces, type)) return true; - if (Context.Resolve (ifaceType) is not TypeDefinition resolvedInterfaceType) + if (Context.Resolve (ifaceType) is not { } resolvedInterfaceType) return false; if (Annotations.IsMarked (resolvedInterfaceType)) @@ -2872,7 +2872,7 @@ void MarkMethodCollection (IList methods, in DependencyInfo re if (reference.DeclaringType is ArrayType arrayType) { MarkType (reference.DeclaringType, new DependencyInfo (DependencyKind.DeclaringType, reference), origin); - if (reference.Name == ".ctor" && Context.TryResolve (arrayType) is TypeDefinition typeDefinition) { + if (reference.Name == ".ctor" && Context.TryResolve (arrayType) is { } typeDefinition) { Annotations.MarkRelevantToVariantCasting (typeDefinition); } return null; @@ -3116,7 +3116,7 @@ protected virtual void ProcessMethod (MethodDefinition method, in DependencyInfo // Calling the implementation method directly has no impact on the interface, and as such it should not mark the interface or its method. // Only if the interface method is referenced, then all the methods which implemented must be kept, but not the other way round. if (!markAllOverrides && - Context.Resolve (@base) is MethodDefinition baseDefinition + Context.Resolve (@base) is { } baseDefinition && baseDefinition.DeclaringType.IsInterface && baseDefinition.IsStatic && method.IsStatic) continue; // Instance methods can have overrides on public implementation methods in IL, but C# will usually only have them for private explicit interface implementations. @@ -3137,7 +3137,7 @@ protected virtual void ProcessMethod (MethodDefinition method, in DependencyInfo MarkBaseMethods (method, methodOrigin); - if (Annotations.GetOverrides (method) is IEnumerable overrides) { + if (Annotations.GetOverrides (method) is { } overrides) { foreach (var @override in overrides.Where (ov => Annotations.IsMarked (ov.Base) || IgnoreScope (ov.Base.DeclaringType.Scope))) { if (ShouldMarkOverrideForBase (@override)) MarkOverrideForBaseMethod (@override, methodOrigin); @@ -3242,7 +3242,7 @@ protected virtual void MarkRequirementsForInstantiatedTypes (TypeDefinition type void MarkRuntimeInterfaceImplementation (MethodDefinition method, MethodReference ov) { - if (Context.Resolve (ov) is not MethodDefinition resolvedOverride) + if (Context.Resolve (ov) is not { } resolvedOverride) return; if (!resolvedOverride.DeclaringType.IsInterface) return; @@ -3654,7 +3654,7 @@ protected virtual void MarkInstruction (Instruction instruction, MethodDefinitio var operand = (TypeReference) instruction.Operand; switch (instruction.OpCode.Code) { case Code.Newarr: - if (Context.TryResolve (operand) is TypeDefinition typeDefinition) { + if (Context.TryResolve (operand) is { } typeDefinition) { Annotations.MarkRelevantToVariantCasting (typeDefinition); } break; @@ -3727,12 +3727,12 @@ protected virtual void MarkReflectionLikeDependencies (MethodIL methodIL, bool r foreach (var compilerGeneratedCallee in compilerGeneratedCallees) { switch (compilerGeneratedCallee) { case MethodDefinition nestedFunction: - if (nestedFunction.Body is MethodBody nestedBody) + if (nestedFunction.Body is { } nestedBody) requiresReflectionMethodBodyScanner |= MarkAndCheckRequiresReflectionMethodBodyScanner (Context.GetMethodIL (nestedBody), origin); break; case TypeDefinition stateMachineType: foreach (var method in stateMachineType.Methods) { - if (method.Body is MethodBody stateMachineBody) + if (method.Body is { } stateMachineBody) requiresReflectionMethodBodyScanner |= MarkAndCheckRequiresReflectionMethodBodyScanner (Context.GetMethodIL (stateMachineBody), origin); } break; diff --git a/src/tools/illink/src/linker/Linker.Steps/ProcessLinkerXmlBase.cs b/src/tools/illink/src/linker/Linker.Steps/ProcessLinkerXmlBase.cs index e96ce5a22f5250..16bfb0decf18d7 100644 --- a/src/tools/illink/src/linker/Linker.Steps/ProcessLinkerXmlBase.cs +++ b/src/tools/illink/src/linker/Linker.Steps/ProcessLinkerXmlBase.cs @@ -573,7 +573,7 @@ public bool TryConvertValue (string value, TypeReference target, out object? res return true; case MetadataType.String: - if (value is string || value == null) { + if (value is not null || value == null) { result = value; return true; } @@ -581,8 +581,8 @@ public bool TryConvertValue (string value, TypeReference target, out object? res break; case MetadataType.ValueType: - if (value is string && - _context.TryResolve (target) is TypeDefinition typeDefinition && + if (value is not null && + _context.TryResolve (target) is { } typeDefinition && typeDefinition.IsEnum) { var enumField = typeDefinition.Fields.Where (f => f.IsStatic && f.Name == value).FirstOrDefault (); if (enumField != null) { diff --git a/src/tools/illink/src/linker/Linker.Steps/SweepStep.cs b/src/tools/illink/src/linker/Linker.Steps/SweepStep.cs index eb3a8fa0f55fc4..80091b7f47a565 100644 --- a/src/tools/illink/src/linker/Linker.Steps/SweepStep.cs +++ b/src/tools/illink/src/linker/Linker.Steps/SweepStep.cs @@ -465,7 +465,7 @@ void SweepOverrides (MethodDefinition method) // OR // ov is an interface method and the interface is not implemented by the type #pragma warning disable RS0030 // Cecil's Resolve is banned - it's necessary when the metadata graph isn't stable - if (method.Overrides[i].Resolve () is not MethodDefinition ov + if (method.Overrides[i].Resolve () is not { } ov || ov.DeclaringType is null || (IsLinkScope (ov.DeclaringType.Scope) && ShouldRemove (ov)) || (ov.DeclaringType.IsInterface && !MarkStep.IsInterfaceImplementationMarkedRecursively (method.DeclaringType, ov.DeclaringType, Context))) diff --git a/src/tools/illink/src/linker/Linker.Steps/UnreachableBlocksOptimizer.cs b/src/tools/illink/src/linker/Linker.Steps/UnreachableBlocksOptimizer.cs index 295d740874cb91..65fcab798a9af5 100644 --- a/src/tools/illink/src/linker/Linker.Steps/UnreachableBlocksOptimizer.cs +++ b/src/tools/illink/src/linker/Linker.Steps/UnreachableBlocksOptimizer.cs @@ -99,7 +99,7 @@ static bool HasJumpIntoTargetRange (Collection instructions, int fi case FlowControl.Branch: case FlowControl.Cond_Branch: if (instr.Operand is Instruction target) { - if (mapping != null && mapping (target) is int index) { + if (mapping != null && mapping (target) is { } index) { if (index >= firstInstr && index <= lastInstr) { return true; } @@ -113,7 +113,7 @@ static bool HasJumpIntoTargetRange (Collection instructions, int fi } } else { foreach (var rtarget in (Instruction[]) instr.Operand) { - if (mapping != null && mapping (rtarget) is int index) { + if (mapping != null && mapping (rtarget) is { } index) { if (index >= firstInstr && index <= lastInstr) { return true; } @@ -480,7 +480,7 @@ public bool RewriteBody () var cpl = new CalleePayload (md, GetArgumentsOnStack (md, instrs, i)); MethodResult? call_result = optimizer.TryGetMethodCallResult (cpl); - if (call_result is not MethodResult result) + if (call_result is not { } result) break; if (!result.IsSideEffectFree) { @@ -1817,7 +1817,7 @@ public bool Analyze (in CalleePayload callee, Stack callStack) if (!callStack.TryPop (out _)) return false; - if (call_result is MethodResult result) { + if (call_result is { } result) { if (!result.IsSideEffectFree) SideEffectFreeResult = false; diff --git a/src/tools/illink/src/linker/Linker.Steps/UnsafeAccessorMarker.cs b/src/tools/illink/src/linker/Linker.Steps/UnsafeAccessorMarker.cs index d6155b8a50b5e1..bc8ff6147b4bf1 100644 --- a/src/tools/illink/src/linker/Linker.Steps/UnsafeAccessorMarker.cs +++ b/src/tools/illink/src/linker/Linker.Steps/UnsafeAccessorMarker.cs @@ -76,7 +76,7 @@ void ProcessConstructorAccessor (MethodDefinition method, string? name) if (method.ReturnsVoid () || method.ReturnType.IsByRefOrPointer () || !string.IsNullOrEmpty (name)) return; - if (_context.TryResolve (method.ReturnType) is not TypeDefinition targetType) + if (_context.TryResolve (method.ReturnType) is not { } targetType) return; foreach (MethodDefinition targetMethod in targetType.Methods) { @@ -97,7 +97,7 @@ void ProcessMethodAccessor (MethodDefinition method, string? name, bool isStatic name = method.Name; TypeReference targetTypeReference = method.Parameters[0].ParameterType; - if (_context.TryResolve (targetTypeReference) is not TypeDefinition targetType) + if (_context.TryResolve (targetTypeReference) is not { } targetType) return; if (!isStatic && targetType.IsValueType && !targetTypeReference.IsByReference) @@ -124,7 +124,7 @@ void ProcessFieldAccessor (MethodDefinition method, string? name, bool isStatic) return; TypeReference targetTypeReference = method.Parameters[0].ParameterType; - if (_context.TryResolve (targetTypeReference) is not TypeDefinition targetType) + if (_context.TryResolve (targetTypeReference) is not { } targetType) return; if (!isStatic && targetType.IsValueType && !targetTypeReference.IsByReference) diff --git a/src/tools/illink/src/linker/Linker/LinkContext.cs b/src/tools/illink/src/linker/Linker/LinkContext.cs index 0301f76f0a9f55..e67032d13eafc3 100644 --- a/src/tools/illink/src/linker/Linker/LinkContext.cs +++ b/src/tools/illink/src/linker/Linker/LinkContext.cs @@ -538,7 +538,7 @@ public void LogMessage (MessageContainer message) if (WarningSuppressionWriter != null && message.IsWarningMessage (out int? code) && - message.Origin?.Provider is Mono.Cecil.ICustomAttributeProvider provider) + message.Origin?.Provider is { } provider) WarningSuppressionWriter.AddWarning (code.Value, provider); if (message.Category == MessageCategory.Error || message.Category == MessageCategory.WarningAsError) @@ -946,7 +946,7 @@ public int GetTargetRuntimeVersion () /// public TypeDefinition? Resolve (ExportedType et) { - if (TryResolve (et) is not TypeDefinition td) { + if (TryResolve (et) is not { } td) { ReportUnresolved (et); return null; } diff --git a/src/tools/illink/src/linker/Linker/MarkingHelpers.cs b/src/tools/illink/src/linker/Linker/MarkingHelpers.cs index 746722625ecd88..7804345e936775 100644 --- a/src/tools/illink/src/linker/Linker/MarkingHelpers.cs +++ b/src/tools/illink/src/linker/Linker/MarkingHelpers.cs @@ -39,7 +39,7 @@ public void MarkForwardedScope (TypeReference typeReference, in MessageOrigin or if (typeReference.Scope is AssemblyNameReference) { var assembly = _context.Resolve (typeReference.Scope); if (assembly != null && - _context.TryResolve (typeReference) is TypeDefinition typeDefinition && + _context.TryResolve (typeReference) is { } typeDefinition && assembly.MainModule.GetMatchingExportedType (typeDefinition, _context, out var exportedType)) MarkExportedType (exportedType, assembly.MainModule, new DependencyInfo (DependencyKind.ExportedType, typeReference), origin); } diff --git a/src/tools/illink/src/linker/Linker/MemberActionStore.cs b/src/tools/illink/src/linker/Linker/MemberActionStore.cs index f8eaeccadd264f..78248ab4f885d6 100644 --- a/src/tools/illink/src/linker/Linker/MemberActionStore.cs +++ b/src/tools/illink/src/linker/Linker/MemberActionStore.cs @@ -81,14 +81,14 @@ internal bool TryGetFeatureCheckValue (MethodDefinition method, out bool value) if (method.ReturnType.MetadataType != MetadataType.Boolean) return false; - if (FindProperty (method) is not PropertyDefinition property) + if (FindProperty (method) is not { } property) return false; if (property.SetMethod != null) return false; foreach (var featureSwitchDefinitionAttribute in _context.CustomAttributes.GetCustomAttributes (property, "System.Diagnostics.CodeAnalysis", "FeatureSwitchDefinitionAttribute")) { - if (featureSwitchDefinitionAttribute.ConstructorArguments is not [CustomAttributeArgument { Value: string switchName }]) + if (featureSwitchDefinitionAttribute.ConstructorArguments is not [{ Value: string switchName }]) continue; // If there's a FeatureSwitchDefinition, don't continue looking for FeatureGuard. @@ -104,7 +104,7 @@ internal bool TryGetFeatureCheckValue (MethodDefinition method, out bool value) return false; foreach (var featureGuardAttribute in _context.CustomAttributes.GetCustomAttributes (property, "System.Diagnostics.CodeAnalysis", "FeatureGuardAttribute")) { - if (featureGuardAttribute.ConstructorArguments is not [CustomAttributeArgument { Value: TypeReference featureType }]) + if (featureGuardAttribute.ConstructorArguments is not [{ Value: TypeReference featureType }]) continue; if (featureType.Namespace == "System.Diagnostics.CodeAnalysis") { diff --git a/src/tools/illink/src/linker/Linker/MethodBodyScanner.cs b/src/tools/illink/src/linker/Linker/MethodBodyScanner.cs index b3a230f1947959..2293864023985a 100644 --- a/src/tools/illink/src/linker/Linker/MethodBodyScanner.cs +++ b/src/tools/illink/src/linker/Linker/MethodBodyScanner.cs @@ -112,7 +112,7 @@ HashSet AllPossibleStackTypes (MethodIL methodIL) foreach (Instruction instruction in methodIL.Instructions) { if (instruction.Operand is FieldReference fieldReference) { - if (context.TryResolve (fieldReference)?.FieldType is TypeReference fieldType) + if (context.TryResolve (fieldReference)?.FieldType is { } fieldType) AddIfResolved (types, fieldType); } else if (instruction.Operand is MethodReference methodReference) { if (methodReference is GenericInstanceMethod genericInstanceMethod) diff --git a/src/tools/illink/src/linker/Linker/MethodDefinitionExtensions.cs b/src/tools/illink/src/linker/Linker/MethodDefinitionExtensions.cs index 0555fbf3cd8450..cd4198d25ac1ed 100644 --- a/src/tools/illink/src/linker/Linker/MethodDefinitionExtensions.cs +++ b/src/tools/illink/src/linker/Linker/MethodDefinitionExtensions.cs @@ -121,7 +121,7 @@ public static void ClearDebugInformation (this MethodDefinition method) /// internal static ParameterProxy GetParameter (this MethodDefinition method, ParameterIndex index) { - if (method.TryGetParameter (index) is not ParameterProxy param) + if (method.TryGetParameter (index) is not { } param) throw new InvalidOperationException ($"Cannot get parameter #{(int) index} of method {method.GetDisplayName ()} with {method.GetParametersCount ()} parameters"); return param; } diff --git a/src/tools/illink/src/linker/Linker/TypeMapInfo.cs b/src/tools/illink/src/linker/Linker/TypeMapInfo.cs index 151a307707dd69..13cbdbec73d7ac 100644 --- a/src/tools/illink/src/linker/Linker/TypeMapInfo.cs +++ b/src/tools/illink/src/linker/Linker/TypeMapInfo.cs @@ -485,8 +485,8 @@ static bool TypeMatch (FunctionPointerType a, FunctionPointerType b) // we need to track what the generic parameter represent - as we cannot allow it to // differ between the return type or any parameter - if (a.ReturnType is not TypeReference aReturnType || - b.ReturnType is not TypeReference bReturnType || + if (a.ReturnType is not { } aReturnType || + b.ReturnType is not { } bReturnType || !TypeMatch (aReturnType, bReturnType)) return false; @@ -499,8 +499,8 @@ b.ReturnType is not TypeReference bReturnType || return false; for (int i = 0; i < ap.Count; i++) { - if (a.Parameters[i].ParameterType is not TypeReference aParameterType || - b.Parameters[i].ParameterType is not TypeReference bParameterType || + if (a.Parameters[i].ParameterType is not { } aParameterType || + b.Parameters[i].ParameterType is not { } bParameterType || !TypeMatch (aParameterType, bParameterType)) return false; } diff --git a/src/tools/illink/src/linker/Linker/TypeNameResolver.cs b/src/tools/illink/src/linker/Linker/TypeNameResolver.cs index aa56f99a2a4f31..d8d1a8f7bb763a 100644 --- a/src/tools/illink/src/linker/Linker/TypeNameResolver.cs +++ b/src/tools/illink/src/linker/Linker/TypeNameResolver.cs @@ -55,7 +55,7 @@ public bool TryResolveTypeName ( return null; AssemblyDefinition? assembly = originalAssembly; - if (typeName.AssemblyName is AssemblyNameInfo assemblyName) + if (typeName.AssemblyName is { } assemblyName) // In this case we ignore the assembly parameter since the type name has assembly in it assembly = _assemblyResolver.TryResolve (assemblyName.Name); diff --git a/src/tools/illink/src/linker/Linker/TypeReferenceExtensions.cs b/src/tools/illink/src/linker/Linker/TypeReferenceExtensions.cs index 7ddb8fe77e5751..54bfda8d049c5b 100644 --- a/src/tools/illink/src/linker/Linker/TypeReferenceExtensions.cs +++ b/src/tools/illink/src/linker/Linker/TypeReferenceExtensions.cs @@ -67,7 +67,7 @@ public static StringBuilder GetDisplayNameWithoutNamespace (this TypeReference t } type = type.GetElementType (); - if (type.DeclaringType is not TypeReference declaringType) + if (type.DeclaringType is not { } declaringType) break; type = declaringType; @@ -153,7 +153,7 @@ void parseArrayDimensions (ArrayType at) public static TypeReference InflateFrom (this TypeReference typeToInflate, IGenericInstance? maybeGenericInstanceProvider) { - if (maybeGenericInstanceProvider is IGenericInstance genericInstanceProvider) + if (maybeGenericInstanceProvider is { } genericInstanceProvider) return InflateGenericType (genericInstanceProvider, typeToInflate); return typeToInflate; } diff --git a/src/tools/illink/src/linker/Linker/TypeReferenceWalker.cs b/src/tools/illink/src/linker/Linker/TypeReferenceWalker.cs index 7b372891203d5b..ffc71a113f81ac 100644 --- a/src/tools/illink/src/linker/Linker/TypeReferenceWalker.cs +++ b/src/tools/illink/src/linker/Linker/TypeReferenceWalker.cs @@ -107,7 +107,7 @@ void WalkScopes (TypeDefinition typeDefinition) if (m.HasBody) WalkTypeScope (m.Body); - if (walkSymbols && m.DebugInformation?.Scope?.Import is ImportDebugInformation import) + if (walkSymbols && m.DebugInformation?.Scope?.Import is { } import) WalkDebugInfoImportScope (import); } } @@ -328,7 +328,7 @@ void WalkDebugInfoImportScope (ImportDebugInformation import) WalkScopeOfTypeReference (target.Type); } - if (import.Parent is ImportDebugInformation parent) + if (import.Parent is { } parent) WalkDebugInfoImportScope (parent); } diff --git a/src/tools/illink/src/linker/Linker/UnconditionalSuppressMessageAttributeState.cs b/src/tools/illink/src/linker/Linker/UnconditionalSuppressMessageAttributeState.cs index 81c3df63647b4e..d9522db1188bca 100644 --- a/src/tools/illink/src/linker/Linker/UnconditionalSuppressMessageAttributeState.cs +++ b/src/tools/illink/src/linker/Linker/UnconditionalSuppressMessageAttributeState.cs @@ -172,7 +172,7 @@ bool TryGetSuppressionsForProvider (ICustomAttributeProvider? provider, out Dict // Gather assembly-level suppressions if we haven't already. To ensure that we always cache // complete information for a member, we will also scan for attributes on any other members // targeted by the assembly-level suppressions. - if (GetModuleFromProvider (provider) is ModuleDefinition module) { + if (GetModuleFromProvider (provider) is { } module) { var assembly = module.Assembly; if (InitializedAssemblies.Add (assembly)) { foreach (var suppression in DecodeAssemblyAndModuleSuppressions (module)) { diff --git a/src/tools/illink/src/linker/Linker/WarningSuppressionWriter.cs b/src/tools/illink/src/linker/Linker/WarningSuppressionWriter.cs index d7a33b87cdcf8f..05ec2bfd12dd4e 100644 --- a/src/tools/illink/src/linker/Linker/WarningSuppressionWriter.cs +++ b/src/tools/illink/src/linker/Linker/WarningSuppressionWriter.cs @@ -33,7 +33,7 @@ public void AddWarning (int code, ICustomAttributeProvider provider) if (provider is not IMemberDefinition memberDefinition) return; - if (UnconditionalSuppressMessageAttributeState.GetModuleFromProvider (provider) is not ModuleDefinition module) + if (UnconditionalSuppressMessageAttributeState.GetModuleFromProvider (provider) is not { } module) return; var assemblyName = module.Assembly.Name;