diff --git a/src/NetAnalyzers/Core/AnalyzerReleases.Unshipped.md b/src/NetAnalyzers/Core/AnalyzerReleases.Unshipped.md index 929f588acd..78144c82c5 100644 --- a/src/NetAnalyzers/Core/AnalyzerReleases.Unshipped.md +++ b/src/NetAnalyzers/Core/AnalyzerReleases.Unshipped.md @@ -13,7 +13,7 @@ CA1857 | Performance | Warning | ConstantExpectedAnalyzer, [Documentation](https CA1858 | Performance | Info | UseStartsWithInsteadOfIndexOfComparisonWithZero, [Documentation](https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1858) CA1859 | Performance | Info | UseConcreteTypeAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1859) CA1860 | Performance | Info | PreferLengthCountIsEmptyOverAnyAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1860) -CA2021 | Reliability | Info | DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2021) +CA2021 | Reliability | Warning | DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2021) ### Removed Rules diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzer.cs index 2dab48d81e..9b5970acae 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzer.cs @@ -30,7 +30,7 @@ public sealed class DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzer s_localizableTitle, s_localizableCastMessage, DiagnosticCategory.Reliability, - RuleLevel.IdeSuggestion, + RuleLevel.BuildWarning, s_localizableDescription, isPortedFxCopRule: false, isDataflowRule: false); @@ -39,7 +39,7 @@ public sealed class DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzer s_localizableTitle, s_localizableOfTypeMessage, DiagnosticCategory.Reliability, - RuleLevel.IdeSuggestion, + RuleLevel.BuildWarning, s_localizableDescription, isPortedFxCopRule: false, isDataflowRule: false); @@ -118,15 +118,28 @@ public override void Initialize(AnalysisContext context) return (operation.Type as IArrayTypeSymbol)?.ElementType; } - if (operation.Type?.OriginalDefinition?.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T) + if (operation.Type.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T) { return GetIEnumerableTParam(operation.Type); } - var r = operation?.Type?.AllInterfaces.FirstOrDefault(t => t.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T); - if (r is not null) + INamedTypeSymbol? enumerableInterface = null; + foreach (var t in operation.Type.AllInterfaces) { - return GetIEnumerableTParam(r); + if (t.OriginalDefinition.SpecialType == SpecialType.System_Collections_Generic_IEnumerable_T) + { + if (enumerableInterface is not null) + { + return null; // if the type implements IEnumerable multiple times, give up + } + + enumerableInterface = t; + } + } + + if (enumerableInterface is not null) + { + return GetIEnumerableTParam(enumerableInterface); } if (operation is IParenthesizedOperation parenthesizedOperation) @@ -170,6 +183,11 @@ public override void Initialize(AnalysisContext context) // as a problem in correctly. We don't want another IDE0004 static bool CastWillAlwaysFail(ITypeSymbol castFrom, ITypeSymbol castTo) { + castFrom = castFrom.GetNullableValueTypeUnderlyingType() + ?? castFrom.GetUnderlyingValueTupleTypeOrThis(); + castTo = castTo.GetNullableValueTypeUnderlyingType() + ?? castTo.GetUnderlyingValueTupleTypeOrThis(); + if (castFrom.TypeKind == TypeKind.Error || castTo.TypeKind == TypeKind.Error) { @@ -189,21 +207,6 @@ static bool CastWillAlwaysFail(ITypeSymbol castFrom, ITypeSymbol castTo) return false; } - static ITypeSymbol UnwrapNullableValueType(ITypeSymbol typeSymbol) - { - if (typeSymbol.IsValueType - && typeSymbol.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T - && ((INamedTypeSymbol)typeSymbol).TypeArguments[0] is var nullableTypeArgument) - { - return nullableTypeArgument; - } - - return typeSymbol; - } - - castFrom = UnwrapNullableValueType(castFrom); - castTo = UnwrapNullableValueType(castTo); - static bool IsUnconstrainedTypeParameter(ITypeParameterSymbol typeParameterSymbol) => !typeParameterSymbol.HasValueTypeConstraint && typeParameterSymbol.ConstraintTypes.IsEmpty; @@ -217,6 +220,10 @@ static bool IsUnconstrainedTypeParameter(ITypeParameterSymbol typeParameterSymbo switch (castFrom.OriginalDefinition.TypeKind, castTo.OriginalDefinition.TypeKind) { + case (TypeKind.Dynamic, _): + case (_, TypeKind.Dynamic): + return false; + case (TypeKind.TypeParameter, _): var castFromTypeParam = (ITypeParameterSymbol)castFrom.OriginalDefinition; if (IsUnconstrainedTypeParameter(castFromTypeParam)) diff --git a/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.md b/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.md index 78a563fdbe..a3ce05bfef 100644 --- a/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.md +++ b/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.md @@ -1886,7 +1886,7 @@ Widening and user defined conversions are not supported with generic types. |-|-| |Category|Reliability| |Enabled|True| -|Severity|Info| +|Severity|Warning| |CodeFix|False| --- diff --git a/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.sarif b/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.sarif index 7695feb426..63c8dcae7a 100644 --- a/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.sarif +++ b/src/NetAnalyzers/Microsoft.CodeAnalysis.NetAnalyzers.sarif @@ -3382,7 +3382,7 @@ "id": "CA2021", "shortDescription": "Do not call Enumerable.Cast or Enumerable.OfType with incompatible types", "fullDescription": "Enumerable.Cast and Enumerable.OfType require compatible types to function expectedly. \u000aThe generic cast (IL 'unbox.any') used by the sequence returned by Enumerable.Cast will throw InvalidCastException at runtime on elements of the types specified. \u000aThe generic type check (C# 'is' operator/IL 'isinst') used by Enumerable.OfType will never succeed with elements of types specified, resulting in an empty sequence. \u000aWidening and user defined conversions are not supported with generic types.", - "defaultLevel": "note", + "defaultLevel": "warning", "helpUri": "https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2021", "properties": { "category": "Reliability", diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzerTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzerTests.cs index 54a52a2617..20f8b20e7a 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzerTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzerTests.cs @@ -1,9 +1,12 @@ // Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System; +using System.Collections.Generic; using System.Linq; +using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.NetCore.Analyzers.Runtime.DoNotCallEnumerableCastOrOfTypeWithIncompatibleTypesAnalyzer, @@ -82,6 +85,94 @@ void M() "); } + [Fact] + public async Task DynamicCSharp() + { + await VerifyCS.VerifyAnalyzerAsync(@" +using System.Linq; + +class C +{ + public void M() + { + dynamic x = null; + _ = x.ToString(); + int[] numbers = new int[] { 1, 2, 3 }; + var v = from dynamic d in numbers select (int)d; + _ = v.ToArray(); + } +} +"); + } + + [Fact] + public async Task ValueTupleCasesCSharp() + { + var x = from (int min, int max) pair in new[] { (1, 2), (-10, -3) } select pair; + _ = x.ToArray(); + + await VerifyCS.VerifyAnalyzerAsync(@" +using System.Linq; + +class C +{ + public void M() + { + var x = from (int min, int max) pair in new[] { (1, 2), (-10, -3) } select pair; + _= x.ToArray(); + } +}"); + } + + [Fact] + public async Task RegExCasesCSharp() + { + var actualSet = new HashSet<(int start, int end)>( + Regex.Match(".", "abc").Groups + .Cast() + .Select(g => (start: g.Index, end: g.Index + g.Length))); + + await VerifyCS.VerifyAnalyzerAsync(@" +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; + +class C +{ + public void M() + { + var actualSet = new HashSet<(int start, int end)>( + Regex.Match(""."", ""abc"").Groups + .Cast() + .Select(g => (start: g.Index, end: g.Index + g.Length))); + } +}"); + } + + [Fact] + public async Task MultipleTypesCasesCSharp() + { + await VerifyCS.VerifyAnalyzerAsync(@" +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +public sealed class MultiContainer : IEnumerable, IEnumerable +{ + IEnumerator IEnumerable.GetEnumerator() => null; + IEnumerator IEnumerable.GetEnumerator() => null; + IEnumerator IEnumerable.GetEnumerator() => null; + + public static void M() + { + _ = new MultiContainer().OfType(); + _ = new MultiContainer().OfType(); + _ = new MultiContainer().OfType(); + } +}"); + } + [Fact] public async Task NonGenericCasesCSharp() { @@ -406,6 +497,8 @@ void M() [Fact] public async Task NullableValueTypeCasesCSharp() { + _ = Enumerable.Range(1, 5).Cast().ToArray(); + _ = new int?[] { 123 }.Cast().ToArray(); _ = new ValueType[] { StringComparison.OrdinalIgnoreCase, null }.Cast().ToArray(); await VerifyCS.VerifyAnalyzerAsync(@" @@ -426,13 +519,56 @@ void M() _ = (new object[0]).Cast(); _ = (new IntEnum?[0]).Cast(); + // nullable value types + _ = (new bool[0]).Cast(); + _ = (new bool?[0]).Cast(); + _ = (new byte[0]).Cast(); + _ = (new byte?[0]).Cast(); + _ = (new short[0]).Cast(); + _ = (new short?[0]).Cast(); + _ = Enumerable.Range(1, 5).Cast(); + _ = (new int?[0]).Cast(); + _ = (new long[0]).Cast(); + _ = (new long?[0]).Cast(); + _ = (new float[0]).Cast(); + _ = (new float?[0]).Cast(); + _ = (new double[0]).Cast(); + _ = (new double?[0]).Cast(); + + + // Nullable + _ = (new bool[0]).Cast(); + _ = (new Nullable[0]).Cast(); + _ = (new byte[0]).Cast>(); + _ = (new Nullable[0]).Cast(); + _ = (new short[0]).Cast>(); + _ = (new Nullable[0]).Cast(); + _ = Enumerable.Range(1, 5).Cast>(); + _ = (new Nullable[0]).Cast(); + _ = (new long[0]).Cast>(); + _ = (new Nullable[0]).Cast(); + _ = (new float[0]).Cast>(); + _ = (new Nullable[0]).Cast(); + _ = (new double[0]).Cast>(); + _ = (new Nullable[0]).Cast(); + + // nullable value types + _ = (new byte[0]).Cast(); + _ = (new byte?[0]).Cast(); + _ = (new short[0]).Cast(); + _ = (new short?[0]).Cast(); + _ = Enumerable.Range(1, 5).Cast(); + _ = (new int?[0]).Cast(); + _ = (new long[0]).Cast(); + _ = (new long?[0]).Cast(); + // base class _ = (new Enum[0]).Cast(); _ = (new IntEnum?[0]).Cast(); _ = {|#10:(new int?[0]).Cast()|}; _ = {|#11:(new Enum[0]).Cast()|}; - // value type + // System.ValueType _ = (new Enum[0]).Cast(); _ = Array.Empty().Cast(); _ = (new IntEnum?[0]).Cast(); @@ -494,9 +630,15 @@ void M() [Fact] public async Task GenericCastsCSharp() { - await VerifyCS.VerifyAnalyzerAsync(@" + await new VerifyCS.Test + { + LanguageVersion = LanguageVersion.CSharp8, + TestCode = @" +using System; using System.Linq; +#nullable enable + struct Struct : IInterface {} interface IInterface {} interface IInterface2 {} @@ -598,13 +740,29 @@ void Mstruct() where TStruct : struct { (new TStruct[0]).Cast(); // int is a struct (new TStruct[0]).Cast(); // can always cast to object - {|#50:(new TStruct[0]).Cast()|}; // string is not is a struct + {|#50:(new TStruct[0]).Cast()|}; // string is not struct + {|#51:(new TStruct[0]).Cast()|}; (new int[0]).Cast(); // int is a struct - (new object[0]).Cast(); // can always cast to object - {|#51:(new string[0]).Cast()|}; // string is not is a struct + (new object[0]).Cast(); // can always cast from object + {|#52:(new string[0]).Cast()|}; // string is not struct + {|#53:(new string?[0]).Cast()|}; + + (new Nullable[0]).Cast(); + (new TStruct[0]).Cast>(); + (new Nullable[0]).Cast(); // int is a struct + (new Nullable[0]).Cast(); + (new Nullable[0]).Cast(); // can always cast to object + (new Nullable[0]).Cast(); + {|#54:(new Nullable[0]).Cast()|}; // string is not struct + {|#55:(new Nullable[0]).Cast()|}; + + (new int[0]).Cast(); // int is a struct + (new object[0]).Cast(); // can always cast from object + {|#56:(new string[0]).Cast()|}; // string is not struct } }", + ExpectedDiagnostics = { VerifyCS.Diagnostic(castRule).WithLocation(10).WithArguments("TClassC", "string"), VerifyCS.Diagnostic(castRule).WithLocation(11).WithArguments("string", "TClassC"), @@ -633,8 +791,14 @@ void Mstruct() where TStruct : struct VerifyCS.Diagnostic(castRule).WithLocation(41).WithArguments("int", "TStructInterface"), VerifyCS.Diagnostic(castRule).WithLocation(50).WithArguments("TStruct", "string"), - VerifyCS.Diagnostic(castRule).WithLocation(51).WithArguments("string", "TStruct") -); + VerifyCS.Diagnostic(castRule).WithLocation(51).WithArguments("TStruct", "string?"), + VerifyCS.Diagnostic(castRule).WithLocation(52).WithArguments("string", "TStruct"), + VerifyCS.Diagnostic(castRule).WithLocation(53).WithArguments("string?", "TStruct"), + VerifyCS.Diagnostic(castRule).WithLocation(54).WithArguments("TStruct?", "string"), + VerifyCS.Diagnostic(castRule).WithLocation(55).WithArguments("TStruct?", "string?"), + VerifyCS.Diagnostic(castRule).WithLocation(56).WithArguments("string", "TStruct?"), + } + }.RunAsync(); } [Fact]