1

I'm using antlr4 with python2 target,

additive_expression returns [value] @init{$value = 0;}
  : multiplicative_expression ((PLUS_OPERATOR | MINUS_OPERATOR) multiplicative_expression)*

Since the ((PLUS_OPERATOR | MINUS_OPERATOR) multiplicative_expression) expression appears zero or multiple times,

I will need to access each of it separately then calculate the final value.

Any ideas? I've tried the following, non of them works

  1. use re = (...) and antlr says I can't define it for non-sets
  2. use op = (PLUS_OPERATOR | MINUS_OPERATOR) etc. but it always point to the last appearance of the expression
daisy
  • 22,498
  • 29
  • 129
  • 265

1 Answers1

1

Try something like this:

additive_expression returns [value] 
@init{$value = 0;}
 : e1=multiplicative_expression                  {$value = $e1.value;}
   ( PLUS_OPERATOR e2=multiplicative_expression  {$value += $e2.value;}
   | MINUS_OPERATOR e2=multiplicative_expression {$value -= $e2.value;}
   )*
 ;

Or better, use a visitor instead of embedding target code inside your grammar1.

1 ANTLR4 visitor pattern on simple arithmetic example

Community
  • 1
  • 1
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288