Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing redundant semicolons in code with SyntaxRewriter

Tags:

c#

roslyn

I am trying to remove redundant semicolons in the code using a custom syntax rewriter.

public class Sample
{
   public void Foo()
   {
      Console.WriteLine("Foo");
      ;
   }
}

The following syntax rewriter covers most scenarios as in the Sample class.

public class EmptyStatementRemoval : CSharpSyntaxRewriter
{
  public override SyntaxNode VisitEmptyStatement(EmptyStatementSyntax node)
  {
    return null;
  }
}

However when the semicolon has a leading or trailing trivia, returning null from the VisitEmptyStatement method removes the trivia, which is unintended.

public class Sample
{
   public void Foo()
   {
      Console.WriteLine("Foo");
      #region SomeRegion
      //Some other code
      #endregion
      ;
   }
}

I couldn't determine how to return a node with only the leading and trailing trivia removing the semicolon. I tried to replace the semicolon token with another token using node.WithSemicolonToken(SyntaxToken) method, which turns out to be accepting only tokens of type SyntaxKind.SemicolonToken or throws an ArgumentException.

like image 951
odulkanberoglu Avatar asked Aug 14 '14 13:08

odulkanberoglu


1 Answers

One approach that could work is to replace the semicolon token with a missing semicolon token:

public override SyntaxNode VisitEmptyStatement(EmptyStatementSyntax node)
{
    return node.WithSemicolonToken(
        SyntaxFactory.MissingToken(SyntaxKind.SemicolonToken)
            .WithLeadingTrivia(node.SemicolonToken.LeadingTrivia)
            .WithTrailingTrivia(node.SemicolonToken.TrailingTrivia));
}

For your #region example, the result looks like this (notice the line containing only whitespace where the semicolon was):

public class Sample
{
    public void Foo()
    {
        Console.WriteLine("Foo");
        #region SomeRegion
        //Some other code
        #endregion

    }
}
like image 173
svick Avatar answered Nov 06 '22 21:11

svick