【问题】
折腾antlr的异常恢复。
参考:
The Definitive ANTLR Reference.pdf
中,添加上对应的代码:
@members { protected void mismatch(IntStream input, int ttype, BitSet follow) throws RecognitionException { throw new MismatchedTokenException(ttype, input); } public void recoverFromMismatchedSet(IntStream input, RecognitionException e, BitSet follow) throws RecognitionException { throw e; } } // Alter code generation so catch-clauses get replace with this action. @rulecatch { catch (RecognitionException e) { throw e; } }
后,结果:
正常编译.g语法文件是可以的。
但是继续想要编译debug版本的代码,会去编译parser的话,就出错了:
[09:54:33] D:\DevRoot\IndustrialMobileAutomation\HandheldDataSetter\ANTLR\projects\v1.5\EddlVariableErrorHandle\output\EddlVariableErrorHandleParser.java:307: error: recoverFromMismatchedSet(IntStream,RecognitionException,BitSet) in EddlVariableErrorHandleParser cannot override recoverFromMismatchedSet(IntStream,RecognitionException,BitSet) in BaseRecognizer [09:54:33] public void recoverFromMismatchedSet(IntStream input, RecognitionException e, BitSet follow) throws RecognitionException [09:54:33] ^ [09:54:33] return type void is not compatible with Object [09:54:33] 1 error
如图:
即:
return type void is not compatible with Object |
【解决过程】
1.看起来,像是:
antlr v3的书里面的代码,给出的示例代码,之前是工作的。
但是或许是因为我当前用的是antlr 3.5的,内部api变化了,导致api不兼容了,所以编译不通过了。
2.那就去找找,这部分的原本的api是什么。
参考:
How to get ANTLR 3.2 to exit upon first error?
去试试:
@members { @Override protected Object recoverFromMismatchedToken(IntStream input, int ttype, BitSet follow) throws RecognitionException { throw new MismatchedTokenException(ttype, input); } @Override public Object recoverFromMismatchedSet(IntStream input, RecognitionException e, BitSet follow) throws RecognitionException { throw e; } } // Alter code generation so catch-clauses get replace with this action. @rulecatch { catch (RecognitionException e) { throw e; } } @lexer::members { @Override public void reportError(RecognitionException e) { throw new RuntimeException(e); } }
结果就可以正常编译通过了:
Generate Code去编译,是正常的:
debug编译,也是Ok的:
【总结】
此处,的确是:
作者parr写的书:
The Definitive ANTLR Reference.pdf
之后,相关的api变化了,导致其原先的代码不工作了
所以,最后是换为:
@members { @Override protected Object recoverFromMismatchedToken(IntStream input, int ttype, BitSet follow) throws RecognitionException { throw new MismatchedTokenException(ttype, input); } @Override public Object recoverFromMismatchedSet(IntStream input, RecognitionException e, BitSet follow) throws RecognitionException { throw e; } } // Alter code generation so catch-clauses get replace with this action. @rulecatch { catch (RecognitionException e) { throw e; } } @lexer::members { @Override public void reportError(RecognitionException e) { throw new RuntimeException(e); } }
然后可以正常编译了。
转载请注明:在路上 » 【已解决】antlr中尝试出错就退出,结果编译parser出错:error: recoverFromMismatchedSet(IntStream,RecognitionException,BitSet) in xxxParser cannot override recoverFromMismatchedSet(IntStream,RecognitionException,BitSet) in BaseRecognizer,return type void is not compatible with Object