Roslyn analyzer to detect all kinds of implicit conversions?

Viewed 81

I need a code analyzer which warns me about every implicit cast/conversion like when assigning a variable or passing an argument to method.

I started a tutorial series on Roslyn but it's still huge and I can't find the solution.

I tried the code below but it doesn't seem to work.

I guess I have to analyze the code semantically instead of syntactically. I tried it but got lost in the huge amount of properties, methods, etc. and don't know how could I find implicit conversions in the model.

context.RegisterSyntaxNodeAction(AnalyzeNodeArgument, SyntaxKind.Argument);
context.RegisterSyntaxNodeAction(AnalyzeNodeExpressionStatement, SyntaxKind.ExpressionStatement);

private void AnalyzeNodeArgument(SyntaxNodeAnalysisContext context)
{
    var arg = (ArgumentSyntax)context.Node;
    var typeInfo = context.SemanticModel.GetTypeInfo(arg);
    var convertedImplicitly = !SymbolEqualityComparer.Default.Equals(typeInfo.Type, typeInfo.ConvertedType);
    if (convertedImplicitly)
    {
        context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation(), new string[1] { "Asd" }));
    }
}

private void AnalyzeNodeExpressionStatement(SyntaxNodeAnalysisContext context)
{
    var expressionStatement = (ExpressionStatementSyntax)context.Node;
    var typeInfo = context.SemanticModel.GetTypeInfo(expressionStatement);
    var convertedImplicitly = !SymbolEqualityComparer.Default.Equals(typeInfo.Type, typeInfo.ConvertedType);
    if (convertedImplicitly)
    {
        context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation(), new string[1] { "Bsd" }));
    }
}

This is the code I tried it on, where Vector3 and Vector2 converted to each other implicitly. (I use the Unity3D engine)

But no error, warning, or anything is shown, everything compiles perfectly. (The only hint shown is that variable "a" is unused.)

void Update()
{
    Vector2 a = Vector3.zero;
    var b = Vector2.zero;
    Asd(b);
}

void Asd(Vector3 a)
{
    print(a.ToString());
}
0 Answers
Related