Search code examples
javajavacc

JavaCC: Matching with wildcard but not consuming for state switch


In JavaCC, for example in state DEFAULT, I want to perform a state switch, if the next token is <A>, I want to switch to state STATE_A, otherwise, I want to switch to state STATE_B.

I tried to use something like the following code with "" as a wildcard:

TOKEN:
{
  <A: "aa"> : STATE_A
| <NOT_A: ""> : STATE_B
}

But it doesn't work, when a character that cannot be reduced to A is met, the function returns immediately, and doesn't get switched to STATE_B, therefore "" doesn't seem to be able to do the job.

Do you have any suggestions? Thanks.


Solution

  • Well I find that this actually works. The empty string will be matched when A cannot be matched, however we need to explicitly refer to NOT_A in the definitions of non-terminals. Therefore expressions like

    [ <A> ]
    

    should be rewritten as

    ( <A> | <NOT_A> )
    

    to enforce a state switch.