1

The stm and stmList gives me this error, it seems that ANTLR see it like a possible infinite recursion loop. How can I avoid it? The following sets of rules are mutually left-recursive [stmList]

stmList: stm stmList | ;
stm: ifStm | whStm;

ifStm: ifPart elifPart* elsePart?;
ifPart: IF LB exp RB CLB stmList CRB;
elifPart: ELIF LB exp RB CLB stmList CRB;
elsePart: ELSE CLB stmList CRB;

whStm: WHILE LB exp RB CLB stmList CRB;

LB: '(';
RB: ')';
CLB: '{';
CRB: '}';
WHILE: 'While';
IF: 'If';
ELIF: 'Elif';
ELSE: 'Else';
Duy Duy
  • 521
  • 1
  • 4
  • 9
  • 1
    The `stmList` rule is right-recursive. There's no left recursion here. – Chris Dodd Apr 15 '21 at 02:58
  • but ANTLR displays that error – Duy Duy Apr 15 '21 at 06:09
  • 2
    @DuyDuy that could be, but not with the rules you posted. You've trimmed down the grammar too much. If you decide to strip the code/grammar and post it on SO, always make sure the original error is still being produced. I recommend posting the entire grammar. – Bart Kiers Apr 15 '21 at 07:08
  • @BartKiers you're right. I haven't define production for forStm that has been trimmed down – Duy Duy Apr 15 '21 at 18:36

1 Answers1

2

This is probably because of the empty alt in stmList, though I also wonder why this error comes up. It doesn't seem right. However, I recommend not to use empty alts anyway, unless you guard the other alt(s) with a predicate and "call" the containing rule unconditionally. This can easily lead to problems when you forget that. Instead remove the empty alt and make the call optional:

stmList: stm stmList;
elsePart: ELSE CLB stmList? CRB;

Additionally, stmList looks pretty much like you would do such a definition in yacc, where no EBNF suffixes are possible. Instead just write:

stmList: stm+;

Mike Lischke
  • 48,925
  • 16
  • 119
  • 181