Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
AstNode node = new BlockStatement(
       [new ReturnStatement(
               new ConstantExpression("Hello")
       )],
       new VariableScope())

Advantages

...

Code Block
List<ASTNode> nodes = new AstBuilder().buildFromSpec {
       block {
               returnStatement {
                        constant "Hello"
               }
       }
}

Advantages

  • Allows conditionals (or any Groovy code) to be executed during the AST building process.
  • Allows any ASTNode subtype to be created
  • Fully documented with lengthy examples in TestCase

...

Code Block
List<ASTNode> result = new AstBuilder().buildFromSpec {
          method('myMethod', Opcodes.ACC_PUBLIC, String) {
                      parameters {
                                   parameter 'parameter': String.class
                      }
                      exceptions {}
                      block {
                                   owner.expression.addAll new AstBuilder().buildFromCode {
                                               println 'Hello from a synthesized method!'
                                               println "Parameter value: $parameter"
                                   }
                      }
                      annotations {}
          }
}

Further Resources

The test cases shipping with Groovy are an excellent resource.
More examples can be found in GEP-2, the original proposal. http://docs.codehaus.org/display/GroovyJSR/GEP+2+-+AST+Builder+Support
Examples and questions can be found on the groovy-user and groovy-dev mailing lists.