Groovy Quickie: Dumping the Groovy AST

Lately I had a strange bug in a project-specific AST transformation that caused me to look for ways to directly use the Groovy AST browser from within the affected components.

Printing the AST tree

I came accross this posting [0] by Cédric Champeau, himself one of the Groovy core comitters. In the mailing list Hamlet D'Arcy pointed to AstNodeToScriptAdapter [1], a class utilized by the AST browser to compile Groovy code to a given compile phase and decompile the result back to Groovy code. One way to add logging the AST tree to the console with this class would be to introduce a compilation customizer [2] and simply pass the current ClassNode instance to the script adapter: [source language="groovy"] class LoggingCompilationCustomizer extends CompilationCustomizer { final PrintStream out LoggingCompilationCustomizer(CompilePhase compilePhase, PrintStream out) { super(compilePhase) this.out = out } void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException { StringWriter writer = new StringWriter() new AstNodeToScriptVisitor(writer).visitClass(classNode) out.println writer } } [/source] Once the customizer is defined it can be used by registering it with a GroovyShell object: [source language="groovy"] def config = new CompilerConfiguration() config.addCompilationCustomizers(new LoggingCompilationCustomizer(CompilePhase.SEMANTIC_ANALYSIS, System.out)) shell = new GroovyShell(config) [/source]

Conclusion

The AstNodeToScriptVisitor is a class used by the Groovy AST browser to render Groovy code from a specific compile phase. When debugging AST transformations it can sometimes be an advantage to dump the actual AST source code to immediately see AST issues.

[0] Nabble: AST browser from code
[1] groovy.inspect.swingui.AstNodeToScriptAdapter
[2] org.codehaus.groovy.control.customizers.CompilationCustomizer