1
我想知道如何在發現不匹配時保持詞法分析器或解析器不運行。例如,如果詞法分析器預期'。'我希望它不要繼續恢復模式。ANTLR4終結Lexer/Parser錯誤Python
我想知道如何在發現不匹配時保持詞法分析器或解析器不運行。例如,如果詞法分析器預期'。'我希望它不要繼續恢復模式。ANTLR4終結Lexer/Parser錯誤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
問題尋求幫助調試(** ** )必須包含所需的行爲,*特定的問題或錯誤*和*必要的最短代碼*在問題本身**中重現**。沒有**明確問題陳述**的問題對其他讀者沒有用處。請參閱:[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 – MattDMo