title: Overcoming ambiguity in antlr4?
body: <p>I have the grammar below, it's an extract out of something I am working on which is highlighting a problem I can't overcome.</p>
  
  <p>In my grammar an expression is either a literal, which is a number or an expression "+" another expression. So I want to parse:</p>
  
  <pre><code>1 + 2 + 3 + 4
  </code></pre>
  
  <p>etc.</p>
  
  <p>However my definition of a number means that it can have an optional sign e.g.:</p>
  
  <p><code>1</code>, <code>+1</code> or <code>-1</code></p>
  
  <p>So it's conceivable that I may need to parse:</p>
  
  <p><code>1 + +1</code> or <code>1 + -1</code></p>
  
  <p>What I am finding is that <code>1 + 1</code> (or bigger numbers) are fine.</p>
  
  <p>What I am struggling to parse are inputs without spaces or with extra signs e.g.:</p>
  
  <p><code>1+2</code></p>
  
  <p>This causes real problems as the lexer picks up <code>+2</code> as a Number when actually I want <code>2</code> as the number and <code>+</code> to be picked up as the sign in the expression.</p>
  
  <p>How do I get antlr4 to recognise the difference?</p>
  
  <pre><code>grammar example;
  
  example : expression* EOF;
  
  expression 
      :  expression '+' expression
      |  literal
      ;
  
  literal : Number;
  
  Number : Sign? Digits;
  
  Sign : [-+];
  
  Digits : Digit+;
  
  Digit : [0-9];
  
  WS : [ \t\r\n\u000C]+ -&gt; skip;
  </code></pre>