mike27
mike27

Reputation: 975

Convert AST nodes string to groovy code

I want to create groovy code using AstBuilder, but afterwards, I'd like to see how the actual groovy code would look like. Is it possible to convert AST nodes' toString output like this:

org.codehaus.groovy.ast.stmt.BlockStatement@5b7a5baa[
org.codehaus.groovy.ast.stmt.ExpressionStatement@776aec5c[
expression:org.codehaus.groovy.ast.expr.DeclarationExpression@1d296da[
org.codehaus.groovy.ast.expr.VariableExpression@7c7a06ec[
variable: cl]("=" at 2:17:  "=" )org.codehaus.groovy.ast.expr.ClosureExpression@13c9d689[
]{ org.codehaus.groovy.ast.stmt.BlockStatement@75d4a5c2[
] }]]]

back into groovy code?

Upvotes: 2

Views: 1451

Answers (2)

Michael Klenk
Michael Klenk

Reputation: 3232

The class AstNodeToScriptVisitor is now part of the groovy sub project groovy-console package. Here you found now the class to generate code from an AST node.

def writer = new StringWriter()
def visitor = new groovy.console.ui.AstNodeToScriptVisitor(writer)
visitor.visitClass(demoClass)
println writer

In your project you can import this package for example via Gradle.

implementation group: 'org.codehaus.groovy', name: 'groovy-console', version: '3.0.11'

Upvotes: 0

bsideup
bsideup

Reputation: 3063

You can use my favourite code snippet which I use when I work with AST transformations:

java.io.StringWriter writer = new java.io.StringWriter();
groovy.inspect.swingui.AstNodeToScriptVisitor visitor = new groovy.inspect.swingui.AstNodeToScriptVisitor(writer);
visitor.visitClass(node); // replace with proper visit****
System.out.println(writer.toString());

It will provide almost correct Groovy code from it. It's still not 100% correct (I mean, if you will compile it back then it might not compile), but more than enough for debugging.

Example in MacroGroovy:

https://github.com/bsideup/MacroGroovy/blob/950193cb2d12443bf0c7b7af9635f24712d3bad0/src/main/groovy/ru/trylogic/groovy/macro/MacroTransformation.java#L58

Upvotes: 4

Related Questions