1
votes

Consider the following ANTLR 4 grammar:

grammar Test;

start: e EOF;

e : e '+' e     #op
  | NUMBER      #atom
  ;

NUMBER: [0-9]+;

Based on the disambiguation rules of ANTLR, in this case binary operators being left associative, the result of parsing the string 1+2+3 is ((1+2)+3). But there is another parse tree possible, namely (1+(2+3)), if you don't consider the ANTLR's default disambiguation rule.

Is there a way to get both parse trees in ANTLR? Or at least enabling a flag or something, so that it tells me that there was another parse tree and possibly print it?

Update I understand that in ANTLR, this grammar is unambiguous, because binary operators are always left-associative, but I couldn't come up with another example. My whole point is that I'd like to get an warning (or something similar) whenever ANTLR tries to resolve the ambiguity. For example, in good old Yacc (Bison), if I have the same grammar:

s : e
  ;

e : e '+' e
  | NUMBER
  ;

when generating the parser, I get the warning State 6 conflicts: 1 shift/reduce.

1
Don't forget Bison generates botton-up parsers, while ANTLR4 creates top-down parsers. Hence what is ambiquious for one parser might not for the other.Mike Lischke

1 Answers

0
votes

There's no ambiquity in this small grammar. There are 2 alts in e each with a definitive path. An ambiquity would be something like this:

e = a b | a c;

where a parser needs some lookahead to determine which path to take. But back to your parse tree question. What you want is to define a different associativity. Normally, all operators are left-associative by default leading to this parse tree:

enter image description here

defining the operator + to be right-associative like so:

grammar Example;

start: e EOF;

e : <assoc=right> e '+' e     #op
  | NUMBER      #atom
;

NUMBER: [0-9]+;

leads to:

enter image description here

Update

In order to get notified whenever an ambiquity is found your error listeners reportAmbiguity function is triggered. Override that to do your own handling in this situation.