Search in sources :

Example 1 with ClosureExpression

use of org.codehaus.groovy.ast.expr.ClosureExpression in project groovy by apache.

the class GeneralUtils method copyStatementsWithSuperAdjustment.

public static boolean copyStatementsWithSuperAdjustment(ClosureExpression pre, BlockStatement body) {
    Statement preCode = pre.getCode();
    boolean changed = false;
    if (preCode instanceof BlockStatement) {
        BlockStatement block = (BlockStatement) preCode;
        List<Statement> statements = block.getStatements();
        for (int i = 0; i < statements.size(); i++) {
            Statement statement = statements.get(i);
            // adjust the first statement if it's a super call
            if (i == 0 && statement instanceof ExpressionStatement) {
                ExpressionStatement es = (ExpressionStatement) statement;
                Expression preExp = es.getExpression();
                if (preExp instanceof MethodCallExpression) {
                    MethodCallExpression mce = (MethodCallExpression) preExp;
                    String name = mce.getMethodAsString();
                    if ("super".equals(name)) {
                        es.setExpression(new ConstructorCallExpression(ClassNode.SUPER, mce.getArguments()));
                        changed = true;
                    }
                }
            }
            body.addStatement(statement);
        }
    }
    return changed;
}
Also used : StaticMethodCallExpression(org.codehaus.groovy.ast.expr.StaticMethodCallExpression) MethodCallExpression(org.codehaus.groovy.ast.expr.MethodCallExpression) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) VariableExpression(org.codehaus.groovy.ast.expr.VariableExpression) ArgumentListExpression(org.codehaus.groovy.ast.expr.ArgumentListExpression) NotExpression(org.codehaus.groovy.ast.expr.NotExpression) BinaryExpression(org.codehaus.groovy.ast.expr.BinaryExpression) FieldExpression(org.codehaus.groovy.ast.expr.FieldExpression) TernaryExpression(org.codehaus.groovy.ast.expr.TernaryExpression) CastExpression(org.codehaus.groovy.ast.expr.CastExpression) BooleanExpression(org.codehaus.groovy.ast.expr.BooleanExpression) PropertyExpression(org.codehaus.groovy.ast.expr.PropertyExpression) StaticMethodCallExpression(org.codehaus.groovy.ast.expr.StaticMethodCallExpression) MethodCallExpression(org.codehaus.groovy.ast.expr.MethodCallExpression) Expression(org.codehaus.groovy.ast.expr.Expression) ConstructorCallExpression(org.codehaus.groovy.ast.expr.ConstructorCallExpression) DeclarationExpression(org.codehaus.groovy.ast.expr.DeclarationExpression) ClosureExpression(org.codehaus.groovy.ast.expr.ClosureExpression) ClassExpression(org.codehaus.groovy.ast.expr.ClassExpression) AttributeExpression(org.codehaus.groovy.ast.expr.AttributeExpression) CatchStatement(org.codehaus.groovy.ast.stmt.CatchStatement) IfStatement(org.codehaus.groovy.ast.stmt.IfStatement) BlockStatement(org.codehaus.groovy.ast.stmt.BlockStatement) Statement(org.codehaus.groovy.ast.stmt.Statement) ExpressionStatement(org.codehaus.groovy.ast.stmt.ExpressionStatement) ThrowStatement(org.codehaus.groovy.ast.stmt.ThrowStatement) ReturnStatement(org.codehaus.groovy.ast.stmt.ReturnStatement) EmptyStatement(org.codehaus.groovy.ast.stmt.EmptyStatement) ConstructorCallExpression(org.codehaus.groovy.ast.expr.ConstructorCallExpression) ExpressionStatement(org.codehaus.groovy.ast.stmt.ExpressionStatement) BlockStatement(org.codehaus.groovy.ast.stmt.BlockStatement)

Example 2 with ClosureExpression

use of org.codehaus.groovy.ast.expr.ClosureExpression in project groovy by apache.

the class GeneralUtils method hasClosureMember.

private static boolean hasClosureMember(AnnotationNode annotation) {
    Map<String, Expression> members = annotation.getMembers();
    for (Map.Entry<String, Expression> member : members.entrySet()) {
        if (member.getValue() instanceof ClosureExpression)
            return true;
        if (member.getValue() instanceof ClassExpression) {
            ClassExpression classExpression = (ClassExpression) member.getValue();
            Class<?> typeClass = classExpression.getType().isResolved() ? classExpression.getType().redirect().getTypeClass() : null;
            if (typeClass != null && GeneratedClosure.class.isAssignableFrom(typeClass))
                return true;
        }
    }
    return false;
}
Also used : ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) VariableExpression(org.codehaus.groovy.ast.expr.VariableExpression) ArgumentListExpression(org.codehaus.groovy.ast.expr.ArgumentListExpression) NotExpression(org.codehaus.groovy.ast.expr.NotExpression) BinaryExpression(org.codehaus.groovy.ast.expr.BinaryExpression) FieldExpression(org.codehaus.groovy.ast.expr.FieldExpression) TernaryExpression(org.codehaus.groovy.ast.expr.TernaryExpression) CastExpression(org.codehaus.groovy.ast.expr.CastExpression) BooleanExpression(org.codehaus.groovy.ast.expr.BooleanExpression) PropertyExpression(org.codehaus.groovy.ast.expr.PropertyExpression) StaticMethodCallExpression(org.codehaus.groovy.ast.expr.StaticMethodCallExpression) MethodCallExpression(org.codehaus.groovy.ast.expr.MethodCallExpression) Expression(org.codehaus.groovy.ast.expr.Expression) ConstructorCallExpression(org.codehaus.groovy.ast.expr.ConstructorCallExpression) DeclarationExpression(org.codehaus.groovy.ast.expr.DeclarationExpression) ClosureExpression(org.codehaus.groovy.ast.expr.ClosureExpression) ClassExpression(org.codehaus.groovy.ast.expr.ClassExpression) AttributeExpression(org.codehaus.groovy.ast.expr.AttributeExpression) ClassExpression(org.codehaus.groovy.ast.expr.ClassExpression) ClosureExpression(org.codehaus.groovy.ast.expr.ClosureExpression) Map(java.util.Map) GeneratedClosure(org.codehaus.groovy.runtime.GeneratedClosure)

Example 3 with ClosureExpression

use of org.codehaus.groovy.ast.expr.ClosureExpression in project groovy by apache.

the class TupleConstructorASTTransformation method createConstructor.

public static void createConstructor(AbstractASTTransformation xform, ClassNode cNode, boolean includeFields, boolean includeProperties, boolean includeSuperFields, boolean includeSuperProperties, boolean callSuper, boolean force, List<String> excludes, final List<String> includes, boolean useSetters, boolean defaults, boolean allNames, SourceUnit sourceUnit, ClosureExpression pre, ClosureExpression post) {
    // no processing if existing constructors found
    if (!cNode.getDeclaredConstructors().isEmpty() && !force)
        return;
    List<FieldNode> superList = new ArrayList<FieldNode>();
    if (includeSuperProperties) {
        superList.addAll(getSuperPropertyFields(cNode.getSuperClass()));
    }
    if (includeSuperFields) {
        superList.addAll(getSuperNonPropertyFields(cNode.getSuperClass()));
    }
    List<FieldNode> list = new ArrayList<FieldNode>();
    if (includeProperties) {
        list.addAll(getInstancePropertyFields(cNode));
    }
    if (includeFields) {
        list.addAll(getInstanceNonPropertyFields(cNode));
    }
    final List<Parameter> params = new ArrayList<Parameter>();
    final List<Expression> superParams = new ArrayList<Expression>();
    final BlockStatement preBody = new BlockStatement();
    boolean superInPre = false;
    if (pre != null) {
        superInPre = copyStatementsWithSuperAdjustment(pre, preBody);
        if (superInPre && callSuper) {
            xform.addError("Error during " + MY_TYPE_NAME + " processing, can't have a super call in 'pre' " + "closure and also 'callSuper' enabled", cNode);
        }
    }
    final BlockStatement body = new BlockStatement();
    for (FieldNode fNode : superList) {
        String name = fNode.getName();
        if (shouldSkipUndefinedAware(name, excludes, includes, allNames))
            continue;
        params.add(createParam(fNode, name, defaults, xform));
        boolean hasSetter = cNode.getProperty(name) != null && !fNode.isFinal();
        if (callSuper) {
            superParams.add(varX(name));
        } else if (!superInPre) {
            if (useSetters && hasSetter) {
                body.addStatement(stmt(callThisX(getSetterName(name), varX(name))));
            } else {
                body.addStatement(assignS(propX(varX("this"), name), varX(name)));
            }
        }
    }
    if (callSuper) {
        body.addStatement(stmt(ctorX(ClassNode.SUPER, args(superParams))));
    }
    if (!preBody.isEmpty()) {
        body.addStatements(preBody.getStatements());
    }
    for (FieldNode fNode : list) {
        String name = fNode.getName();
        if (shouldSkipUndefinedAware(name, excludes, includes, allNames))
            continue;
        Parameter nextParam = createParam(fNode, name, defaults, xform);
        params.add(nextParam);
        boolean hasSetter = cNode.getProperty(name) != null && !fNode.isFinal();
        if (useSetters && hasSetter) {
            body.addStatement(stmt(callThisX(getSetterName(name), varX(nextParam))));
        } else {
            body.addStatement(assignS(propX(varX("this"), name), varX(nextParam)));
        }
    }
    if (post != null) {
        body.addStatement(post.getCode());
    }
    if (includes != null) {
        Comparator<Parameter> includeComparator = new Comparator<Parameter>() {

            public int compare(Parameter p1, Parameter p2) {
                return new Integer(includes.indexOf(p1.getName())).compareTo(includes.indexOf(p2.getName()));
            }
        };
        Collections.sort(params, includeComparator);
    }
    cNode.addConstructor(new ConstructorNode(ACC_PUBLIC, params.toArray(new Parameter[params.size()]), ClassNode.EMPTY_ARRAY, body));
    if (sourceUnit != null && !body.isEmpty()) {
        VariableScopeVisitor scopeVisitor = new VariableScopeVisitor(sourceUnit);
        scopeVisitor.visitClass(cNode);
    }
    // or if there is only one Map property (for backwards compatibility)
    if (!params.isEmpty() && defaults) {
        ClassNode firstParam = params.get(0).getType();
        if (params.size() > 1 || firstParam.equals(ClassHelper.OBJECT_TYPE)) {
            String message = "The class " + cNode.getName() + " was incorrectly initialized via the map constructor with null.";
            if (firstParam.equals(ClassHelper.MAP_TYPE)) {
                addMapConstructors(cNode, true, message);
            } else {
                ClassNode candidate = HMAP_TYPE;
                while (candidate != null) {
                    if (candidate.equals(firstParam)) {
                        addMapConstructors(cNode, true, message);
                        break;
                    }
                    candidate = candidate.getSuperClass();
                }
            }
        }
    }
}
Also used : ClassNode(org.codehaus.groovy.ast.ClassNode) FieldNode(org.codehaus.groovy.ast.FieldNode) ArrayList(java.util.ArrayList) BlockStatement(org.codehaus.groovy.ast.stmt.BlockStatement) Comparator(java.util.Comparator) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) VariableExpression(org.codehaus.groovy.ast.expr.VariableExpression) Expression(org.codehaus.groovy.ast.expr.Expression) ClosureExpression(org.codehaus.groovy.ast.expr.ClosureExpression) ConstructorNode(org.codehaus.groovy.ast.ConstructorNode) Parameter(org.codehaus.groovy.ast.Parameter) VariableScopeVisitor(org.codehaus.groovy.classgen.VariableScopeVisitor)

Example 4 with ClosureExpression

use of org.codehaus.groovy.ast.expr.ClosureExpression 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);
}
Also used : ClassNode(org.codehaus.groovy.ast.ClassNode) FieldNode(org.codehaus.groovy.ast.FieldNode) AnnotatedNode(org.codehaus.groovy.ast.AnnotatedNode) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) GroovyBugError(org.codehaus.groovy.GroovyBugError) TupleExpression(org.codehaus.groovy.ast.expr.TupleExpression) BlockStatement(org.codehaus.groovy.ast.stmt.BlockStatement) VariableExpression(org.codehaus.groovy.ast.expr.VariableExpression) GroovyClassLoader(groovy.lang.GroovyClassLoader) MethodCallExpression(org.codehaus.groovy.ast.expr.MethodCallExpression) AnnotationNode(org.codehaus.groovy.ast.AnnotationNode) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) MethodCallExpression(org.codehaus.groovy.ast.expr.MethodCallExpression) Expression(org.codehaus.groovy.ast.expr.Expression) VariableExpression(org.codehaus.groovy.ast.expr.VariableExpression) ClosureExpression(org.codehaus.groovy.ast.expr.ClosureExpression) TupleExpression(org.codehaus.groovy.ast.expr.TupleExpression) DynamicVariable(org.codehaus.groovy.ast.DynamicVariable) ClosureExpression(org.codehaus.groovy.ast.expr.ClosureExpression) VariableScopeVisitor(org.codehaus.groovy.classgen.VariableScopeVisitor) ClassCodeExpressionTransformer(org.codehaus.groovy.ast.ClassCodeExpressionTransformer)

Example 5 with ClosureExpression

use of org.codehaus.groovy.ast.expr.ClosureExpression 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;
        }
    };
}
Also used : Expression(org.codehaus.groovy.ast.expr.Expression) VariableExpression(org.codehaus.groovy.ast.expr.VariableExpression) ArgumentListExpression(org.codehaus.groovy.ast.expr.ArgumentListExpression) ClosureExpression(org.codehaus.groovy.ast.expr.ClosureExpression) DynamicVariable(org.codehaus.groovy.ast.DynamicVariable) Parameter(org.codehaus.groovy.ast.Parameter) VariableExpression(org.codehaus.groovy.ast.expr.VariableExpression) ClosureExpression(org.codehaus.groovy.ast.expr.ClosureExpression) ClassCodeExpressionTransformer(org.codehaus.groovy.ast.ClassCodeExpressionTransformer)

Aggregations

ClosureExpression (org.codehaus.groovy.ast.expr.ClosureExpression)50 Expression (org.codehaus.groovy.ast.expr.Expression)39 VariableExpression (org.codehaus.groovy.ast.expr.VariableExpression)34 MethodCallExpression (org.codehaus.groovy.ast.expr.MethodCallExpression)33 ConstantExpression (org.codehaus.groovy.ast.expr.ConstantExpression)31 ArgumentListExpression (org.codehaus.groovy.ast.expr.ArgumentListExpression)28 ClassExpression (org.codehaus.groovy.ast.expr.ClassExpression)21 ClassNode (org.codehaus.groovy.ast.ClassNode)18 BlockStatement (org.codehaus.groovy.ast.stmt.BlockStatement)18 PropertyExpression (org.codehaus.groovy.ast.expr.PropertyExpression)17 BinaryExpression (org.codehaus.groovy.ast.expr.BinaryExpression)16 ConstructorCallExpression (org.codehaus.groovy.ast.expr.ConstructorCallExpression)16 DeclarationExpression (org.codehaus.groovy.ast.expr.DeclarationExpression)16 Parameter (org.codehaus.groovy.ast.Parameter)15 TupleExpression (org.codehaus.groovy.ast.expr.TupleExpression)15 ExpressionStatement (org.codehaus.groovy.ast.stmt.ExpressionStatement)13 FieldNode (org.codehaus.groovy.ast.FieldNode)10 ListExpression (org.codehaus.groovy.ast.expr.ListExpression)10 ArrayList (java.util.ArrayList)9 DynamicVariable (org.codehaus.groovy.ast.DynamicVariable)9