Flat Infix Operator

30 views
Skip to first unread message

Robert Jacobson

unread,
Mar 2, 2015, 8:21:29 PM3/2/15
to antlr-di...@googlegroups.com
I have a silly question about writing an ANTLR4 expression grammar with a flat infix operator. I want "1+2+3" to parse as (PLUS 1 2 3) rather than (PLUS (PLUS 1 2) 3). So consider this grammar:

expr

: LEAF

| LPAREN expr RPAREN //parentheses

| <assoc=right> expr POWER expr //exponentiation

| expr MUL expr //multiplication

| expr PLUS expr //addition

;


This of course gives the left associativity I'm trying to avoid. If I modify the addition alternative as follows,

| expr (PLUS expr)+ //addition


then PLUS becomes right associative! Is there a way to coax ANTLR to give me (PLUS 1 2 3)? Or do I need to "flatten" after the fact?

Best,

Robert


Reply all
Reply to author
Forward
0 new messages