Antlr v4 : can't set any kind of error monitoring on parser. How to throw exceptions

65 views
Skip to first unread message

Emiel Steerneman

unread,
Aug 26, 2015, 9:55:48 AM8/26/15
to antlr-discussion
All I want from Antlr is to throw an exception when it encouters something like "mismatched input" or "extraneous input" etc.
I tried
    parser.setErrorHandler(BailErrorStrategy)                  ERROR: 'parser' object has no attribute 'setErrorHandler'
    parser.addErrorListener(BaseErrorListener)               ERROR: 'BaseErrorListener' is not defined

CODE

from grammar_paidLexer import grammar_paidLexer
from grammar_paidParser import grammar_paidParser
from grammar_paidListener import grammar_paidListener
input  = FileStream(file)
lexer = grammar_paidLexer(input)
stream = CommonTokenStream(lexer)
parser = grammar_paidParser(stream)

parser.setErrorHandler(BailErrorStrategy)
parser.addErrorListener(BaseErrorListener)

try:
tree = parser.receipt()
except Exception as e:
print e
sys.exit()

listener = grammar_paidListener()
walker = ParseTreeWalker()
walker.walk(listener, tree)

Emiel Steerneman

unread,
Aug 26, 2015, 10:40:07 AM8/26/15
to antlr-discussion
I fixed it myself:

from antlr4.error.ErrorStrategy import ErrorStrategy

class MyErrorListener( ErrorListener ):
def __init__(self):
super(MyErrorListener, self).__init__()
def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):
raise Exception("syntaxError!")
def reportAmbiguity(self, recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs):
raise Exception("reportAmbiguity!")
def reportAttemptingFullContext(self, recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs):
raise Exception("reportAttemptingFullContext!")
def reportContextSensitivity(self, recognizer, dfa, startIndex, stopIndex, prediction, configs):
raise Exception("reportContextSensitivity!")

parser._listeners = [ MyErrorListener() ]
try:
tree = parser.receipt()
except Exception as e:
print e
return


Op woensdag 26 augustus 2015 15:55:48 UTC+2 schreef Emiel Steerneman:

Eric Vergnaud

unread,
Aug 26, 2015, 1:06:00 PM8/26/15
to antlr-discussion
Hi,

_listeners is private, you should write:

parser.addErrorListener(MyErrorListener()]

Eric
Reply all
Reply to author
Forward
0 new messages