Buenos
Buenos

Reputation: 25

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

Upvotes: 1

Views: 127

Answers (1)

Maurice Perry
Maurice Perry

Reputation: 9648

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 >
        )
}

Upvotes: 1

Related Questions