Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating well-formatted syntax with Roslyn

I am using Roslyn to modify the syntax of C# files. Using CSharpSyntaxRewriter, it is very easy to find and replace nodes in the syntax tree. However, the generated code is very ugly and won't even parse in all cases because the syntax nodes I create (using SyntaxFactory) lack even a minimal amount of whitespace trivia. Does Roslyn provide some basic formatting functionality to avoid this or do I have to add trivia manually to each node I create?

like image 298
ChaseMedallion Avatar asked Nov 01 '15 21:11

ChaseMedallion


2 Answers

Yes - it is possible, using Microsoft.CodeAnalysis.Formatting.Formatter:

var formattedResult = Formatter.Format(syntaxNode, workspace);
like image 199
pg0xC Avatar answered Nov 15 '22 03:11

pg0xC


You can see the usage of different Roslyn formatters here in Roslyn source code: https://sourceroslyn.io/#Microsoft.CodeAnalysis.Workspaces/CodeActions/CodeAction.cs,329

internal static async Task<Document> CleanupDocumentAsync(
        Document document, CancellationToken cancellationToken)
{
    if (document.SupportsSyntaxTree)
    {
        document = await ImportAdder.AddImportsFromSymbolAnnotationAsync(
        document, Simplifier.AddImportsAnnotation, cancellationToken: cancellationToken).ConfigureAwait(false);

        document = await Simplifier.ReduceAsync(document, Simplifier.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);

        // format any node with explicit formatter annotation
        document = await Formatter.FormatAsync(document, Formatter.Annotation, cancellationToken: cancellationToken).ConfigureAwait(false);

        // format any elastic whitespace
        document = await Formatter.FormatAsync(document, SyntaxAnnotation.ElasticAnnotation, cancellationToken: cancellationToken).ConfigureAwait(false);

        document = await CaseCorrector.CaseCorrectAsync(document, CaseCorrector.Annotation, cancellationToken).ConfigureAwait(false);
     }

     return document;
}
like image 20
SENya Avatar answered Nov 15 '22 05:11

SENya