我有一个ParseTree监听器实现,用于在标准VBA模块中获​​取全局作用域声明:

public class DeclarationSectionListener : DeclarationListener
{
    private bool _insideProcedure;

    public override void EnterVariableStmt(VisualBasic6Parser.VariableStmtContext context)
    {
        var visibility = context.visibility();
        if (!_insideProcedure && visibility == null
            || visibility.GetText() == Tokens.Public
            || visibility.GetText() == Tokens.Global)
        {
            base.EnterVariableStmt(context);
        }
    }

    public override void EnterConstStmt(VisualBasic6Parser.ConstStmtContext context)
    {
        var visibility = context.visibility();
        if (!_insideProcedure && visibility == null
            || visibility.GetText() == Tokens.Public
            || visibility.GetText() == Tokens.Global)
        {
            base.EnterConstStmt(context);
        }
    }

    public override void EnterArg(VisualBasic6Parser.ArgContext context)
    {
        return;
    }

    public override void EnterSubStmt(VisualBasic6Parser.SubStmtContext context)
    {
        _insideProcedure = true;
    }

    public override void EnterFunctionStmt(VisualBasic6Parser.FunctionStmtContext context)
    {
        _insideProcedure = true;
    }

    public override void EnterPropertyGetStmt(VisualBasic6Parser.PropertyGetStmtContext context)
    {
        _insideProcedure = true;
    }

    public override void EnterPropertyLetStmt(VisualBasic6Parser.PropertyLetStmtContext context)
    {
        _insideProcedure = true;
    }

    public override void ExitPropertySetStmt(VisualBasic6Parser.PropertySetStmtContext context)
    {
        _insideProcedure = true;
    }
}

有没有办法告诉树行者停止行走?说我有一个这样的VBA模块:
Public Const foo = 123
Public bar As String

Public Sub DoSomething()
    ' some code
End Sub

' ...
' 10K more lines of code
' ...

Private Function GetSomething() As String
     ' some code
End Function

我希望树浏览器在输入Public Sub DoSomething()时立即停止分析树,因为我对下面的内容不感兴趣。目前,我正在遍历整个分析树,只是在过程范围内不做任何事情。

从解析树监听器实现中,是否有一种方法告诉步行者停止步行该树?

最佳答案

是的,您可以执行以下任一操作:

  • 引发异常,例如CancellationException
  • 创建一个扩展ParseTreeWalker的新类,并提供您自己的 walk 实现,该实现了解您需要的取消概念。从current implementation of walk 开始并对其进行修改以满足您的需求是很有意义的。
  • 关于c# - 步行者可以停下来吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28529041/

    10-11 19:27