N-ary operators in ANTLR4 grammar

Viewed 61

I have a grammar for parsing boolean formulas:

expr: op=NOT right=expr                                   #Not
    | left=expr op=AND right=expr                         #And
    | left=expr op=OR right=expr                          #Or
    | left=expr op=XOR right=expr                         #Xor
    | <assoc=right> left=expr op=IMPL right=expr          #Implication
    | <assoc=right> left=expr op=EQ right=expr            #Equivalence
    | boolean=BOOL                                        #Boolean
    | '(' content=expr+ ')'                               #Brackets
    | atomic=ATOMIC                                       #Atomic
    ;
BOOL        : TRUE|FALSE;
NOT         : ('!'|'not');
AND         : ('&'|'and');
OR          : ('|'|'or');
XOR         : ('^'|'xor');
IMPL        : '->';
EQ          : '<->';
TRUE        : ('True'|'true');
FALSE       : ('False'|'false');
ATOMIC      : [a-z]+([_]?[a-z]+)*;
WS          : [ \t\n]+ -> skip;       //Skip whitespaces

How can I change AND, OR, and XOR to be n-ary instead of binary (so that the children of these operators are on the same level)? I tried replacing left=expr op=AND right=expr with expr (op=AND expr)+, which does not change anything.

1 Answers

Something like this would do the trick:

expr
 : <assoc=right> expr IMPL expr
 | <assoc=right> expr EQ expr
 | xor_expr
 ;

xor_expr
 : or_expr (XOR or_expr)*
 ;

or_expr
 : and_expr (OR and_expr)*
 ;

and_expr
 : unary (AND unary)*
 ;

unary
 : NOT atom
 | atom
 ;

atom
 : BOOL
 | '(' expr+ ')'
 | ATOMIC
 ;
Related