Created
February 24, 2014 06:55
-
-
Save azenla/9183112 to your computer and use it in GitHub Desktop.
Script Debugging AST Transformation
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.ASTNode | |
import org.codehaus.groovy.ast.expr.ArgumentListExpression | |
import org.codehaus.groovy.ast.expr.ConstantExpression | |
import org.codehaus.groovy.ast.expr.MethodCallExpression | |
import org.codehaus.groovy.ast.expr.VariableExpression | |
import org.codehaus.groovy.ast.stmt.ExpressionStatement | |
import org.codehaus.groovy.ast.stmt.Statement | |
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.SEMANTIC_ANALYSIS) | |
class ScriptDebugTransformation implements ASTTransformation { | |
@Override | |
void visit(ASTNode[] nodes, SourceUnit source) { | |
def oldStatements = source.AST.statementBlock.statements.clone() as List<Statement> | |
def newStatements = [] as List<Statement> | |
oldStatements.each { statement -> | |
if (statement instanceof ExpressionStatement) { | |
def expr = (statement as ExpressionStatement) | |
if (expr.expression instanceof MethodCallExpression) { | |
def call = expr.expression as MethodCallExpression | |
newStatements.add(createPrintln("[Debugger] ${call.text}")) | |
} | |
} | |
newStatements.add(statement) | |
} | |
newStatements.add(0, createPrintln("[Debugger] Starting Script '${source.name}'")) | |
newStatements.add(createPrintln("[Debugger] Ending Script '${source.name}'")) | |
source.AST.statementBlock.getStatements().clear() | |
source.AST.statementBlock.getStatements().addAll(newStatements) | |
} | |
private static Statement createPrintln(String message) { | |
return new ExpressionStatement( | |
new MethodCallExpression( | |
new VariableExpression("this"), | |
new ConstantExpression("println"), | |
new ArgumentListExpression( | |
new ConstantExpression(message) | |
) | |
) | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment