[antlr-interest] parentheses sequence validation

Christopher Schultz christopher.d.schultz at comcast.net
Tue Jan 25 09:41:40 PST 2005


Martin,

> You need to check for the EOF condition. In your case your parser just
> stops parsing if it can't continue to match rules. The trailing ')' is
> silently ignored. Fix it by writing:
> 
> expr: LPAREN (expr)* RPAREN EOF!
> 
> ( EOF is the meta-token for the End-Of-File, the ! operator keeps it out
> of your parse tree).

I have a followup question about this. I wrote an expression evaluator 
that is similar to one of the examples available but supports strings, 
floating point, function calls, etc. and had the same sort of problem.

I changed by top-level expression to something like this:

    expr: some_lower_level_expr EOF ;

And half of my unit tests failed when using parenthesis. Anything ending 
in a ) would fail. For example:

    1 + 2

was fine but

    ( 1 + 2 )

would fail with a message like "expected ) but got NULL".

Just for kicks, I tried:

    ( 1 + 2 ))

but I got a similar message (or even worse, I think I got "expected ), 
got )" which is pretty silly.

I ended up doing this:

    expr: some_lower_level_expr EOF?


and made the EOF optional. Seems pretty stupid, but now everything works.

I posted a question a week or so about this with no response. Heres a link:

http://www.antlr.org/pipermail/antlr-interest/2005-January/010906.html

I'd love an explanation of why this happens.

Thanks,
-chris


More information about the antlr-interest mailing list