Emiswelt
Emiswelt

Reputation: 4009

Remove all SyntaxTrivia nodes from Roslyn SyntaxTree

I am trying to remove all nodes of type SyntaxTrivia from a SyntaxTree using Roslyn.

I tried to use the SyntaxRewriter class, but that does not work as SyntaxTrivia is non-nullable:

public class WhitespaceRemover : CSharpSyntaxRewriter
{
   public override SyntaxTrivia VisitTrivia(SyntaxTrivia trivia)
   {
       // Cannot convert null to 'SyntaxTrivia' because it is a non-nullable value type
       return null;
   }
}

What's the correct way to accomplish this?

Upvotes: 2

Views: 1232

Answers (1)

George Alexandria
George Alexandria

Reputation: 2936

I suppose that you need to rewrite a SyntaxNode invoking Microsoft.CodeAnalysis.SyntaxNodeExtensions.WithoutTrivia(...), which will removes all trivias, instead of try to rewrite a SyntaxtTrivia.

Upd. @Emiswelt correctly mentioned that should override Visit method and additionally overriding VisitTrivia in the comment, which allows to remove non atached trivias from SyntaxTree

You can use it inside your syntax rewrite and it will looks like this:

public class WhitespaceRemover : CSharpSyntaxRewriter
{
    public override SyntaxNode Visit(SyntaxNode node) => base.Visit(node).WithoutTrivia();

    public override SyntaxTrivia VisitTrivia(SyntaxTrivia trivia) => default;
}

Upvotes: 3

Related Questions