Java Code Examples for org.codehaus.groovy.ast.AnnotationNode#getClassNode()

The following examples show how to use org.codehaus.groovy.ast.AnnotationNode#getClassNode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AnnotationVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void checkCircularReference(ClassNode searchClass, ClassNode attrType, Expression startExp) {
    if (!isValidAnnotationClass(attrType)) return;
    if (!(startExp instanceof AnnotationConstantExpression)) {
        addError("Found '" + startExp.getText() + "' when expecting an Annotation Constant", startExp);
        return;
    }
    AnnotationConstantExpression ace = (AnnotationConstantExpression) startExp;
    AnnotationNode annotationNode = (AnnotationNode) ace.getValue();
    if (annotationNode.getClassNode().equals(searchClass)) {
        addError("Circular reference discovered in " + searchClass.getName(), startExp);
        return;
    }
    ClassNode cn = annotationNode.getClassNode();
    for (MethodNode method : cn.getMethods()) {
        if (method.getReturnType().equals(searchClass)) {
            addError("Circular reference discovered in " + cn.getName(), startExp);
        }
        ReturnStatement code = (ReturnStatement) method.getCode();
        if (code == null) continue;
        checkCircularReference(searchClass, method.getReturnType(), code.getExpression());
    }
}
 
Example 2
Source File: ExtendedVerifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void visitOverride(AnnotatedNode node, AnnotationNode visited) {
    ClassNode annotationType = visited.getClassNode();
    if (annotationType.isResolved() && annotationType.getName().equals("java.lang.Override")) {
        if (node instanceof MethodNode && !Boolean.TRUE.equals(node.getNodeMetaData(Verifier.DEFAULT_PARAMETER_GENERATED))) {
            boolean override = false;
            MethodNode origMethod = (MethodNode) node;
            ClassNode cNode = origMethod.getDeclaringClass();
            if (origMethod.hasDefaultValue()) {
                List<MethodNode> variants = cNode.getDeclaredMethods(origMethod.getName());
                for (MethodNode m : variants) {
                    if (m.getAnnotations().contains(visited) && isOverrideMethod(m)) {
                        override = true;
                        break;
                    }
                }
            } else {
                override = isOverrideMethod(origMethod);
            }

            if (!override) {
                addError("Method '" + origMethod.getName() + "' from class '" + cNode.getName() + "' does not override " +
                        "method from its superclass or interfaces but is annotated with @Override.", visited);
            }
        }
    }
}
 
Example 3
Source File: VariableScopeVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void addAnnotationOccurrences(AnnotationNode annotation, ClassNode findingNode) {
    ClassNode classNode = annotation.getClassNode();
    classNode.setLineNumber(annotation.getLineNumber());
    classNode.setColumnNumber(annotation.getColumnNumber());
    classNode.setLastLineNumber(annotation.getLastLineNumber());
    classNode.setLastColumnNumber(annotation.getLastColumnNumber());

    addOccurrences(classNode, findingNode);
}
 
Example 4
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected Expression transformAnnotationConstantExpression(final AnnotationConstantExpression ace) {
    AnnotationNode an = (AnnotationNode) ace.getValue();
    ClassNode type = an.getClassNode();
    resolveOrFail(type, " for annotation", an);
    for (Map.Entry<String, Expression> member : an.getMembers().entrySet()) {
        member.setValue(transform(member.getValue()));
    }
    return ace;
}
 
Example 5
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitAnnotations(final AnnotatedNode node) {
    List<AnnotationNode> annotations = node.getAnnotations();
    if (annotations.isEmpty()) return;
    Map<String, AnnotationNode> tmpAnnotations = new HashMap<>();
    for (AnnotationNode an : annotations) {
        // skip built-in properties
        if (an.isBuiltIn()) continue;
        ClassNode annType = an.getClassNode();
        resolveOrFail(annType, " for annotation", an);
        for (Map.Entry<String, Expression> member : an.getMembers().entrySet()) {
            Expression newValue = transform(member.getValue());
            Expression adjusted = transformInlineConstants(newValue);
            member.setValue(adjusted);
            checkAnnotationMemberValue(adjusted);
        }
        if (annType.isResolved()) {
            Class<?> annTypeClass = annType.getTypeClass();
            Retention retAnn = annTypeClass.getAnnotation(Retention.class);
            if (retAnn != null && !retAnn.value().equals(RetentionPolicy.SOURCE) && !isRepeatable(annTypeClass)) {
                // remember non-source/non-repeatable annos (auto collecting of Repeatable annotations is handled elsewhere)
                AnnotationNode anyPrevAnnNode = tmpAnnotations.put(annTypeClass.getName(), an);
                if (anyPrevAnnNode != null) {
                    addError("Cannot specify duplicate annotation on the same member : " + annType.getName(), an);
                }
            }
        }
    }
}
 
Example 6
Source File: AnnotationCollectorTransform.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression serialize(AnnotationNode an) {
    ClassExpression type = new ClassExpression(an.getClassNode());
    type.setSourcePosition(an.getClassNode());

    MapExpression map = new MapExpression();
    for (Map.Entry<String, Expression> entry : an.getMembers().entrySet()) {
        Expression key = new ConstantExpression(entry.getKey());
        Expression val = serialize(entry.getValue());
        map.addMapEntryExpression(key, val);
    }

    return new ArrayExpression(ClassHelper.OBJECT_TYPE, Arrays.asList(type, map));
}
 
Example 7
Source File: AnnotationCollectorTransform.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static List<AnnotationNode> copy(List<AnnotationNode> orig, AnnotationNode aliasAnnotationUsage) {
    if (orig.isEmpty()) return orig;
    List<AnnotationNode> ret = new ArrayList<>(orig.size());
    for (AnnotationNode an : orig) {
        AnnotationNode newAn = new AnnotationNode(an.getClassNode());
        copyMembers(an, newAn);
        newAn.setSourcePosition(aliasAnnotationUsage);
        ret.add(newAn);
    }
    return ret;
}
 
Example 8
Source File: AnnotationCollectorTransform.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static List<AnnotationNode> getTargetListFromAnnotations(ClassNode alias) {
    List<AnnotationNode> annotations = alias.getAnnotations();
    if (annotations.size() < 2) {
        return Collections.emptyList();
    }
    List<AnnotationNode> ret = new ArrayList<>(annotations.size());
    for (AnnotationNode an : annotations) {
        ClassNode type = an.getClassNode();
        if (type.getName().equals(AnnotationCollector.class.getName()) || "java.lang.annotation".equals(type.getPackageName())) continue;
        AnnotationNode toAdd = new AnnotationNode(type);
        copyMembers(an, toAdd);
        ret.add(toAdd);
    }
    return ret;
}
 
Example 9
Source File: GeneralUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Copies all <tt>candidateAnnotations</tt> with retention policy {@link java.lang.annotation.RetentionPolicy#RUNTIME}
 * and {@link java.lang.annotation.RetentionPolicy#CLASS}.
 * {@link groovy.transform.Generated} annotations will be copied if {@code includeGenerated} is true.
 * <p>
 * Annotations with {@link org.codehaus.groovy.runtime.GeneratedClosure} members are not supported at present.
 */
public static void copyAnnotatedNodeAnnotations(final AnnotatedNode annotatedNode, final List<AnnotationNode> copied, final List<AnnotationNode> notCopied, final boolean includeGenerated) {
    List<AnnotationNode> annotationList = annotatedNode.getAnnotations();
    for (AnnotationNode annotation : annotationList)  {
        List<AnnotationNode> annotations = annotation.getClassNode().getAnnotations(AbstractASTTransformation.RETENTION_CLASSNODE);
        if (annotations.isEmpty()) continue;

        if (hasClosureMember(annotation)) {
            notCopied.add(annotation);
            continue;
        }

        if (!includeGenerated && annotation.getClassNode().getName().equals("groovy.transform.Generated")) {
            continue;
        }

        AnnotationNode retentionPolicyAnnotation = annotations.get(0);
        Expression valueExpression = retentionPolicyAnnotation.getMember("value");
        if (!(valueExpression instanceof PropertyExpression)) continue;

        PropertyExpression propertyExpression = (PropertyExpression) valueExpression;
        boolean processAnnotation = propertyExpression.getProperty() instanceof ConstantExpression
                && ("RUNTIME".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue())
                    || "CLASS".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue()));
        if (processAnnotation)  {
            AnnotationNode newAnnotation = new AnnotationNode(annotation.getClassNode());
            for (Map.Entry<String, Expression> member : annotation.getMembers().entrySet())  {
                newAnnotation.addMember(member.getKey(), member.getValue());
            }
            newAnnotation.setSourcePosition(annotatedNode);

            copied.add(newAnnotation);
        }
    }
}
 
Example 10
Source File: AnnotationVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
public AnnotationNode visit(AnnotationNode node) {
    this.annotation = node;
    this.reportClass = node.getClassNode();

    if (!isValidAnnotationClass(node.getClassNode())) {
        addError("class " + node.getClassNode().getName() + " is not an annotation");
        return node;
    }

    // check if values have been passed for all annotation attributes that don't have defaults
    if (!checkIfMandatoryAnnotationValuesPassed(node)) {
        return node;
    }

    // if enum constants have been used, check if they are all valid
    if (!checkIfValidEnumConstsAreUsed(node)) {
        return node;
    }

    Map<String, Expression> attributes = node.getMembers();
    for (Map.Entry<String, Expression> entry : attributes.entrySet()) {
        String attrName = entry.getKey();
        ClassNode attrType = getAttributeType(node, attrName);
        Expression attrExpr = transformInlineConstants(entry.getValue(), attrType);
        entry.setValue(attrExpr);
        visitExpression(attrName, attrExpr, attrType);
    }
    VMPluginFactory.getPlugin().configureAnnotation(node);
    return this.annotation;
}
 
Example 11
Source File: AnnotationVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean checkIfMandatoryAnnotationValuesPassed(AnnotationNode node) {
    boolean ok = true;
    Map attributes = node.getMembers();
    ClassNode classNode = node.getClassNode();
    for (MethodNode mn : classNode.getMethods()) {
        String methodName = mn.getName();
        // if the annotation attribute has a default, getCode() returns a ReturnStatement with the default value
        if (mn.getCode() == null && !attributes.containsKey(methodName)) {
            addError("No explicit/default value found for annotation attribute '" + methodName + "'", node);
            ok = false;
        }
    }
    return ok;
}
 
Example 12
Source File: AnnotationVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private ClassNode getAttributeType(AnnotationNode node, String attrName) {
    ClassNode classNode = node.getClassNode();
    List methods = classNode.getMethods(attrName);
    // if size is >1, then the method was overwritten or something, we ignore that
    // if it is an error, we have to test it at another place. But size==0 is
    // an error, because it means that no such attribute exists.
    if (methods.isEmpty()) {
        addError("'" + attrName + "'is not part of the annotation " + classNode.getNameWithoutPackage(), node);
        return ClassHelper.OBJECT_TYPE;
    }
    MethodNode method = (MethodNode) methods.get(0);
    return method.getReturnType();
}
 
Example 13
Source File: Java8.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void configureAnnotation(AnnotationNode node) {
    ClassNode type = node.getClassNode();
    VMPlugin plugin = VMPluginFactory.getPlugin();
    List<AnnotationNode> annotations = type.getAnnotations();
    for (AnnotationNode an : annotations) {
        plugin.configureAnnotationNodeFromDefinition(an, node);
    }
    if (!node.getClassNode().getName().equals("java.lang.annotation.Retention")) {
        plugin.configureAnnotationNodeFromDefinition(node, node);
    }
}
 
Example 14
Source File: FieldASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    sourceUnit = source;
    if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) {
        throw new GroovyBugError("Internal error: expecting [AnnotationNode, AnnotatedNode] but got: " + Arrays.asList(nodes));
    }

    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode node = (AnnotationNode) nodes[0];
    if (!MY_TYPE.equals(node.getClassNode())) return;

    if (parent instanceof DeclarationExpression) {
        DeclarationExpression de = (DeclarationExpression) parent;
        ClassNode cNode = de.getDeclaringClass();
        if (!cNode.isScript()) {
            addError("Annotation " + MY_TYPE_NAME + " can only be used within a Script.", parent);
            return;
        }
        candidate = de;
        // GROOVY-4548: temp fix to stop CCE until proper support is added
        if (de.isMultipleAssignmentDeclaration()) {
            addError("Annotation " + MY_TYPE_NAME + " not supported with multiple assignment notation.", parent);
            return;
        }
        VariableExpression ve = de.getVariableExpression();
        variableName = ve.getName();
        // set owner null here, it will be updated by addField
        fieldNode = new FieldNode(variableName, ve.getModifiers(), ve.getType(), null, de.getRightExpression());
        fieldNode.setSourcePosition(de);
        cNode.addField(fieldNode);
        // provide setter for CLI Builder purposes unless final
        if (fieldNode.isFinal()) {
            if (!de.getAnnotations(OPTION_TYPE).isEmpty()) {
                addError("Can't have a final field also annotated with @" + OPTION_TYPE.getNameWithoutPackage(), de);
            }
        } else {
            String setterName = getSetterName(variableName);
            cNode.addMethod(setterName, ACC_PUBLIC | ACC_SYNTHETIC, ClassHelper.VOID_TYPE, params(param(ve.getType(), variableName)), ClassNode.EMPTY_ARRAY, block(
                    stmt(assignX(propX(varX("this"), variableName), varX(variableName)))
            ));
        }

        // GROOVY-4833 : annotations that are not Groovy transforms should be transferred to the generated field
        // GROOVY-6112 : also copy acceptable Groovy transforms
        final List<AnnotationNode> annotations = de.getAnnotations();
        for (AnnotationNode annotation : annotations) {
            // GROOVY-6337 HACK: in case newly created field is @Lazy
            if (annotation.getClassNode().equals(LAZY_TYPE)) {
                LazyASTTransformation.visitField(this, annotation, fieldNode);
            }
            final ClassNode annotationClassNode = annotation.getClassNode();
            if (notTransform(annotationClassNode) || acceptableTransform(annotation)) {
                fieldNode.addAnnotation(annotation);
            }
        }

        super.visitClass(cNode);
        // GROOVY-5207 So that Closures can see newly added fields
        // (not super efficient for a very large class with many @Fields but we chose simplicity
        // and understandability of this solution over more complex but efficient alternatives)
        VariableScopeVisitor scopeVisitor = new VariableScopeVisitor(source);
        scopeVisitor.visitClass(cNode);
    }
}