I am using antlr to generate my parser, but I want to override some of the error reporting. At the moment if I give some incorrect syntax, for example a missing token, antlr gives the error “line 1:11 missing TYPE at ‘.'”
However I can’t find in which method this error is outputted. It is not, as I originally thought, in the reportError() method. Does anyone know where the message is generated?
Thanks!
A
MissingTokenExceptiondoes pass throughreportError(...). Let’s say you would like to parse assignments using the grammar below:Now simply override the
reportError(...)method like this:and then try to parse, say,
"= 123;"(a missingId):As you can see, the custom error message is being printed to the console.
EDIT
And a warning like “no viable alternative …” is a problem in the lexer, not the parser. This happens when the lexer encounters a character that you did not account for in your grammar (or not as a proper token, at least).
Let’s say you parse the input
a = 123:(note the:at the end instead of a;). The lexer will now produce a “no viable alternative …” warning because I didn’t define any token for that:.An easy solution to account for such mistakes is to add a “catch-all” rule at the end of your lexer grammar that will match any character that is not matched by any lexer rule before it. Whenever such a “catch-all” rule matches, you simply throw an exception (or do something else, of course!) in the
@after{...}block of that rule.Here’s a demo:
If you now parse
a = 123:, you will see the following on your console: