title: ANTLR4 - Is it possible to store a variable of a certain data type within a matched rule?
body: <p>I would like to somehow store a variable of a pre-determined type (or even an Object) within the matched rule, much like in GNU Bison, where you would define the type that each rule has and therefore the constructors and fields associated with them.</p>
  
  <p>For example (in GNU Bison), if I had predetermined that instances of the <strong>varAssign</strong> rule would be of type <code>TokenVarAssign</code>, which has a constructor and two fields (variable identifier and assignment expression), I could do the following:</p>
  
  <pre><code>varAssign: id '=' expr {$$ = new TokenVarAssign(); $$.id = $1; $$.expr = $3;}
  </code></pre>
  
  <p>Where <strong>$$</strong> represents the current token being matched (in this case, one of <strong>varAssign</strong>) and <strong>$n</strong> represents the nth token in the rule.</p>
  
  <p>Is it at all possible to achieve the same (or something similar) with ANTLR4.
  Up until now, I have been traversing the tree of <code>ParserRuleContext</code> objects after parsing the file and constructing my Token objects that way, which has turned out to be much less polymorphic and dynamic.</p>
  
  <p><strong>Edit in response to answer:</strong> With the following grammar file, I get the error below:</p>
  
  <pre><code>grammar Test ;
  
  INT: '0' .. '9' ;
  add [int x] returns [int result] : '+=' INT {$result = $x + $INT.int;} ;
  </code></pre>
  
  <p>Error:</p>
  
  <pre><code>$ antlr4 Test.g4
  error(50): Test.g4:4:4: syntax error: '[int x]' came as a complete surprise to me while matching rule preamble
  </code></pre>