您需要重写mismatch
andrecoverFromMismatchedSet
方法以确保立即引发异常(示例用于 Java):
@members {
protected void mismatch(IntStream input, int ttype, BitSet follow) throws RecognitionException {
throw new MismatchedTokenException(ttype, input);
}
public Object recoverFromMismatchedSet(IntStream input, RecognitionException e, BitSet follow) throws RecognitionException {
throw e;
}
}
那么您需要更改解析器处理这些异常的方式,以免它们被吞没:
@rulecatch {
catch (RecognitionException e) {
throw e;
}
}
(解析器中所有规则匹配方法的主体都将包含在try
块中,并以此作为catch
块。)
为了比较,recoverFromMismatchedSet
继承自的默认实现BaseRecognizer
:
public Object recoverFromMismatchedSet(IntStream input, RecognitionException e, BitSet follow) throws RecognitionException {
if (mismatchIsMissingToken(input, follow)) {
reportError(e);
return getMissingSymbol(input, e, Token.INVALID_TOKEN_TYPE, follow);
}
throw e;
}
和默认规则捕获:
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}