title: Antlr4 grammar - trouble identifying grammar
body: <p>I'm working with Antlr4 to parse a boolean-like DSL. </p>
  
  <p>Here is my grammar:</p>
  
  <pre><code>grammar filter;
  
  filter: overall EOF;
  
  overall
      : LPAREN overall RPAREN 
      | category
      ;
  
  category
      : expression # InferenceCategory
      | category AND category # CategoryAndBlock
      | label COLON expression # CategoryBlock
      | LPAREN category RPAREN # NestedCategory
      ;
  
  expression
      : NOT expression            # NotExpr
      | expression AND expression  # AndExpr
      | expression OR expression   # OrExpr
      | atom                      # AtomExpr
      | LPAREN expression RPAREN  # NestedExpression
      ;
  
  label
      : ALPHANUM
      ;
  
  atom 
      : ALPHANUM
      ;
  </code></pre>
  
  <p>Here is an example input string to parse:</p>
  
  <blockquote>
    <p>(cat1:(1 OR 2) AND cat2:( 4 ))</p>
  </blockquote>
  
  <p>This grammar works fine with this input; it produces the following parse tree which perfectly suits my needs:</p>
  
  <p><a href="https://i.stack.imgur.com/ucz77m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ucz77m.png" alt="enter image description here"></a></p>
  
  <p>However, there is weird case of the DSL, where the "cat1" label is implicit when no other category is specified. This is what the InferenceCategory tag catches, where this expression will be handled as a category in my code later. </p>
  
  <p>For example, with</p>
  
  <blockquote>
    <p>((1 OR 2) AND cat2:( 4 ))</p>
  </blockquote>
  
  <p>I get (as expected):</p>
  
  <p><a href="https://i.stack.imgur.com/7pmJ1m.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7pmJ1m.png" alt="enter image description here"></a></p>
  
  <p>However, in the following instance: </p>
  
  <blockquote>
    <p>cat2:( 4 ) AND (1 OR 2)</p>
  </blockquote>
  
  <p>I get:</p>
  
  <p><a href="https://i.stack.imgur.com/bI2anm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bI2anm.png" alt="enter image description here"></a></p>
  
  <p>Notice that the second block is not identified as a InferenceCategory and but instead as a normal expression, under the first category. This is because there the grammar parses ( 4 ) following cat2: as a normal expression, and everything past that is parsed as a normal expression.</p>
  
  <p>Is there any way to fix this? I've tried:</p>
  
  <p><code>label COLON expression (AND category)* # CategoryBlock</code> 
  (which doesn't work)</p>
  
  <p>and </p>
  
  <p><code>category AND category AND category</code>
  (which "works", but is extremely hacky and only works in the specific case that I have exactly three categories. Any more, and it breaks again.)</p>