Python 2.7& ANTLR4:使ANTLR在无效输入

时间:2015-08-26 11:06:17

标签: python python-2.7 antlr antlr4

我想抓住像

这样的错误
line 1:1 extraneous input '\r\n' expecting {':', '/',}

line 1:1 mismatched input 'Vaasje' expecting 'Tafel'

我尝试在try-catch中包装我的函数但是,正如预期的那样,这些错误只是print语句而不是异常。我已经看到了一些在.g4文件中切换错误的例子,但是所有的例子都是针对Java的,我似乎无法让它工作。

Python中的ANTLR4是否可以抛出我可以捕获的异常?

1 个答案:

答案 0 :(得分:10)

我查看了python类并注意到他们没有java添加和删除错误监听器的方法,这可能是ANTLR中的一个错误,但python是python你可以修改成员而不用如下例所示需要一个setter:

我通过执行:antlr4 -Dlanguage = Python2 AlmostEmpty.g4然后输入main.py来运行该示例

AlmostEmpty.g4

grammar AlmostEmpty;

animals: (CAT | DOG | SHEEP ) EOF;

WS: [ \n\r]+ -> skip;
CAT: [cC] [aA] [tT];
DOG: [dD] [oO] [gG];
SHEEP: [sS] [hH] [eE] [pP];

main.py

from antlr4 import *
import sys
from AlmostEmptyLexer import AlmostEmptyLexer
from AlmostEmptyParser import AlmostEmptyParser
from antlr4.error.ErrorListener import ErrorListener

class MyErrorListener( ErrorListener ):

    def __init__(self):
        super(MyErrorListener, self).__init__()

    def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):
        raise Exception("Oh no!!")

    def reportAmbiguity(self, recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs):
        raise Exception("Oh no!!")

    def reportAttemptingFullContext(self, recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs):
        raise Exception("Oh no!!")

    def reportContextSensitivity(self, recognizer, dfa, startIndex, stopIndex, prediction, configs):
        raise Exception("Oh no!!")

if __name__ == "__main__":
    inputStream = StdinStream( )
    lexer = AlmostEmptyLexer(inputStream)
    # Add your error listener to the lexer if required
    #lexer.removeErrorListeners()
    #lexer._listeners = [ MyErrorListener() ]
    stream = CommonTokenStream(lexer)
    parser = AlmostEmptyParser(stream)
    # As mentioned in the comments by @Tim Stewart instead of doing this:
    # parser._listeners = [ MyErrorListener() ]
    # you can do this:
    parser.addErrorListener( MyErrorListener() )
    tree = parser.animals()