Created
March 6, 2014 18:31
-
-
Save melix/9396365 to your computer and use it in GitHub Desktop.
A demonstration on how to transform a local variable using a compilation customizer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.codehaus.groovy.ast.ClassCodeExpressionTransformer | |
import org.codehaus.groovy.ast.ClassNode | |
import org.codehaus.groovy.ast.expr.ConstantExpression | |
import org.codehaus.groovy.ast.expr.DeclarationExpression | |
import org.codehaus.groovy.ast.expr.Expression | |
import org.codehaus.groovy.classgen.GeneratorContext | |
import org.codehaus.groovy.control.CompilationFailedException | |
import org.codehaus.groovy.control.CompilePhase | |
import org.codehaus.groovy.control.CompilerConfiguration | |
import org.codehaus.groovy.control.SourceUnit | |
import org.codehaus.groovy.control.customizers.CompilationCustomizer | |
class MyTransformer extends ClassCodeExpressionTransformer { | |
private final SourceUnit unit | |
MyTransformer(SourceUnit unit) { | |
this.unit = unit | |
} | |
@Override | |
protected SourceUnit getSourceUnit() { | |
unit | |
} | |
@Override | |
Expression transform(final Expression exp) { | |
if (exp instanceof DeclarationExpression) { | |
return transformDeclaration(exp) | |
} | |
return super.transform(exp) | |
} | |
def transformDeclaration(final DeclarationExpression bin) { | |
if (bin.annotations.any { it.classNode.name == 'Foo' }) { | |
println "Hey, found it!: $bin.text" | |
bin.leftExpression = transform(bin.leftExpression) | |
bin.rightExpression = new ConstantExpression(null) | |
bin | |
} else { | |
super.transform(exp) | |
} | |
} | |
} | |
def config = new CompilerConfiguration() | |
config.addCompilationCustomizers(new CompilationCustomizer(CompilePhase.SEMANTIC_ANALYSIS) { | |
@Override | |
void call( | |
final SourceUnit source, | |
final GeneratorContext context, final ClassNode classNode) throws CompilationFailedException { | |
new MyTransformer(source).visitClass(classNode) | |
} | |
}) | |
def shell = new GroovyShell(config) | |
shell.evaluate ''' | |
@interface Foo {} | |
@Foo | |
String myVar | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment