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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With