Skip to content

Commit

Permalink
Fix analyzer crash on unbound generic types
Browse files Browse the repository at this point in the history
This was due to a bug where the analyzer would continue even if only
unbound generic types were used in the typeof operator.
  • Loading branch information
mpidash committed Mar 15, 2024
1 parent 2e80d61 commit 50c9eb9
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,8 @@ static bool AreNullabilityConstraintsViolated(IMethodSymbol method)
method.TypeArguments[i].CanHoldNullValue())
{
return true;
}
}
}
}

return false;
}
Expand Down Expand Up @@ -169,6 +169,13 @@ public static bool TryGetContext(IInvocationOperation invocation, [NotNullWhen(t
.Select(t => t.TypeOperand)
.Where(t => t is not INamedTypeSymbol { IsUnboundGenericType: true })
.ToImmutableArray();

// Bail out if there are no type arguments left after filtering out unbound generic types.
if (typeArguments.Length == 0)
{
return false;
}

var otherArguments = argumentsInParameterOrder.RemoveRange(typeOfArguments);

invocationContext = new RuntimeTypeInvocationContext(invocation, typeArguments, otherArguments);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,28 @@ void Test()
await VerifyCS.VerifyCodeFixAsync(source, source);
}

[Fact, WorkItem(7246, "https://github.com/dotnet/roslyn-analyzers/issues/7246")]
public async Task UnboundGenericTypeArgumentWithMatchingOtherArguments_NoDiagnostic_CS()
{
string source = """
class ViolatingType<T> {}

class C
{
void M(System.Type type, object other) {}
void M<T>() {}
void M(object other) {}

void Test()
{
M(typeof(ViolatingType<>), null);
}
}
""";

await VerifyCS.VerifyCodeFixAsync(source, source);
}

[Fact]
public async Task WrongArity_NoDiagnostic_CS()
{
Expand Down Expand Up @@ -1463,6 +1485,26 @@ End Class
await VerifyVB.VerifyCodeFixAsync(source, source);
}

[Fact, WorkItem(7246, "https://github.com/dotnet/roslyn-analyzers/issues/7246")]
public async Task UnboundGenericTypeArgumentWithMatchingOtherArguments_NoDiagnostic_VB()
{
string source = """
Class ViolatingType(Of T) : End Class

Class C
Sub M(type as System.Type, other as Object) : End Sub
Sub M(Of T)() : End Sub
Sub M(other as Object) : End Sub

Sub Test()
M(GetType(ViolatingType(Of )))
End Sub
End Class
""";

await VerifyVB.VerifyCodeFixAsync(source, source);
}

[Fact]
public async Task WrongArity_NoDiagnostic_VB()
{
Expand Down

0 comments on commit 50c9eb9

Please sign in to comment.