nalka
nalka

Reputation: 2330

Code fix : change members and class being used for a method call

I am doing a code analyser but I can't find a way to change the class and the members being accessed when you are calling a method. For example if i have

public class FirstClass
{
    public static void DoSomething(object SomeParameter)
    {
        //method body 
    }
}
public class SecondClass
{
    public static void ReplaceDoSomething(object SomeParameter)
    {
        //other method's body
    }
}

How could i make my code fix change FirstClass.DoSomething(new object()); to SecondClass.ReplaceDoSomething(new object());?

I tried to use SyntaxFactory but i can't realy figure out what parameters are expected for most methods and the MSDN provides nearly no details on them...

The code analyzer

public override void Initialize(AnalysisContext context)
{
    context.RegisterOperationAction(Analyze, OperationKind.Invocation);
}
private void Analyze(OperationAnalysisContext context)
{
    IInvocationOperation operation = (IInvocationOperation)context.Operation;
    if (operation.TargetMethod.Name == "DoSomething" && operation.TargetMethod.ContainingNamespace.Name == "FirstNamespace" && operation.TargetMethod.ContainingType.Inherits("FirstNamespace.FirstClass"))
    {
        //Rule is an automaticaly generated variable by visual studio when you create the analyzer
        Diagnostic diagnostic = Diagnostic.Create(Rule, operation.Syntax.GetLocation());
        context.ReportDiagnostic(diagnostic);
    }
}
public static class INamedTypeSymbolExtensions
{
    public static bool Inherits(this INamedTypeSymbol first, string otherFullName)
    {
        if (first.GetFullName() == otherFullName)
        {
            return true;
        }
        else if (typeof(object).FullName == first.GetFullName())
        {
            return false;
        }
        else
        {
            return first.BaseType.Inherits(otherFullName);
        }
    }

    public static string GetFullName(this INamedTypeSymbol element)
    {
        StringBuilder ret = new StringBuilder(element.Name);
        INamespaceSymbol ContainingNamespace = element.ContainingNamespace;
        while (ContainingNamespace.ContainingNamespace != null)
        {
            ret.Insert(0, ContainingNamespace.Name + ".");
            ContainingNamespace = ContainingNamespace.ContainingNamespace;
        }
        return ret.ToString();
    }
}

EDIT : The best result i have had was with

private async Task<Document> ProvideCodeFix(Document document, InvocationExpressionSyntax invocation, CancellationToken cancellationToken)
{
    SyntaxToken replaced = invocation.GetFirstToken();
    SyntaxToken replacing = SyntaxFactory.IdentifierName("SecondClass").GetFirstToken().WithLeadingTrivia(replaced.LeadingTrivia));
    return document.WithSyntaxRoot((await document.GetSyntaxRootAsync()).ReplaceToken(replaced, replacing);
}

with this it would change FirstClass.DoSomething(new object()); to SecondClass.DoSomething(new object());

But the main problem with this approach is that if i'd have to change FirstNamespace.FirstClass.DoSomething(new object()); to SecondClass.ReplaceDoSomething(new object()); then it'd not work

PS : I use .WithLeadingTrivia(...) to keep the comments and such stuff that was written before FirstClass

Upvotes: 2

Views: 472

Answers (1)

NineBerry
NineBerry

Reputation: 28499

This code works. We get the InvocationExpressionSyntax.Expression which represents the whole part before the () argument list. Then we replace that whole expression.

private async Task<Document> ProvideCodeFix(Document document, InvocationExpressionSyntax invocationExpression, CancellationToken cancellationToken)
{
    // Get the expression that represents the entity that the invocation happens on
    // (In this case this is the method name including possible class name, namespace, etc)
    var invokedExpression = invocationExpression.Expression;

    // Construct an expression for the new classname and methodname
    var classNameSyntax = SyntaxFactory.IdentifierName("SecondClass");
    var methodNameSyntax = SyntaxFactory.IdentifierName("ReplaceDoSomething");
    var classNameAndMethodNameSyntax = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, classNameSyntax, methodNameSyntax);

    // Add the surrounding trivia from the original expression
    var replaced = classNameAndMethodNameSyntax;
    replaced = replaced.WithLeadingTrivia(invokedExpression.GetLeadingTrivia());
    replaced = replaced.WithTrailingTrivia(invokedExpression.GetTrailingTrivia());

    // Replace the whole original expression with the new expression
    return document.WithSyntaxRoot((await document.GetSyntaxRootAsync()).ReplaceNode(invokedExpression, replaced));
}

Upvotes: 2

Related Questions