ANTLR4 在 Lexer/Parser 错误 Python 时终止

ANTLR4 Terminate on Lexer/Parser error Python

我想知道当 运行 发现不匹配时如何让词法分析器或解析器不受影响。例如,如果词法分析器期望一个 '.'我不希望它继续恢复模式。

这对我有用:

import sys
from antlr4 import *
from bin.LEDSGrammarLexer import LEDSGrammarLexer
from bin.LEDSGrammarParser import LEDSGrammarParser
from bin.LEDSGrammarListener import LEDSGrammarListener
from src.Gramatica import Gramatica
from src.Traductor import Translator
#Add This Library
from antlr4.error.ErrorListener import ErrorListener

import src.CuboSemantico

class MyErrorListener( ErrorListener ):
    def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):
        print str(line) + ":" + str(column) + ": sintax ERROR, " + str(msg)
        print "Terminating Translation"
        sys.exit()

    def reportAmbiguity(self, recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs):
        print "Ambiguity ERROR, " + str(configs)
        sys.exit()

    def reportAttemptingFullContext(self, recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs):
        print "Attempting full context ERROR, " + str(configs)
        sys.exit()

    def reportContextSensitivity(self, recognizer, dfa, startIndex, stopIndex, prediction, configs):
        print "Context ERROR, " + str(configs)
        sys.exit()

def main(argv):
    print "Parsing: " + argv[1] + "\n"
    input = FileStream(argv[1])
    lexer = LEDSGrammarLexer(input)

    #This was the key!
    stream = CommonTokenStream(lexer)
    parser = LEDSGrammarParser(stream)
    parser._listeners = [ MyErrorListener() ]

    tree = parser.programa()
    printer = Gramatica()
    walker = ParseTreeWalker()
    result = walker.walk(printer,tree)
    print "Resultado del parseo" + str(result)
    for idx,x in enumerate(printer.Cuadruplos):
        print str(idx) +" - "+str(x)
    translator = Translator()
    translator.translate(printer)
    #print(tree.toStringTree(recog=parser))

if __name__ == '__main__':
    main(sys.argv)

感谢: HAR