title: How do I pretty-print productions and line numbers, using ANTLR4?
body: <p>I'm trying to write a piece of code that will take an ANTLR4 parser and use it to generate ASTs for inputs similar to the ones given by the -tree option on grun (<code>misc.TestRig</code>).  However, I'd additionally like for the output to include all the line number/offset information.  </p>
  
  <p>For example, instead of printing</p>
  
  <pre><code>(add (int 5) '+' (int 6))
  </code></pre>
  
  <p>I'd like to get</p>
  
  <pre><code>(add (int 5 [line 3, offset 6:7]) '+' (int 6 [line 3, offset 8:9]) [line 3, offset 5:10])
  </code></pre>
  
  <p>Or something similar.</p>
  
  <p>There aren't a tremendous number of visitor examples for ANTLR4 yet, but I am pretty sure I can do most of this by copying the default implementation for <code>toStringTree</code> (used by grun).  However, I do not see any information about the line numbers or offsets. </p>
  
  <p>I expected to be able to write super simple code like this:</p>
  
  <pre><code>String visit(ParseTree t) {
      return "(" + t.productionName + t.visitChildren() + t.lineNumber + ")";
  }
  </code></pre>
  
  <p>but it doesn't seem to be this simple.  I'm guessing I should be able to get line number information from the parser, but I haven't figured out how to do so.  How can I grab this line number/offset information in my traversal?</p>
  
  <hr />
  
  <p>To fill in the few blanks in the solution below, I used:</p>
  
  <pre><code>List&lt;String&gt; ruleNames = Arrays.asList(parser.getRuleNames());
  parser.setBuildParseTree(true);
  ParserRuleContext prc = parser.program();
  ParseTree tree = prc;
  </code></pre>
  
  <p>to get the <code>tree</code> and the <code>ruleNames</code>.  <code>program</code> is the name for the top production in my grammar.</p>