[antlr-interest] How does one suppress 'no viable alternative at character' warning messages

Tim Halloran hallorant at gmail.com
Wed Sep 17 13:27:20 PDT 2008


On Wed, Sep 17, 2008 at 3:27 PM, Terence Parr <parrt at cs.usfca.edu> wrote:

> Just throw an Error, which will not require a change to the signature and
> will blast all way out.
>

This is undesirable because it breaks the client side and loses reporting
information.  My client side looks like:

    public static ColumnAnnotation parse(String annotation) {
        ColumnAnnotation result = null;
        ANTLRStringStream input = new ANTLRStringStream(annotation);
        ColumnAnnotationLexer lexer = new ColumnAnnotationLexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        ColumnAnnotationParser parser = new ColumnAnnotationParser(tokens);
        try {
            result = parser.columnAnnotation();
        } catch (RecognitionException e) {
            SLLogger.getLogger().log(Level.WARNING,
                    I18N.err(129, annotation, e.charPositionInLine));
        }
        if (result == null) {
            result = new ColumnAnnotation();
            result.setIsValid(false);
        }
        return result;
    }

Where I try to report a (hopefully) helpful warning.

There is, however, a solution (albeit a bit messy) that does what the client
desires:

@lexer::members {
@Override
public void reportError(RecognitionException e) {
  Thrower.sneakyThrow(e);
}

/**
 * See "Puzzle 43: Exceptionally Unsafe" from Bloch Gafter, <i>Java
Puzzlers</i>. Addison Wesley 2005.
 */
static class Thrower {
    private static Throwable t;
    private Thrower() throws Throwable {
        throw t;
    }
    public static synchronized void sneakyThrow(Throwable t) {
        Thrower.t = t;
        try {
            Thrower.class.newInstance();
        } catch (InstantiationException e) {
            throw new IllegalArgumentException(e);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException(e);
        } finally {
            Thrower.t = null; // Avoid memory leak
        }
    }
}
}

A better approach (like an option to turn off lexer error recovery) seems a
good enhancement to a future version of ANTLR.  That said, this approach is
nice because it works in the way most folks client code would expect.

Regards,
Tim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.antlr.org/pipermail/antlr-interest/attachments/20080917/89da2a13/attachment.html 


More information about the antlr-interest mailing list