gpt4 book ai didi

python - ANTLR4 因 Lexer/Parser 错误而终止 Python

转载 作者:行者123 更新时间:2023-12-01 04:20:06 30 4
gpt4 key购买 nike

我想知道如何在发现不匹配时阻止词法分析器或解析器运行。例如,如果词法分析器期望一个“.”我希望它不要继续恢复模式。

最佳答案

这对我有用:

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

Reference Answer

关于python - ANTLR4 因 Lexer/Parser 错误而终止 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33847547/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com