JavaCC syntactic lookahead to the rescue

02 Mar 2006

There's been a grammar bug in PMD for a while; it wouldn't parse non-static initializers that started with a reference to a field, i.e.:

class Foo extends Bar {
 { 
   // Bar declares x, and Foo uses it
   x = 5; 
 }
}

This is fairly bizarre code, but it's certainly valid Java, and PMD was erroring out on it. Here's the fix:

Before: ! { LOOKAHEAD(3) Initializer()
After:  ! { LOOKAHEAD(["static"] "{" ) Initializer()

Instead of blindly looking ahead three tokens, JavaCC's syntactic lookahead lets us look for several specific tokens and choose the parser action based on those. Fun stuff!

Using JavaCC? Get the book - Generating Parsers With JavaCC!