1

I am using antlr 'org.antlr:antlr4:4.9.2' and come across the "dangling else" ambiguity problem; see the following grammar IfStat.g4.

// file: IfStat.g4
grammar IfStat;

stat : 'if' expr 'then' stat
     | 'if' expr 'then' stat 'else' stat
     | expr
     ;

expr : ID ;

ID : LETTER (LETTER | [0-9])* ;
fragment LETTER : [a-zA-Z] ;

WS  : [ \t\n\r]+ -> skip ;

I tested this grammar against the input "if a then if b then c else d". It is parsed as `"if a then (if b then c else d)" as expected. How does ANTLR4 resolve this ambiguity?

hengxin
  • 1,867
  • 2
  • 21
  • 42

1 Answers1

2

ANTLR will choose the first possible (successful) path it is able to make.

You can enable ANTLR to report such ambiguities in your grammar. Check this Q&A for that: Ambiguity in grammar not reported by ANTLR

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288