[antlr-interest] Over-eager lexer?

Michael Coupland mcoupland at gmail.com
Mon Nov 30 15:27:40 PST 2009


I'm trying to use ANTLR to extract portions of a text file, and I'm
having a strange lexer problem. I've boiled my problem down to a
pretty simple case:

I want to match the interesting segments of C-like input, as
delineated by the keyword 'interesting' and matching braces:

        /* blah blah blah - this part should be ignored */
        interesting { /* this is the part */ { /* that is matched */ } }
        /* also ignored */

Here's my ANTLR file:

        grammar test;

        : ignored_segment (interesting_segment ignored_segment)*

        : ( ~ INTERESTING_KEYWORD )*

        : INTERESTING_KEYWORD brace_scope

        : OPEN_BRACE (
          ( options {greedy=true;} : ~( OPEN_BRACE | CLOSE_BRACE )
          | brace_scope )
        )* CLOSE_BRACE

        : (' '|'\t'|'\n'|'\r')+

        INTERESTING_KEYWORD : 'interesting' ;
        OPEN_BRACE : '{' ;
        CLOSE_BRACE : '}' ;
        UNMATCHED : . ;

When I run the grammar on the following input, I get the expected behavior.

        interesting { xxx }

However, running a slightly different input through the ANTLRWorks
debugger (or C runtime generated code) gives an error:

        interesting { xxx }

I get the following lexer complaint in the debugger output:

        line 1:5 mismatched character 'g' expecting 't'

It's like the lexer sees the 'in' in 'boring' and then refuses to give
up trying to match an 'interesting' token. Can someone explain why
this is happening, and how to solve it? I realize I'm kinda abusing
the lexer/parser, but the grammar seems like the best way to
accomplish my goal.


PS. I’m vaguely aware of the concept of filter lexers, but I don’t
think I can do the brace matching I need with them? Also, I can’t
meaningfully test them in ANTLRWorks, since it doesn’t show the lexer
results. I rely on ANTLRWorks heavily to author my grammars before
running them in the ANTLR C Runtime.

More information about the antlr-interest mailing list