3
votes

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 reports these ambiguities (e.g., "line 2:29 reportAmbiguity d=0 (e): ambigAlts={1, 2}, input=..."). It produces a parse tree, despite these ambiguities (by chosing the first alternative, according to the documentation). But what can I do, if I want it to chose some other alternative? In other words, how can I explicitly resolve ambiguities?

For example, the dangling else problem:

prog
    :   e EOF
    ;

e
    :   'if' e 'then' e ('else' e)?
    |   INT
    ;

With this grammar, from the input "if 1 then if 2 then 3 else 4", it builds this parse tree: (prog (e if (e 1) then (e if (e 2) then (e 3) else (e 4))) ).

What can I do, if for some reason, I want the other tree: (prog (e if (e 1) then (e if (e 2) then (e 3)) else (e 4)) ) ?

Edit: for a more complex example, see What to use in ANTLR4 to resolve ambiguities in more complex cases (instead of syntactic predicates)?)

1

1 Answers

4
votes
  • 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)
      ;