In ANTLR v3, syntactic predicates could be used to solve e.g., the dangling else problem. ANTLR4 seems to accept grammars with similar ambiguities, but during parsing it rep
You can explicitly disallow an alternative in this type of situation by using a semantic predicate.
('else' e | {_input.LA(1) != ELSE}?)
You should be able to use the ??
operator instead of ?
to prefer associating the else
with the outermost if
. However, performance will suffer substantially. Another option is distinguishing matched if
/else
pairs separately from an unmatched if
.
ifStatement
: 'if' expression 'then' (statement | block) 'else' (statement | block)
| 'if' expression 'then' (statementNoIf | block)
;