use of org.codehaus.groovy.ast.ClassCodeExpressionTransformer in project groovy by apache.
the class LogASTTransformation method visit.
public void visit(ASTNode[] nodes, final SourceUnit source) {
init(nodes, source);
AnnotatedNode targetClass = (AnnotatedNode) nodes[1];
AnnotationNode logAnnotation = (AnnotationNode) nodes[0];
final GroovyClassLoader classLoader = compilationUnit != null ? compilationUnit.getTransformLoader() : source.getClassLoader();
final LoggingStrategy loggingStrategy = createLoggingStrategy(logAnnotation, classLoader);
if (loggingStrategy == null)
return;
final String logFieldName = lookupLogFieldName(logAnnotation);
final String categoryName = lookupCategoryName(logAnnotation);
if (!(targetClass instanceof ClassNode))
throw new GroovyBugError("Class annotation " + logAnnotation.getClassNode().getName() + " annotated no Class, this must not happen.");
final ClassNode classNode = (ClassNode) targetClass;
ClassCodeExpressionTransformer transformer = new ClassCodeExpressionTransformer() {
private FieldNode logNode;
@Override
protected SourceUnit getSourceUnit() {
return source;
}
public Expression transform(Expression exp) {
if (exp == null)
return null;
if (exp instanceof MethodCallExpression) {
return transformMethodCallExpression(exp);
}
if (exp instanceof ClosureExpression) {
return transformClosureExpression((ClosureExpression) exp);
}
return super.transform(exp);
}
@Override
public void visitClass(ClassNode node) {
FieldNode logField = node.getField(logFieldName);
if (logField != null && logField.getOwner().equals(node)) {
addError("Class annotated with Log annotation cannot have log field declared", logField);
} else if (logField != null && !Modifier.isPrivate(logField.getModifiers())) {
addError("Class annotated with Log annotation cannot have log field declared because the field exists in the parent class: " + logField.getOwner().getName(), logField);
} else {
logNode = loggingStrategy.addLoggerFieldToClass(node, logFieldName, categoryName);
}
super.visitClass(node);
}
private Expression transformClosureExpression(ClosureExpression exp) {
if (exp.getCode() instanceof BlockStatement) {
BlockStatement code = (BlockStatement) exp.getCode();
super.visitBlockStatement(code);
}
return exp;
}
private Expression transformMethodCallExpression(Expression exp) {
Expression modifiedCall = addGuard((MethodCallExpression) exp);
return modifiedCall == null ? super.transform(exp) : modifiedCall;
}
private Expression addGuard(MethodCallExpression mce) {
// only add guard to methods of the form: logVar.logMethod(params)
if (!(mce.getObjectExpression() instanceof VariableExpression)) {
return null;
}
VariableExpression variableExpression = (VariableExpression) mce.getObjectExpression();
if (!variableExpression.getName().equals(logFieldName) || !(variableExpression.getAccessedVariable() instanceof DynamicVariable)) {
return null;
}
String methodName = mce.getMethodAsString();
if (methodName == null)
return null;
if (!loggingStrategy.isLoggingMethod(methodName))
return null;
// since there is no saving
if (usesSimpleMethodArgumentsOnly(mce))
return null;
variableExpression.setAccessedVariable(logNode);
return loggingStrategy.wrapLoggingMethodCall(variableExpression, methodName, mce);
}
private boolean usesSimpleMethodArgumentsOnly(MethodCallExpression mce) {
Expression arguments = mce.getArguments();
if (arguments instanceof TupleExpression) {
TupleExpression tuple = (TupleExpression) arguments;
for (Expression exp : tuple.getExpressions()) {
if (!isSimpleExpression(exp))
return false;
}
return true;
}
return !isSimpleExpression(arguments);
}
private boolean isSimpleExpression(Expression exp) {
if (exp instanceof ConstantExpression)
return true;
if (exp instanceof VariableExpression)
return true;
return false;
}
};
transformer.visitClass(classNode);
// GROOVY-6373: references to 'log' field are normally already FieldNodes by now, so revisit scoping
new VariableScopeVisitor(sourceUnit, true).visitClass(classNode);
}
use of org.codehaus.groovy.ast.ClassCodeExpressionTransformer in project groovy by apache.
the class MapConstructorASTTransformation method makeMapTypedArgsTransformer.
private static ClassCodeExpressionTransformer makeMapTypedArgsTransformer() {
return new ClassCodeExpressionTransformer() {
@Override
public Expression transform(Expression exp) {
if (exp instanceof ClosureExpression) {
ClosureExpression ce = (ClosureExpression) exp;
ce.getCode().visit(this);
} else if (exp instanceof VariableExpression) {
VariableExpression ve = (VariableExpression) exp;
if (ve.getName().equals("args") && ve.getAccessedVariable() instanceof DynamicVariable) {
VariableExpression newVe = new VariableExpression(new Parameter(MAP_TYPE, "args"));
newVe.setSourcePosition(ve);
return newVe;
}
}
return exp.transformExpression(this);
}
@Override
protected SourceUnit getSourceUnit() {
return null;
}
};
}
use of org.codehaus.groovy.ast.ClassCodeExpressionTransformer in project groovy by apache.
the class ContextualClassCodeVisitor method popContext.
protected TreeContext popContext() {
final TreeContext treeContext = treeContextStack.pop();
List<TreeContextAction> actions = treeContext.getOnPopHandlers();
for (TreeContextAction contextAction : actions) {
contextAction.call(treeContext);
}
lastContext = treeContext;
ASTNode parentNode = treeContext.parent != null ? treeContext.parent.node : null;
if (treeContext.node instanceof Expression && parentNode != null) {
ClassCodeExpressionTransformer trn = new ClassCodeExpressionTransformer() {
@Override
protected SourceUnit getSourceUnit() {
return null;
}
@Override
public Expression transform(final Expression exp) {
if (exp == treeContext.node) {
Expression replacement = treeContext.getReplacement();
if (replacement != null) {
return replacement;
}
}
return super.transform(exp);
}
};
// todo: reliable way to call the transformer
//parentNode.visit(trn);
}
return treeContext;
}
use of org.codehaus.groovy.ast.ClassCodeExpressionTransformer in project groovy-core by groovy.
the class CategoryASTTransformation method visit.
/**
* Property invocations done on 'this' reference are transformed so that the invocations at runtime are
* done on the additional parameter 'self'
*/
public void visit(ASTNode[] nodes, final SourceUnit source) {
if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof ClassNode)) {
source.getErrorCollector().addError(new SyntaxErrorMessage(new SyntaxException("@Category can only be added to a ClassNode but got: " + (nodes.length == 2 ? nodes[1] : "nothing"), nodes[0].getLineNumber(), nodes[0].getColumnNumber()), source));
}
AnnotationNode annotation = (AnnotationNode) nodes[0];
ClassNode parent = (ClassNode) nodes[1];
ClassNode targetClass = getTargetClass(source, annotation);
thisExpression.setType(targetClass);
final LinkedList<Set<String>> varStack = new LinkedList<Set<String>>();
if (!ensureNoInstanceFieldOrProperty(source, parent))
return;
Set<String> names = new HashSet<String>();
for (FieldNode field : parent.getFields()) {
names.add(field.getName());
}
for (PropertyNode field : parent.getProperties()) {
names.add(field.getName());
}
varStack.add(names);
final Reference parameter = new Reference();
final ClassCodeExpressionTransformer expressionTransformer = new ClassCodeExpressionTransformer() {
protected SourceUnit getSourceUnit() {
return source;
}
private void addVariablesToStack(Parameter[] params) {
Set<String> names = new HashSet<String>();
names.addAll(varStack.getLast());
for (Parameter param : params) {
names.add(param.getName());
}
varStack.add(names);
}
@Override
public void visitCatchStatement(CatchStatement statement) {
varStack.getLast().add(statement.getVariable().getName());
super.visitCatchStatement(statement);
varStack.getLast().remove(statement.getVariable().getName());
}
@Override
public void visitMethod(MethodNode node) {
addVariablesToStack(node.getParameters());
super.visitMethod(node);
varStack.removeLast();
}
@Override
public void visitBlockStatement(BlockStatement block) {
Set<String> names = new HashSet<String>();
names.addAll(varStack.getLast());
varStack.add(names);
super.visitBlockStatement(block);
varStack.remove(names);
}
@Override
public void visitClosureExpression(ClosureExpression ce) {
addVariablesToStack(ce.getParameters());
super.visitClosureExpression(ce);
varStack.removeLast();
}
@Override
public void visitDeclarationExpression(DeclarationExpression expression) {
if (expression.isMultipleAssignmentDeclaration()) {
TupleExpression te = expression.getTupleExpression();
List<Expression> list = te.getExpressions();
for (Expression arg : list) {
VariableExpression ve = (VariableExpression) arg;
varStack.getLast().add(ve.getName());
}
} else {
VariableExpression ve = expression.getVariableExpression();
varStack.getLast().add(ve.getName());
}
super.visitDeclarationExpression(expression);
}
@Override
public void visitForLoop(ForStatement forLoop) {
Expression exp = forLoop.getCollectionExpression();
exp.visit(this);
Parameter loopParam = forLoop.getVariable();
if (loopParam != null) {
varStack.getLast().add(loopParam.getName());
}
super.visitForLoop(forLoop);
}
@Override
public void visitExpressionStatement(ExpressionStatement es) {
// GROOVY-3543: visit the declaration expressions so that declaration variables get added on the varStack
Expression exp = es.getExpression();
if (exp instanceof DeclarationExpression) {
exp.visit(this);
}
super.visitExpressionStatement(es);
}
@Override
public Expression transform(Expression exp) {
if (exp instanceof VariableExpression) {
VariableExpression ve = (VariableExpression) exp;
if (ve.getName().equals("this"))
return thisExpression;
else {
if (!varStack.getLast().contains(ve.getName())) {
return new PropertyExpression(thisExpression, ve.getName());
}
}
} else if (exp instanceof PropertyExpression) {
PropertyExpression pe = (PropertyExpression) exp;
if (pe.getObjectExpression() instanceof VariableExpression) {
VariableExpression vex = (VariableExpression) pe.getObjectExpression();
if (vex.isThisExpression()) {
pe.setObjectExpression(thisExpression);
return pe;
}
}
} else if (exp instanceof ClosureExpression) {
ClosureExpression ce = (ClosureExpression) exp;
ce.getVariableScope().putReferencedLocalVariable((Parameter) parameter.get());
Parameter[] params = ce.getParameters();
if (params == null) {
params = Parameter.EMPTY_ARRAY;
} else if (params.length == 0) {
params = new Parameter[] { new Parameter(ClassHelper.OBJECT_TYPE, "it") };
}
addVariablesToStack(params);
ce.getCode().visit(this);
varStack.removeLast();
}
return super.transform(exp);
}
};
for (MethodNode method : parent.getMethods()) {
if (!method.isStatic()) {
method.setModifiers(method.getModifiers() | Opcodes.ACC_STATIC);
final Parameter[] origParams = method.getParameters();
final Parameter[] newParams = new Parameter[origParams.length + 1];
Parameter p = new Parameter(targetClass, "$this");
p.setClosureSharedVariable(true);
newParams[0] = p;
parameter.set(p);
System.arraycopy(origParams, 0, newParams, 1, origParams.length);
method.setParameters(newParams);
expressionTransformer.visitMethod(method);
}
}
new VariableScopeVisitor(source, true).visitClass(parent);
}
use of org.codehaus.groovy.ast.ClassCodeExpressionTransformer in project groovy-core by groovy.
the class LogASTTransformation method visit.
public void visit(ASTNode[] nodes, final SourceUnit source) {
init(nodes, source);
AnnotatedNode targetClass = (AnnotatedNode) nodes[1];
AnnotationNode logAnnotation = (AnnotationNode) nodes[0];
final GroovyClassLoader classLoader = compilationUnit != null ? compilationUnit.getTransformLoader() : source.getClassLoader();
final LoggingStrategy loggingStrategy = createLoggingStrategy(logAnnotation, classLoader);
if (loggingStrategy == null)
return;
final String logFieldName = lookupLogFieldName(logAnnotation);
final String categoryName = lookupCategoryName(logAnnotation);
if (!(targetClass instanceof ClassNode))
throw new GroovyBugError("Class annotation " + logAnnotation.getClassNode().getName() + " annotated no Class, this must not happen.");
final ClassNode classNode = (ClassNode) targetClass;
ClassCodeExpressionTransformer transformer = new ClassCodeExpressionTransformer() {
private FieldNode logNode;
@Override
protected SourceUnit getSourceUnit() {
return source;
}
public Expression transform(Expression exp) {
if (exp == null)
return null;
if (exp instanceof MethodCallExpression) {
return transformMethodCallExpression(exp);
}
return super.transform(exp);
}
@Override
public void visitClass(ClassNode node) {
FieldNode logField = node.getField(logFieldName);
if (logField != null && logField.getOwner().equals(node)) {
addError("Class annotated with Log annotation cannot have log field declared", logField);
} else if (logField != null && !Modifier.isPrivate(logField.getModifiers())) {
addError("Class annotated with Log annotation cannot have log field declared because the field exists in the parent class: " + logField.getOwner().getName(), logField);
} else {
logNode = loggingStrategy.addLoggerFieldToClass(node, logFieldName, categoryName);
}
super.visitClass(node);
}
private Expression transformMethodCallExpression(Expression exp) {
MethodCallExpression mce = (MethodCallExpression) exp;
if (!(mce.getObjectExpression() instanceof VariableExpression)) {
return exp;
}
VariableExpression variableExpression = (VariableExpression) mce.getObjectExpression();
if (!variableExpression.getName().equals(logFieldName) || !(variableExpression.getAccessedVariable() instanceof DynamicVariable)) {
return exp;
}
String methodName = mce.getMethodAsString();
if (methodName == null)
return exp;
if (usesSimpleMethodArgumentsOnly(mce))
return exp;
variableExpression.setAccessedVariable(logNode);
if (!loggingStrategy.isLoggingMethod(methodName))
return exp;
return loggingStrategy.wrapLoggingMethodCall(variableExpression, methodName, exp);
}
private boolean usesSimpleMethodArgumentsOnly(MethodCallExpression mce) {
Expression arguments = mce.getArguments();
if (arguments instanceof TupleExpression) {
TupleExpression tuple = (TupleExpression) arguments;
for (Expression exp : tuple.getExpressions()) {
if (!isSimpleExpression(exp))
return false;
}
return true;
}
return !isSimpleExpression(arguments);
}
private boolean isSimpleExpression(Expression exp) {
if (exp instanceof ConstantExpression)
return true;
if (exp instanceof VariableExpression)
return true;
return false;
}
};
transformer.visitClass(classNode);
// GROOVY-6373: references to 'log' field are normally already FieldNodes by now, so revisit scoping
new VariableScopeVisitor(sourceUnit, true).visitClass(classNode);
}
Aggregations