title: ANTLR4 variable types and order of operations
body: <p>I have two grammars:</p>
  
  <p>Hello.g4:</p>
  
  <pre><code>grammar Hello;
  start: exp? EOF;
  exp: int_exp | vector_exp;
  int_exp: int_exp '*' int_exp | int_exp '+' int_exp | INT;
  vector_exp: vector_exp '*' int_exp | int_exp '*' vector_exp | 
              vector_exp '+' vector_exp | VECTOR;
  INT  : ('0'..'9') | (('1'..'9')('0'..'9')+);
  VECTOR: 'v';
  WS  : [ \t\r\n]+ -&gt; skip ;
  </code></pre>
  
  <p>Hello2.g4</p>
  
  <pre><code>grammar Hello2;
  start: exp? EOF;
  exp: add;
  add: add '+' add | mult '+' add | add '+' mult | mult;
  mult: mult '*' mult | INT '*' mult | mult '*' INT | INT | VECTOR;
  INT  : ('0'..'9') | (('1'..'9')('0'..'9')+);
  VECTOR: 'v';
  WS  : [ \t\r\n]+ -&gt; skip ;
  </code></pre>
  
  <p>The first grammar checks the types correctly: adding a vector to a scalar <code>v+1</code> doesnt work. But it fails to have the correct order of operations.</p>
  
  <p><code>1+1*v</code> gives </p>
  
  <p><a href="https://i.stack.imgur.com/YOBA4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YOBA4.png" alt="wrong order"></a></p>
  
  <p>The second grammar has the correct order, but allows <code>v+1</code>, which shouldnt work.</p>
  
  <p>I understand <em>why</em> the grammars work like that, but I fail to combine these two, creating a grammar that checks types and has the correct order of operations.</p>
  
  <p>Whatever I check first works, my problem is that I have to start somewhere breaking the thing that I do second. How would one combine these two requirements?</p>