步行者可以停下来吗?

时间:2015-02-15 17:42:20

标签: c# metaprogramming antlr4

我有一个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()后立即停止行走,因为我对这下面的任何东西都不感兴趣。目前我正在遍历整个解析树,只是在程序范围内没有做任何事情。

从解析树监听器实现中有没有办法告诉walker停止走树?

1 个答案:

答案 0 :(得分:5)

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

  1. 抛出异常,例如CancellationException
  2. 创建一个扩展ParseTreeWalker的新类,并提供您自己的walk实现,该类了解您需要的取消概念。从current implementation of walk开始并修改它以满足您的需求是有意义的。