JavaCC: How can I specify which token(s) are expected in certain context?

Posted by java.is.for.desktop on Stack Overflow See other posts from Stack Overflow or by java.is.for.desktop
Published on 2010-04-29T06:40:15Z Indexed on 2010/04/29 6:47 UTC
Read the original article Hit count: 209

Filed under:
|
|
|
|

Hello, everyone!

I need to make JavaCC aware of a context (current parent token), and depending on that context, expect different token(s) to occur.

Consider the following pseudo-code:

TOKEN <abc> { "abc*" } // recognizes "abc", "abcd", "abcde", ...
TOKEN <abcd> { "abcd*" } // recognizes "abcd", "abcde", "abcdef", ...

TOKEN <element1> { "element1" "[" expectOnly(<abc>) "]" }
TOKEN <element2> { "element2" "[" expectOnly(<abcd>) "]" }
...

So when the generated parser is "inside" a token named "element1" and it encounter "abcdef" it recognizes it as <abc>, but when its "inside" a token named "element2" it recognizes the same string as <abcd>.

element1 [ abcdef ] // aha! it can only be <abc>
element2 [ abcdef ] // aha! it can only be <abcd>

If I'm not wrong, it would behave similar to more complex DTD definitions of an XML file.

So, how can one specify, in which "context" which token(s) are valid/expected?

NOTE: It would be not enough for my real case to define a kind of "hierarchy" of tokens, so that "abcdef" is always first matched against <abcd> and than <abc>. I really need context-aware tokens.

© Stack Overflow or respective owner

Related posts about java

Related posts about javacc