title: ANTLR: From CommonTree to useful object graph
body: <p>I started using ANTLR today and I've created a basic parser.</p>
  
  <p>After parsing I end up with a tree. To me it seems like this is just a bunch of <code>String</code>s put together in a tree structure of <code>Tree</code>-nodes. That's not very useful to me. I'd like to have a graph of objects.</p>
  
  <p>To clarify (this is an example, and not my real application): For <code>"5-1+6"</code> I seem to end up with:</p>
  
  <pre><code>new String("PLUS")
      new String("MINUS")
          new String("5")
          new String("1")
      new String("6")
  </code></pre>
  
  <p>What I would find more useful:</p>
  
  <pre><code>new Plus(
      new Minus(
          new IntegerLiteral(5),
          new IntegerLiteral(1)),
      new IntegerLiteral(6))
  </code></pre>
  
  <p>What is the most convenient way of going from the first representation to the other? In <a href="http://zentapestry.wordpress.com/2008/02/27/antlr-interpreter-using-visitor-i-2/" rel="nofollow noreferrer">this article</a> the author does something similar to this:</p>
  
  <pre><code>public Expression createExpr(CommonTree ast) {
  
      // ...
  
      switch (ast.getType()) {
      case SimpleExpressionParser.INT:
          return new IntegerLiteral(ast.getText())
      case SimpleExpressionParser.PLUS:
          return new Plus(createExpr((CommonTree)ast.getChild(0)),    // recurse
                          createExpr((CommonTree)ast.getChild(1)));   // recurse
      case SimpleExpressionParser.MINUS:
          return new Minus(createExpr((CommonTree)ast.getChild(0)),   // recurse
                           createExpr((CommonTree)ast.getChild(1)));  // recurse
      }
  
      // ...
  }
  </code></pre>
  
  <p>Is this the preferred way?! Can't I instruct ANTLR to generate this boiler-plate code somehow (it will be huge)?</p>
  
  <hr>
  
  <p><strong>Possibly related questions:</strong></p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/2217173/converting-antlr-syntax-tree-into-useful-objects">Converting Antlr syntax tree into useful objects</a> (But I can't see how the answer answers my question.)</li>
  </ul>