Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace a string variable with a var in Roslyn?

For local declarations like: string a = string.Empty;

How can I write a diagnostic to change it to: var a = string.Empty;

like image 652
user3500462 Avatar asked Apr 22 '14 18:04

user3500462


2 Answers

I've put together a code fix with diagnostic. Here's the interesting parts:

Implementation of AnalyzeNode from ISyntaxNodeAnalyzer

public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action<Diagnostic> public void AnalyzeNode(SyntaxNode node, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
    {
        var localDeclaration = (LocalDeclarationStatementSyntax)node;
        if (localDeclaration.Declaration.Type.IsVar) return;
        var variable = localDeclaration.Declaration.Variables.First();
        var initialiser = variable.Initializer;
        if (initialiser == null) return;
        var variableTypeName = localDeclaration.Declaration.Type;
        var variableType = semanticModel.GetTypeInfo(variableTypeName).ConvertedType;
        var initialiserInfo = semanticModel.GetTypeInfo(variable.Initializer.Value);
        var typeOfRightHandSideOfDeclaration = initialiserInfo.Type;
        if (Equals(variableType, typeOfRightHandSideOfDeclaration))
        {
            addDiagnostic(Diagnostic.Create(Rule, node.GetLocation(), localDeclaration.Declaration.Variables.First().Identifier.Value));
        }
    }

This essentially looks at the types on both sides of the declaration and if they're the same (and the RHS isn't already var) then add a diagnostic.

And here's the code for the Code Fix:

public async Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
    {
        var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
        var diagnosticSpan = diagnostics.First().Location.SourceSpan;
        var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<LocalDeclarationStatementSyntax>().First();
        return new[] { CodeAction.Create("Use var", c => ChangeDeclarationToVar(document, declaration, c)) };
    }

private async Task<Document> ChangeDeclarationToVar(Document document, LocalDeclarationStatementSyntax localDeclaration, CancellationToken cancellationToken)
    {
        var root = await document.GetSyntaxRootAsync(cancellationToken);
        var variableTypeName = localDeclaration.Declaration.Type;
        var varTypeName = SyntaxFactory.IdentifierName("var").WithAdditionalAnnotations(Formatter.Annotation);
        var newDeclaration = localDeclaration.ReplaceNode(variableTypeName, varTypeName);            
        var newRoot = root.ReplaceNode(localDeclaration, newDeclaration);
        return document.WithSyntaxRoot(newRoot);
    }

This bit is nice and simple, just get var from the Syntax factory and switch it out. Note that var doesn't have it's own static method in the SyntaxFactory so instead is reference by name.

like image 35
rh072005 Avatar answered Nov 09 '22 23:11

rh072005


You can't. The var keyword tells the compiler to perform type inference, and with just var a; the compiler doesn't have enough information to infer a type.

You could however do any of the following

var a = new String();
var b = String.Empty;
var c = "";

but this seems like more effort than it's worth.

Edit for updated request: Why do you want to modify all the code to be declared with var? It compiles to the same IL anyway (trivially simple example):

// var a = String.Empty;
IL_0000:  ldsfld     string [mscorlib]System.String::Empty
IL_0005:  pop
// string b = String.Empty;
IL_0006:  ldsfld     string [mscorlib]System.String::Empty
IL_000b:  pop
like image 103
Nathan Avatar answered Nov 10 '22 01:11

Nathan