Skip to content

Instantly share code, notes, and snippets.

@nithril
Last active August 29, 2015 13:57
Show Gist options
  • Save nithril/9843242 to your computer and use it in GitHub Desktop.
Save nithril/9843242 to your computer and use it in GitHub Desktop.
AST Test
import groovy.transform.TypeChecked
import org.nigajuan.lilactu.indexer.core.Coerce
import org.testng.annotations.Test
class AstTest {
static class MyBean {
public MyBean(int a, int b) {
}
}
@Coerce
@TypeChecked
public MyBean createBean_Ok() {
return [10, 1000]
}
@Coerce
@TypeChecked
public MyBean createBean_NOk() {
return [10, 1000 , ""]
}
@Test
public void testCreateBean_Ok() {
createBean_Ok()
}
@Test
public void testCreateBean_NOk() {
createBean_NOk()
}
}
import org.codehaus.groovy.transform.GroovyASTTransformationClass
import java.lang.annotation.ElementType
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
import java.lang.annotation.Target
@Retention (RetentionPolicy.SOURCE)
@Target ([ElementType.METHOD])
@GroovyASTTransformationClass (classes = CoerceTransformation)
public @interface Coerce { }
import org.codehaus.groovy.ast.*
import org.codehaus.groovy.ast.expr.ArgumentListExpression
import org.codehaus.groovy.ast.expr.ConstructorCallExpression
import org.codehaus.groovy.ast.expr.ListExpression
import org.codehaus.groovy.ast.stmt.ReturnStatement
import org.codehaus.groovy.control.CompilePhase
import org.codehaus.groovy.control.SourceUnit
import org.codehaus.groovy.transform.ASTTransformation
import org.codehaus.groovy.transform.GroovyASTTransformation
@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
public class CoerceTransformation implements ASTTransformation {
void visit(ASTNode[] astNodes, SourceUnit sourceUnit) {
if (!astNodes) return
if (!astNodes[0]) return
if (!astNodes[1]) return
if (!(astNodes[0] instanceof AnnotationNode)) return
if (!(astNodes[1] instanceof MethodNode)) return
MethodNode annotatedMethod = astNodes[1]
ClassNode returnType = annotatedMethod.getReturnType()
new MyClassCodeVisitorSupport(sourceUnit, returnType).visitMethod(annotatedMethod)
}
static class MyClassCodeVisitorSupport extends ClassCodeVisitorSupport{
SourceUnit sourceUnit
ClassNode returnType
MyClassCodeVisitorSupport(SourceUnit sourceUnit, ClassNode returnType) {
this.sourceUnit = sourceUnit
this.returnType = returnType
}
@Override
void visitReturnStatement(ReturnStatement statement) {
if (statement.getExpression() instanceof ListExpression){
ListExpression listExpression = (ListExpression)statement.getExpression()
ArgumentListExpression argumentListExpression = new ArgumentListExpression()
argumentListExpression.expressions.addAll(listExpression.expressions)
ConstructorCallExpression callExpression = new ConstructorCallExpression(returnType , argumentListExpression)
statement.setExpression(callExpression)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment