Access properties defined with in parentheses
<p>I'm using antlr4 with python2 target,</p>

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

<p>Since the <code>((PLUS_OPERATOR | MINUS_OPERATOR) multiplicative_expression)</code> expression appears zero or multiple times, </p>

<p>I will need to access each of it separately then calculate the final value.</p>

<p>Any ideas? I've tried the following, non of them works</p>

<ol>
<li>use <code>re = (...)</code> and antlr says I can't define it for non-sets</li>
<li>use <code>op = (PLUS_OPERATOR | MINUS_OPERATOR)</code> etc. but it always point to the last appearance of the expression</li>
</ol>

<p>Try something like this:</p>

<pre><code>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;}
   )*
 ;
</code></pre>

<p>Or better, use a visitor instead of embedding target code inside your grammar<sup>1</sup>.</p>

<p><sup>1</sup> <a href="http://stackoverflow.com/questions/23092081/antlr4-visitor-pattern-on-simple-arithmetic-example">ANTLR4 visitor pattern on simple arithmetic example</a></p>

python antlr antlr4