title: Combining ANTLR and Code Files
body: <p>I'm in the process of creating a Java analyzer for an ANTLR grammar that someone else is writing.</p>
  
  <p>Is it possible to combine ANTLR files so that I can add my bracketed Java code to the ANTLR-generated Java files through a file separate from the original grammar (.g) file? I've investigated composite grammars, but it doesn't seem as though I can import the existing grammar as a combined lexer/parser.</p>
  
  <p>For instance, can I do something like this:</p>
  
  <p><strong>Grammar.g</strong></p>
  
  <pre><code>grammar Grammar;
  
  statement   : first=WORD ';' ;
  WORD        : ('A'..'z')* ;
  </code></pre>
  
  <p><strong>JavaGrammar.g</strong></p>
  
  <pre><code>grammar JavaGrammar;
  imports Grammar;
  
  @header {
      package pkg;
      import Container;
  }
  
  @lexer::header {
      package pkg;
  }
  
  @members{
      Container c = null;
      public void setContainer(Container c) { this.c = c; }
  
      @Override
      protected Object recoverFromMismatchedToken(IntStream input, int ttype, BitSet follow) throws RecognitionException {
        throw new MismatchedTokenException(ttype, input);
      }
  
      @Override
      public Object recoverFromMismatchedSet(IntStream input, RecognitionException e, BitSet follow) throws RecognitionException {
        throw e;
      }
  }
  
  @rulecatch {
      catch (RecognitionException e) {
          throw e;
      }
  }
  
  jStatement: statement { if(c!=null) c.add($first.text); } ;
  </code></pre>