【问题标题】:Removing redundant semicolons in code with SyntaxRewriter使用 SyntaxRewriter 删除代码中的多余分号
【发布时间】:2014-08-14 22:55:44
【问题描述】:

我正在尝试使用自定义语法重写器删除代码中多余的分号。

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

以下语法重写器涵盖了 Sample 类中的大多数场景。

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

但是,当分号有前导或尾随琐事时,从 VisitEmptyStatement 方法返回 null 会删除琐事,这是无意的。

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

我无法确定如何返回只有前导和尾随琐事删除分号的节点。我尝试使用 node.WithSemicolonToken(SyntaxToken) 方法将分号标记替换为另一个标记,结果证明只接受 SyntaxKind.SemicolonToken 类型的标记或抛出 ArgumentException。

【问题讨论】:

  • 分号是否被认为是node.GetLeadingTrivia()的一部分?
  • 不,分号不是琐事。

标签: c# roslyn


【解决方案1】:

一种可行的方法是将分号标记替换为缺少的分号标记:

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

对于您的 #region 示例,结果如下所示(注意该行仅包含分号所在的空格):

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

    }
}

【讨论】:

  • 感谢您的回答。我仍然想知道如果不留下多余的空格,这种情况是否是不可能的。
  • @odulkanberoglu 我认为是,但它需要更复杂的代码来检测哪些空白是“冗余的”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-10
  • 1970-01-01
  • 2012-10-02
  • 2016-08-02
  • 2019-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多