title: How does the ANTLR lexer disambiguate its rules (or why does my parser produce "mismatched input" errors)?
body: <blockquote>
    <p><strong>Note:</strong> This is a <a href="https://stackoverflow.blog/2011/07/01/its-ok-to-ask-and-answer-your-own-questions/">self-answered question</a> that aims to provide a reference about one of the most common mistakes made by ANTLR users.</p>
  </blockquote>
  
  <hr>
  
  <p>When I test this very simple grammar:</p>
  
  <pre><code>grammar KeyValues;
  
  keyValueList: keyValue*;
  keyValue: key=IDENTIFIER '=' value=INTEGER ';';
  
  IDENTIFIER: [A-Za-z0-9]+;
  INTEGER: [0-9]+;
  
  WS: [ \t\r\n]+ -&gt; skip;
  </code></pre>
  
  <p>With the following input:</p>
  
  <pre><code>foo = 42;
  </code></pre>
  
  <p>I end up with the following run-time error:</p>
  
  <blockquote>
    <p>line 1:6 mismatched input '42' expecting INTEGER<br>
    line 1:8 mismatched input ';' expecting '='</p>
  </blockquote>
  
  <p>Why doesn't ANTLR recognize <code>42</code> as an <code>INTEGER</code> in this case?<br>
  It should match the pattern <code>[0-9]+</code> just fine.</p>
  
  <p>If I invert the order in which <code>INTEGER</code> and <code>IDENTIFIER</code> are defined it seems to work, but why does the order matter in the first place?</p>