Andremoniy
Andremoniy

Reputation: 34900

Catching ANTLR's NoViableAltException in Java and ANTLRWorks Debugger

Consider we try to feed some incorrect input text to some grammar (e.g. text which contains some unknown token). In ANTLRWorks during interpretation we will see NoViableAltException in graph.

UPD: There are two cases when this exception appears:

1) Unexpected using of some known token, in this case we will receive something like line 5:36 no viable alternative at input ','

2) Using unknown token type. For example grammar doesn't know anything about tokens, which start with @ symbol. And we are trying to feed text with such token to our grammar.

Unfortunately in case (2) this exception isn't thrown neither in ANTLRWorks debugger, neither in generated Java code; but it is seen only in ANTLRWorks interpreter's result graph.

I've tried also to add the following standard code to my grammar:

@parser::members {
    private IErrorReporter errorReporter = null;
    public void setErrorReporter(IErrorReporter errorReporter) {
        this.errorReporter = errorReporter;
    }
    public void emitErrorMessage(String msg) {
        errorReporter.reportError(msg);
    }
}
@lexer::members {
    ... the same code as above ...
}

This construction successfully catches parsing errors of type (1) (e.g. errors about unexpected using of token: line 5:36 no viable alternative at input ','). But in case of not-viable-input with unknown tokens parser generates just children == null in top CommonTree object without any error reporting.

I'm using antlr 3.5.

The question: is it possible to catch NoViableAltException in described situation in generated Java code and how?

Upvotes: 2

Views: 2291

Answers (2)

Andremoniy
Andremoniy

Reputation: 34900

Well, this answer given by 280Z28 to my second part of this question solves both problems well. So, this is the proper answer.

Upvotes: 2

Sam Harwell
Sam Harwell

Reputation: 99869

You need to add the following as the very last rule in your lexer. It will create a token for the invalid character(s) and send it to the parser where the error will be properly reported.

ANYCHAR : . ;

Upvotes: 0

Related Questions