[antlr-interest] best practice for unwanted input before EOF

Michael Bedward michael.bedward at gmail.com
Wed Jan 26 16:50:12 PST 2011


Hi folks,

I have a grammar with the following start rule...

prog: (init_block)? statement+ EOF ;

The purpose of the EOF token is to detect unwanted input after
statements. I'm unclear on the best way to respond to input that is
unwanted but, because it is defined in the grammar, does not provoke a
NoViableAlt exception such as an init_block following rather than
preceding the statements.

At the moment I'm doing this in the @members section of my grammar...

@Override
protected Object recoverFromMismatchedToken(IntStream input, int
ttype, BitSet follow) throws RecognitionException {
    if (ttype == Token.EOF) {
        throw new UnexpectedInputException("Invalid input before end of file");
    }
    return super.recoverFromMismatchedToken(input, ttype, follow);
}

It works, but it seems like a clunky solution.

I've searched the list archives and scanned the Definitive Reference
and Patterns books without success, although I suspect I must be
missing something obvious.

I'd be grateful for any examples or pointers to docs.

Michael


More information about the antlr-interest mailing list