Search code examples
javacc

Javacc left recursion


I need to implement this grammar

       Exp ::= Exp op Exp
           ::= Exp [ Exp ]
           ::= Exp . length
           ::= Exp . id ( ExpList )
           ::= INTEGER LITERAL
           ::= true
           ::= false
           ::= id
           ::= this
           ::= new int [ Exp ]
           ::= new id ()
           ::= ! Exp
           ::= ( Exp )

and this is what I have done so far

void Exp() :
{}
{
  ExpOp()            
| "INTEGER" "LITERAL"
| < TRUE >
| < FALSE >
| < ID >
| < THIS >
| < NEW > < INT > < LBR > Exp() < RBR >
| < NEW > < ID > < LPAR > < RPAR >
}

void ExpOp():
{}
{
    Exp() (
            (< OP > Exp())
          | (< LBR > Exp() < RBR >)
          | (< DOT >   ( < LEN >
                       | (< ID > < LPAR > ExpList() < RPAR >) )))
}
  

but I don't know how to remove left recursion for function Exp.

I tried to add another function ExpOp but this didn't work


Solution

  • Try something like this:

    void Exp() :
    {}
    {
        ExpOp() (
            < OP > Exp()
        | < LBR > Exp() < RBR >
        | < DOT > (
            < LEN >
            | < ID > < LPAR > ExpList() < RPAR >
            )
        )?
    }
    
    void ExpOp():
    {}
    {
        "INTEGER" "LITERAL"
        | < TRUE >
        | < FALSE >
        | < ID >
        | < THIS >
        | < NEW > (
            < INT > < LBR > Exp() < RBR >
            | < ID > < LPAR > < RPAR >
            )
    }