Search code examples
parsinggrammarjavacc

How to match 0 tokens in JavCC


I'm fairly new at javaCC and I'm trying to create a miniJava parser but I dont know how to skip a semantic action.

 SKIP : /* Definition of white-space and comments here */
    {
       " "
      | "\t"
      | "\n"
      | "\r"
      | "\f"
  |  < "//" (~["\n","\r"])* ("\n"|"\r"|"\r\n") >
}

TOKEN : /* Definition of the MiniJava tokens here. */
{
  < NUM: (["0"-"9"])+ >
| < LPAREN: "(" >
| < RPAREN: ")" >
| < COMMA: "," >
| < IDENTIFIER: ["a"-"z","A"-"Z"](["a"-"z","A"-"Z","0"-"9","_"])* >

...

This is the method that im trying to use the skip on.

public void nt_FormalList() :
{}
{
    nt_Type() <IDENTIFIER> (nt_FormalRest())*
    | SKIP
}

public void nt_FormalRest() :
{}
{
    <COMMA> nt_Type() <IDENTIFIER>
}

public void nt_Type() :
{}
{
    <INT>
  | <BOOLEAN>
  | <INT> <LSQBR> <RSQBR>
  | <IDENTIFIER>
} 

Solution

  • I'm guessing that you don't want a "space" at all, but rather that you want no tokens. In Java "" and " " are both valid formal parameter lists; no space is required. So I think what you want is

    public void nt_FormalList() :
    {}
    {
        [ nt_Type() <IDENTIFIER> (nt_FormalRest())* ]
    }
    

    The square brackets indicate that the stuff in between is optional.