Roslyn Annotations for Code Fix

 
 
  • Gérald Barré

Roslyn Analyzer can be used to detect patterns in your code and report them. It can also provide code fixes to automatically fix the issues. In this case the code fix takes the existing SyntaxTree and return the new SyntaxTree with the issue fixed. Roslyn does provide the concept of Annotation to mark a node in the SyntaxTree. You can use special annotations to indicate Roslyn to post-process the syntax tree provided by the code fix and take specific actions. In this post I describe the most common annotations.

Simplifier.Annotation removes useless stuff from your code. For instance, it can remove unnecessary parentheses or simplify type names. This can be useful to generate an expression that is valid and have the right evaluation order, but let the compiler removes parentheses if possible.

C#
// Souround the expression with parentheses. If the compiler determines that the parentheses are not needed, it will remove them.
public static ParenthesizedExpressionSyntax Parentheses<T>(this ExpressionSyntax expression)
{
    return SyntaxFactory.ParenthesizedExpression(expression)
        .WithAdditionalAnnotations(Simplifier.Annotation);
}

Simplifier.AddImportsAnnotation add missing using directives to your code.

C#
generator.TypeExpression(cultureInfo)
    .WithAdditionalAnnotations(Simplifier.AddImportsAnnotation);

Formatter.Annotation formats the code based on the configuration (EditorConfig). It will remove unnecessary whitespaces, add missing whitespaces, etc. Be careful to add it only to the node that you actually edited. Otherwise, you may reformat the whole file which is not acceptable from a user perspective.

C#
newNode.WithAdditionalAnnotations(Formatter.Annotation);

RenameAnnotation.Create() is used to rename a symbol. After applying the code fix the IDE should ask the name of the symbol to the user and remame it. For example you can use this annotation when you introduce a new member and you want to let the user choose the name.

C#
Identifier(methodName).WithAdditionalAnnotations(RenameAnnotation.Create());

You can find other annotations in the Microsoft.CodeAnalysis namespace such as ElasticAnnotation, ConflictAnnotation, WarningAnnotation, etc., but there are less common.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub