antlr4: Precedence and Left-recursion Bug?

I’m trying to write a grammar that supports functions calls without using parentheses:

f x, y

As in Haskell, I’d like function calls to minimally slurp up their parameters. That is, I want

g 5 + 3

to mean

(g 5) + 3

instead of

g (5 + 3)

Unfortunately, I’m getting the second parse with this grammar:

grammar Parameters;

expr
  : '(' expr ')'
  | expr MULTIPLICATIVE_OPERATOR expr
  | expr ADDITIVE_OPERATOR expr
  | ID (expr (',' expr)*?)??
  | INT
  ;

MULTIPLICATIVE_OPERATOR: [*/%];
ADDITIVE_OPERATOR: [-+];

ID: [a..z]+;
INT: '-'? [0-9]+;
WHITESPACE: [ \t\n\r]+ -> skip;

The parse tree I’m getting is this:

Not the parse tree I want

I had thought that the subrule listed first would get attempted first. In this case, expr ADDITIVE_OPERATOR expr appears before the ID subrule, so why is the ID subrule taking higher precedence?

I’m running ANTLR 4.5. Thanks for any help!

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 22 (11 by maintainers)

Most upvoted comments

when making a decision in test (it is ambiguous btw) for 1 + 1 and matches it to first exprD term in first alt of test then matches GR then 0 matches for exprD.