Search in sources :

Example 26 with PropertyNode

use of org.codehaus.groovy.ast.PropertyNode in project grails-core by grails.

the class DefaultASTValidateableHelper method getPropertiesToEnsureConstraintsFor.

/**
     * Retrieves a Map describing all of the properties which need to be constrained for the class
     * represented by classNode.  The keys in the Map will be property names and the values are the
     * type of the corresponding property.
     * 
     * @param classNode the class to inspect
     * @return a Map describing all of the properties which need to be constrained
     */
protected Map<String, ClassNode> getPropertiesToEnsureConstraintsFor(final ClassNode classNode) {
    final Map<String, ClassNode> fieldsToConstrain = new HashMap<String, ClassNode>();
    final List<FieldNode> allFields = classNode.getFields();
    for (final FieldNode field : allFields) {
        if (!field.isStatic()) {
            final PropertyNode property = classNode.getProperty(field.getName());
            if (property != null) {
                fieldsToConstrain.put(field.getName(), field.getType());
            }
        }
    }
    final Map<String, MethodNode> declaredMethodsMap = classNode.getDeclaredMethodsMap();
    for (Entry<String, MethodNode> methodEntry : declaredMethodsMap.entrySet()) {
        final MethodNode value = methodEntry.getValue();
        if (!value.isStatic() && value.isPublic() && classNode.equals(value.getDeclaringClass()) && value.getLineNumber() > 0) {
            Parameter[] parameters = value.getParameters();
            if (parameters == null || parameters.length == 0) {
                final String methodName = value.getName();
                if (methodName.startsWith("get")) {
                    final ClassNode returnType = value.getReturnType();
                    final String restOfMethodName = methodName.substring(3);
                    final String propertyName = GrailsNameUtils.getPropertyName(restOfMethodName);
                    fieldsToConstrain.put(propertyName, returnType);
                }
            }
        }
    }
    final ClassNode superClass = classNode.getSuperClass();
    if (!superClass.equals(new ClassNode(Object.class))) {
        fieldsToConstrain.putAll(getPropertiesToEnsureConstraintsFor(superClass));
    }
    return fieldsToConstrain;
}
Also used : ClassNode(org.codehaus.groovy.ast.ClassNode) FieldNode(org.codehaus.groovy.ast.FieldNode) MethodNode(org.codehaus.groovy.ast.MethodNode) HashMap(java.util.HashMap) PropertyNode(org.codehaus.groovy.ast.PropertyNode) Parameter(org.codehaus.groovy.ast.Parameter)

Example 27 with PropertyNode

use of org.codehaus.groovy.ast.PropertyNode in project groovy-core by groovy.

the class GeneralUtils method getAllProperties.

public static List<PropertyNode> getAllProperties(ClassNode type) {
    ClassNode node = type;
    List<PropertyNode> result = new ArrayList<PropertyNode>();
    while (node != null) {
        result.addAll(node.getProperties());
        node = node.getSuperClass();
    }
    return result;
}
Also used : ClassNode(org.codehaus.groovy.ast.ClassNode) PropertyNode(org.codehaus.groovy.ast.PropertyNode) ArrayList(java.util.ArrayList)

Example 28 with PropertyNode

use of org.codehaus.groovy.ast.PropertyNode in project groovy-core by groovy.

the class EqualsAndHashCodeASTTransformation method calculateHashStatements.

private static Statement calculateHashStatements(ClassNode cNode, Expression hash, boolean includeFields, boolean callSuper, List<String> excludes, List<String> includes) {
    final List<PropertyNode> pList = getInstanceProperties(cNode);
    final List<FieldNode> fList = new ArrayList<FieldNode>();
    if (includeFields) {
        fList.addAll(getInstanceNonPropertyFields(cNode));
    }
    final BlockStatement body = new BlockStatement();
    // def _result = HashCodeHelper.initHash()
    final Expression result = varX("_result");
    body.addStatement(declS(result, callX(HASHUTIL_TYPE, "initHash")));
    for (PropertyNode pNode : pList) {
        if (shouldSkip(pNode.getName(), excludes, includes))
            continue;
        // _result = HashCodeHelper.updateHash(_result, getProperty()) // plus self-reference checking
        Expression getter = getterX(cNode, pNode);
        final Expression current = callX(HASHUTIL_TYPE, "updateHash", args(result, getter));
        body.addStatement(ifS(notX(sameX(getter, varX("this"))), assignS(result, current)));
    }
    for (FieldNode fNode : fList) {
        if (shouldSkip(fNode.getName(), excludes, includes))
            continue;
        // _result = HashCodeHelper.updateHash(_result, field) // plus self-reference checking
        final Expression fieldExpr = varX(fNode);
        final Expression current = callX(HASHUTIL_TYPE, "updateHash", args(result, fieldExpr));
        body.addStatement(ifS(notX(sameX(fieldExpr, varX("this"))), assignS(result, current)));
    }
    if (callSuper) {
        // _result = HashCodeHelper.updateHash(_result, super.hashCode())
        final Expression current = callX(HASHUTIL_TYPE, "updateHash", args(result, callSuperX("hashCode")));
        body.addStatement(assignS(result, current));
    }
    // $hash$code = _result
    if (hash != null) {
        body.addStatement(assignS(hash, result));
    } else {
        body.addStatement(returnS(result));
    }
    return body;
}
Also used : FieldNode(org.codehaus.groovy.ast.FieldNode) Expression(org.codehaus.groovy.ast.expr.Expression) VariableExpression(org.codehaus.groovy.ast.expr.VariableExpression) BinaryExpression(org.codehaus.groovy.ast.expr.BinaryExpression) CastExpression(org.codehaus.groovy.ast.expr.CastExpression) PropertyNode(org.codehaus.groovy.ast.PropertyNode) ArrayList(java.util.ArrayList) BlockStatement(org.codehaus.groovy.ast.stmt.BlockStatement)

Example 29 with PropertyNode

use of org.codehaus.groovy.ast.PropertyNode in project groovy-core by groovy.

the class DelegateASTTransformation method visit.

public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode node = (AnnotationNode) nodes[0];
    if (parent instanceof FieldNode) {
        FieldNode fieldNode = (FieldNode) parent;
        final ClassNode type = fieldNode.getType();
        final ClassNode owner = fieldNode.getOwner();
        if (type.equals(ClassHelper.OBJECT_TYPE) || type.equals(GROOVYOBJECT_TYPE)) {
            addError(MY_TYPE_NAME + " field '" + fieldNode.getName() + "' has an inappropriate type: " + type.getName() + ". Please add an explicit type but not java.lang.Object or groovy.lang.GroovyObject.", parent);
            return;
        }
        if (type.equals(owner)) {
            addError(MY_TYPE_NAME + " field '" + fieldNode.getName() + "' has an inappropriate type: " + type.getName() + ". Delegation to own type not supported. Please use a different type.", parent);
            return;
        }
        final List<MethodNode> fieldMethods = getAllMethods(type);
        for (ClassNode next : type.getAllInterfaces()) {
            fieldMethods.addAll(getAllMethods(next));
        }
        final boolean skipInterfaces = memberHasValue(node, MEMBER_INTERFACES, false);
        final boolean includeDeprecated = memberHasValue(node, MEMBER_DEPRECATED, true) || (type.isInterface() && !skipInterfaces);
        List<String> excludes = getMemberList(node, MEMBER_EXCLUDES);
        List<String> includes = getMemberList(node, MEMBER_INCLUDES);
        List<ClassNode> excludeTypes = getClassList(node, MEMBER_EXCLUDE_TYPES);
        List<ClassNode> includeTypes = getClassList(node, MEMBER_INCLUDE_TYPES);
        checkIncludeExclude(node, excludes, includes, excludeTypes, includeTypes, MY_TYPE_NAME);
        final List<MethodNode> ownerMethods = getAllMethods(owner);
        for (MethodNode mn : fieldMethods) {
            addDelegateMethod(node, fieldNode, owner, ownerMethods, mn, includeDeprecated, includes, excludes, includeTypes, excludeTypes);
        }
        for (PropertyNode prop : getAllProperties(type)) {
            if (prop.isStatic() || !prop.isPublic())
                continue;
            String name = prop.getName();
            addGetterIfNeeded(fieldNode, owner, prop, name, includes, excludes);
            addSetterIfNeeded(fieldNode, owner, prop, name, includes, excludes);
        }
        if (skipInterfaces)
            return;
        final Set<ClassNode> allInterfaces = getInterfacesAndSuperInterfaces(type);
        final Set<ClassNode> ownerIfaces = owner.getAllInterfaces();
        Map<String, ClassNode> genericsSpec = createGenericsSpec(fieldNode.getDeclaringClass());
        genericsSpec = createGenericsSpec(fieldNode.getType(), genericsSpec);
        for (ClassNode iface : allInterfaces) {
            if (Modifier.isPublic(iface.getModifiers()) && !ownerIfaces.contains(iface)) {
                final ClassNode[] ifaces = owner.getInterfaces();
                final ClassNode[] newIfaces = new ClassNode[ifaces.length + 1];
                for (int i = 0; i < ifaces.length; i++) {
                    newIfaces[i] = correctToGenericsSpecRecurse(genericsSpec, ifaces[i]);
                }
                newIfaces[ifaces.length] = correctToGenericsSpecRecurse(genericsSpec, iface);
                owner.setInterfaces(newIfaces);
            }
        }
    }
}
Also used : ClassNode(org.codehaus.groovy.ast.ClassNode) FieldNode(org.codehaus.groovy.ast.FieldNode) AnnotatedNode(org.codehaus.groovy.ast.AnnotatedNode) MethodNode(org.codehaus.groovy.ast.MethodNode) AnnotationNode(org.codehaus.groovy.ast.AnnotationNode) PropertyNode(org.codehaus.groovy.ast.PropertyNode)

Example 30 with PropertyNode

use of org.codehaus.groovy.ast.PropertyNode in project groovy-core by groovy.

the class ImmutableASTTransformation method createConstructorOrdered.

private void createConstructorOrdered(ClassNode cNode, List<PropertyNode> list) {
    final MapExpression argMap = new MapExpression();
    final Parameter[] orderedParams = new Parameter[list.size()];
    int index = 0;
    for (PropertyNode pNode : list) {
        Parameter param = new Parameter(pNode.getField().getType(), pNode.getField().getName());
        orderedParams[index++] = param;
        argMap.addMapEntryExpression(constX(pNode.getName()), varX(pNode.getName()));
    }
    final BlockStatement orderedBody = new BlockStatement();
    orderedBody.addStatement(stmt(ctorX(ClassNode.THIS, args(castX(HASHMAP_TYPE, argMap)))));
    doAddConstructor(cNode, new ConstructorNode(ACC_PUBLIC, orderedParams, ClassNode.EMPTY_ARRAY, orderedBody));
}
Also used : MapExpression(org.codehaus.groovy.ast.expr.MapExpression) PropertyNode(org.codehaus.groovy.ast.PropertyNode) ConstructorNode(org.codehaus.groovy.ast.ConstructorNode) Parameter(org.codehaus.groovy.ast.Parameter) BlockStatement(org.codehaus.groovy.ast.stmt.BlockStatement)

Aggregations

PropertyNode (org.codehaus.groovy.ast.PropertyNode)71 ClassNode (org.codehaus.groovy.ast.ClassNode)36 FieldNode (org.codehaus.groovy.ast.FieldNode)30 ArrayList (java.util.ArrayList)25 MethodNode (org.codehaus.groovy.ast.MethodNode)19 BlockStatement (org.codehaus.groovy.ast.stmt.BlockStatement)16 VariableExpression (org.codehaus.groovy.ast.expr.VariableExpression)12 Parameter (org.codehaus.groovy.ast.Parameter)11 InnerClassNode (org.codehaus.groovy.ast.InnerClassNode)10 Expression (org.codehaus.groovy.ast.expr.Expression)10 LowestUpperBoundClassNode (org.codehaus.groovy.ast.tools.WideningCategories.LowestUpperBoundClassNode)8 AnnotationNode (org.codehaus.groovy.ast.AnnotationNode)7 ConstructorNode (org.codehaus.groovy.ast.ConstructorNode)6 DynamicVariable (org.codehaus.groovy.ast.DynamicVariable)6 CastExpression (org.codehaus.groovy.ast.expr.CastExpression)6 ConstantExpression (org.codehaus.groovy.ast.expr.ConstantExpression)6 MethodCallExpression (org.codehaus.groovy.ast.expr.MethodCallExpression)6 SyntaxErrorMessage (org.codehaus.groovy.control.messages.SyntaxErrorMessage)6 SyntaxException (org.codehaus.groovy.syntax.SyntaxException)6 HashSet (java.util.HashSet)5