Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to lookahead in ANTLR4 without actually matching a token?

Tags:

antlr4

I am writing a compiler by translating JavaCC to ANTLR4 and one of the rules involve passing parameters and getting return values from it.

I have to do something like the following for a rule 'term':

Term term(ReadOptions options, int priority):
{
  int p = options.operatorSet.getNextLevel(priority);
  Term t;
}
{
  (
    LOOKAHEAD({p==0})
    t = simpleTerm(options)
  |
    LOOKAHEAD(<NAME_TOKEN>,{priority==1201 && is1201Separator(2)})
    t = name()
  |
    t = operatorTerm(options, p)
  )
  {return t;}
}

The problem is that how do I match sub-rules on the basis of the value of 'p'. In the previous versions of ANTLR I could have used => and my problem would have solved but what do I do in ANTLR4 ?

like image 599
Rishabh Garg Avatar asked Oct 19 '25 01:10

Rishabh Garg


1 Answers

The => operator in previous versions of ANTLR is no longer necessary in ANTLR 4.

  • ANTLR 4 does not support syntactic predicates because its lookahead algorithm fully supports infinite lookahead. If you used the form (x) => y previously, in ANTLR 4 you can simply use y.
  • Semantic predicates are still supported, but in ANTLR 4 all semantic predicates work like gated semantic predicates in ANTLR 3. If you used the form {x}? => y previously, then in ANTLR 4 you can simply use {x}? y.
like image 120
Sam Harwell Avatar answered Oct 22 '25 04:10

Sam Harwell