ANTLR: From CommonTree to useful object graph


Staff member
I started using ANTLR today and I've created a basic parser.

After parsing I end up with a tree. To me it seems like this is just a bunch of
s put together in a tree structure of
-nodes. That's not very useful to me. I'd like to have a graph of objects.

To clarify (this is an example, and not my real application): For
I seem to end up with:

new String("PLUS")
    new String("MINUS")
        new String("5")
        new String("1")
    new String("6")

What I would find more useful:

new Plus(
    new Minus(
        new IntegerLiteral(5),
        new IntegerLiteral(1)),
    new IntegerLiteral(6))

What is the most convenient way of going from the first representation to the other? In <a href="" rel="nofollow noreferrer">this article</a> the author does something similar to this:

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

    // ...

Is this the preferred way?! Can't I instruct ANTLR to generate this boiler-plate code somehow (it will be huge)?


<strong>Possibly related questions:</strong>

<li><a href="">Converting Antlr syntax tree into useful objects</a> (But I can't see how the answer answers my question.)</li>