Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix CA2021 false positive casting from value type constraint to Enum or ValueType #7575

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -216,16 +216,40 @@ static bool CastWillAlwaysFail(ITypeSymbol castFrom, ITypeSymbol castTo)
return false;
}

static bool IsUnconstrainedTypeParameter(ITypeParameterSymbol typeParameterSymbol)
=> !typeParameterSymbol.HasValueTypeConstraint
&& typeParameterSymbol.ConstraintTypes.IsEmpty;
// because object is a reference type the 'class' reference type constraint
// doesn't actually constrain unless a type is specified too
// not implemented:
// NotNullConstraint
// ConstructorConstraint
// UnmanagedTypeConstraint
// Nullability annotations
static bool CastToTypeParamWillAlwaysFail(ITypeSymbol castFrom, ITypeParameterSymbol castToTypeParam)
{
if (castToTypeParam.HasValueTypeConstraint
&& ValueTypeConstraintImpossible(castFrom))
{
return true;
}

// because object is a reference type the 'class' reference type constraint
// doesn't actually constrain unless a type is specified too
// not implemented:
// NotNullConstraint
// ConstructorConstraint
// UnmanagedTypeConstraint
// Nullability annotations

if (castToTypeParam.ConstraintTypes.Any(constraintType => CastWillAlwaysFail(castFrom, constraintType)))
{
return true;
}

return false;
}

static bool ValueTypeConstraintImpossible(ITypeSymbol t)
{
if (t.TypeKind == TypeKind.Class)
{
return t.SpecialType is not SpecialType.System_Enum
and not SpecialType.System_ValueType;
}

return false;
}

switch (castFrom.TypeKind, castTo.TypeKind)
{
Expand All @@ -235,42 +259,25 @@ static bool IsUnconstrainedTypeParameter(ITypeParameterSymbol typeParameterSymbo

case (TypeKind.TypeParameter, _):
var castFromTypeParam = (ITypeParameterSymbol)castFrom;
if (IsUnconstrainedTypeParameter(castFromTypeParam))
{
return false;
}

if (castFromTypeParam.ConstraintTypes.Any(constraintType => CastWillAlwaysFail(constraintType, castTo)))
{
return true;
}

if (castFromTypeParam.HasValueTypeConstraint
&& castTo.TypeKind == TypeKind.Class)
{
return true;
}

return false;
case (_, TypeKind.TypeParameter):
var castToTypeParam = (ITypeParameterSymbol)castTo;
if (IsUnconstrainedTypeParameter(castToTypeParam))
{
return false;
}

if (castToTypeParam.ConstraintTypes.Any(constraintType => CastWillAlwaysFail(castFrom, constraintType)))
&& ValueTypeConstraintImpossible(castTo))
{
return true;
}

if (castToTypeParam.HasValueTypeConstraint
&& castFrom.TypeKind == TypeKind.Class)
if (castTo.TypeKind == TypeKind.TypeParameter)
{
return true;
return CastToTypeParamWillAlwaysFail(castFrom, (ITypeParameterSymbol)castTo);
}

return false;
case (_, TypeKind.TypeParameter):
return CastToTypeParamWillAlwaysFail(castFrom, (ITypeParameterSymbol)castTo);

case (TypeKind.Class, TypeKind.Class):
return !castFromParam.DerivesFrom(castToParam)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -910,6 +910,82 @@ class GenericDerived : GenericBase<int>
await test.RunAsync();
}

[Fact, WorkItem(7031, "https://github.com/dotnet/roslyn-analyzers/issues/7031")]
public async Task GenericConstraints()
{
// ensure runtime behavior is matches
_ = new Enum[] { StringComparison.OrdinalIgnoreCase }.Cast<StringComparison>().ToArray();
_ = new ValueType[] { int.MaxValue }.Cast<int>().ToArray();

var test = new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net90,
LanguageVersion = LanguageVersion.Latest,

TestCode = @"
using System;
using System.Collections.Generic;
using System.Linq;

public static class Program
{
public static IEnumerable<T> CastFromEnums<T>(IEnumerable<Enum> values) where T : struct, Enum
=> values.Cast<T>();

public static IEnumerable<T> CastFromValueTypes<T>(IEnumerable<ValueType> values) where T : struct
=> values.Cast<T>();

public static IEnumerable<Enum> CastToEnums<T>(IEnumerable<T> values) where T : struct, Enum
=> values.Cast<Enum>();

public static IEnumerable<ValueType> CastToValueTypes<T>(IEnumerable<T> values) where T : struct
=> values.Cast<ValueType>();

public static IEnumerable<T> CastValueTypes<T>(IEnumerable<ValueType> values) where T : struct
=> values.Cast<T>();

public static IEnumerable<TOut> CastUnconstrainedGeneric<TIn, TOut>(IEnumerable<TIn> values)
=> values.Cast<TOut>();

public static IEnumerable<TOut> CastGenericUnmanagedToGeneric<TIn, TOut>(IEnumerable<TIn> values)
where TOut : unmanaged
=> values.Cast<TOut>();

public static IEnumerable<TOut> CastGenericUnmanagedToGenericUnmanagedl<TIn, TOut>(IEnumerable<TIn> values)
where TIn : unmanaged
where TOut : unmanaged
=> values.Cast<TOut>();

public static IEnumerable<TOut> CastGenericNotNullToGenericNotNull<TIn, TOut>(IEnumerable<TIn> values)
where TIn : notnull
where TOut : notnull
=> values.Cast<TOut>();

public static IEnumerable<TOut> CastGenericToGeneric<TIn, TOut>(IEnumerable<TIn> values)
where TIn : Enum
where TOut : Uri
=> {|#1:values.Cast<TOut>()|};

public static IEnumerable<TOut> CastGenericStructToGeneric<TIn, TOut>(IEnumerable<TIn> values)
where TIn : struct
where TOut : Uri
=> {|#2:values.Cast<TOut>()|};

public static IEnumerable<TOut> CastGenericToGenericStruct<TIn, TOut>(IEnumerable<TIn> values)
where TIn : Uri
where TOut : struct
=> {|#3:values.Cast<TOut>()|};
}",
ExpectedDiagnostics =
{
VerifyCS.Diagnostic(castRule).WithLocation(1).WithArguments("TIn", "TOut"),
VerifyCS.Diagnostic(castRule).WithLocation(2).WithArguments("TIn", "TOut"),
VerifyCS.Diagnostic(castRule).WithLocation(3).WithArguments("TIn", "TOut"),
}
};
await test.RunAsync();
}

[Fact]
public async Task NonGenericCasesVB()
{
Expand Down
Loading