antlr4如何使规则抛出异常

antlr4 how to make rule throw exception

在我的代码中:

     andexpr : orexpr (AND orexpr)*;
 orexpr :  atomicExpression ( OR  atomicExpression)*;

 atomicExpression :
    attribute //THIS
  | equalsExpression
  | notEqualsExpression;

equalsExpression: attribute eq (value | arrayValue);
notEqualsExpression: attribute neq (value | arrayValue);

我想让 THIS 规则抛出异常并且无效。 我希望它作为 'valid' 包含在内,以便在解析树时创建额外的上下文。而我只输入 attribute。 可能吗?

使用您的代码:

 atomicExpression :
    attribute {if(true) {System.out.println("error");throw new RuntimeException();}}
  | equalsExpression
  | notEqualsExpression;

error

Problems calling org.antlr.v4.gui.TestRig.main(args)

我做了一个快速测试,似乎 ANTLR v4.5.3 的 TestRig 本身捕获了 RuntimeException。所以它只是打印一条语句,说调用 TestRig.mains(args) 时出现问题,而没有我们在异常后通常遇到的通常堆栈跟踪。所以我建议你在抛出异常之前添加一些有意义的东西。

if(true) 是防止 java 编译器抱怨无法访问的语句所必需的,因为它足够聪明,知道 RuntimeException() 终止了程序,但肯定会生成一些代码异常子句后的 ANTLR。

看我之前的问题: How To Terminate a Lexer in ANTLR4