ANTLR4 解析器(在 Java 中)可以被检测为可中断的吗?

问题描述 投票:0回答:1

我想用

ExecutorService
运行我的 ANTLR 解析器,这样我就可以在超时后调用
Future.cancel()
。 AIUI,我需要解析器检查
Thread.isInterrupted()
;解析器接口中是否有用于这种检测的机制?

在相关的情况下,解析器似乎在

PredictionContext
递归中很深。

antlr antlr4
1个回答
2
投票

有一个 ParseCancellationException(https://javadoc.io/doc/org.antlr/antlr4-runtime/latest/index.html)。

根据文档:“抛出此异常是为了取消解析操作。此异常不扩展 RecognitionException,允许它绕过标准错误恢复机制。 BailErrorStrategy 抛出此异常以响应解析错误。”

您可以将覆盖 enterEveryRule() 的侦听器附加到您的解析器。您可以在该侦听器上使用一个方法来设置一个标志,以便在解析器下次输入规则时抛出 ParseCancellationException(这种情况经常发生)。

这里有一个简短的例子,说明听众可能是什么样子的:

public class CancelListener extends YourBaseListener {
    public boolean cancel = false;

    @Override
    public void enterEveryRule(ParserRuleContext ctx) {
        if (cancel) {
            throw new ParseCancellationException("gotta go");
        }
        super.enterEveryRule(ctx);
    }
}

然后您可以将该侦听器添加到您的解析器:

 parser.addParseListener(cancelListener);

然后:

cancelListener.cancel = true
© www.soinside.com 2019 - 2024. All rights reserved.