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

The following examples show how to use org.codehaus.groovy.ast.AnnotationNode#getMember() . 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: BaseScriptASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void changeBaseScriptTypeFromDeclaration(final DeclarationExpression de, final AnnotationNode node) {
    if (de.isMultipleAssignmentDeclaration()) {
        addError("Annotation " + MY_TYPE_NAME + " not supported with multiple assignment notation.", de);
        return;
    }

    if (!(de.getRightExpression() instanceof EmptyExpression)) {
        addError("Annotation " + MY_TYPE_NAME + " not supported with variable assignment.", de);
        return;
    }
    Expression value = node.getMember("value");
    if (value != null) {
        addError("Annotation " + MY_TYPE_NAME + " cannot have member 'value' if used on a declaration.", value);
        return;
    }

    ClassNode cNode = de.getDeclaringClass();
    ClassNode baseScriptType = de.getVariableExpression().getType().getPlainNodeReference();
    de.setRightExpression(new VariableExpression("this"));

    changeBaseScriptType(de, cNode, baseScriptType);
}
 
Example 2
Source File: AbstractASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
public List<ClassNode> getMemberClassList(AnnotationNode anno, String name) {
    List<ClassNode> list = new ArrayList<>();
    Expression expr = anno.getMember(name);
    if (expr == null) {
        return null;
    }
    if (expr instanceof ListExpression) {
        final ListExpression listExpression = (ListExpression) expr;
        if (isUndefinedMarkerList(listExpression)) {
            return null;
        }
        list = getTypeList(listExpression);
    } else if (expr instanceof ClassExpression) {
        ClassNode cn = expr.getType();
        if (isUndefined(cn)) return null;
        if (cn != null) list.add(cn);
    }
    return list;
}
 
Example 3
Source File: NewifyASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    this.source = source;
    if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) {
        internalError("Expecting [AnnotationNode, AnnotatedClass] but got: " + Arrays.asList(nodes));
    }

    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode node = (AnnotationNode) nodes[0];
    if (!MY_TYPE.equals(node.getClassNode())) {
        internalError("Transformation called from wrong annotation: " + node.getClassNode().getName());
    }

    final boolean autoFlag = determineAutoFlag(node.getMember("auto"));
    final Expression classNames = node.getMember("value");
    final Pattern cnPattern = determineClassNamePattern(node.getMember("pattern"));

    if (parent instanceof ClassNode) {
        newifyClass((ClassNode) parent, autoFlag, determineClasses(classNames, false), cnPattern);
    } else if (parent instanceof MethodNode || parent instanceof FieldNode) {
        newifyMethodOrField(parent, autoFlag, determineClasses(classNames, false), cnPattern);
    } else if (parent instanceof DeclarationExpression) {
        newifyDeclaration((DeclarationExpression) parent, autoFlag, determineClasses(classNames, true), cnPattern);
    }
}
 
Example 4
Source File: AnnotationCollectorTransform.java    From groovy with Apache License 2.0 6 votes vote down vote up
private List<AnnotationNode> getTargetListFromValue(AnnotationNode collector, AnnotationNode aliasAnnotationUsage, SourceUnit source) {
    Expression memberValue = collector.getMember("value");
    if (memberValue == null) {
        return Collections.emptyList();
    }
    if (!(memberValue instanceof ListExpression)) {
        addError("Annotation collector expected a list of classes, but got a "+memberValue.getClass(), collector, source);
        return Collections.emptyList();
    }
    ListExpression memberListExp = (ListExpression) memberValue;
    List<Expression> memberList = memberListExp.getExpressions();
    if (memberList.isEmpty()) {
        return Collections.emptyList();
    }
    List<AnnotationNode> ret = new ArrayList<>();
    for (Expression e : memberList) {
        AnnotationNode toAdd = new AnnotationNode(e.getType());
        toAdd.setSourcePosition(aliasAnnotationUsage);
        ret.add(toAdd);
    }
    return ret;
}
 
Example 5
Source File: LazyASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
static void visitField(ErrorCollecting xform, AnnotationNode node, FieldNode fieldNode) {
    final Expression soft = node.getMember("soft");
    final Expression init = getInitExpr(xform, fieldNode);

    String backingFieldName = "$" + fieldNode.getName();
    fieldNode.rename(backingFieldName);
    fieldNode.setModifiers(ACC_PRIVATE | ACC_SYNTHETIC | (fieldNode.getModifiers() & (~(ACC_PUBLIC | ACC_PROTECTED))));
    PropertyNode pNode = fieldNode.getDeclaringClass().getProperty(backingFieldName);
    if (pNode != null) {
        fieldNode.getDeclaringClass().getProperties().remove(pNode);
    }

    if (soft instanceof ConstantExpression && ((ConstantExpression) soft).getValue().equals(true)) {
        createSoft(fieldNode, init);
    } else {
        create(fieldNode, init);
        // @Lazy not meaningful with primitive so convert to wrapper if needed
        if (ClassHelper.isPrimitiveType(fieldNode.getType())) {
            fieldNode.setType(ClassHelper.getWrapper(fieldNode.getType()));
        }
    }
}
 
Example 6
Source File: ImmutablePropertyUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static List<String> getKnownImmutables(AbstractASTTransformation xform, ClassNode cNode) {
    List<AnnotationNode> annotations = cNode.getAnnotations(ImmutablePropertyUtils.IMMUTABLE_OPTIONS_TYPE);
    AnnotationNode anno = annotations.isEmpty() ? null : annotations.get(0);
    final List<String> immutables = new ArrayList<String>();
    if (anno == null) return immutables;

    final Expression expression = anno.getMember(MEMBER_KNOWN_IMMUTABLES);
    if (expression == null) return immutables;

    if (!(expression instanceof ListExpression)) {
        xform.addError("Use the Groovy list notation [el1, el2] to specify known immutable property names via \"" + MEMBER_KNOWN_IMMUTABLES + "\"", anno);
        return immutables;
    }

    final ListExpression listExpression = (ListExpression) expression;
    for (Expression listItemExpression : listExpression.getExpressions()) {
        if (listItemExpression instanceof ConstantExpression) {
            immutables.add((String) ((ConstantExpression) listItemExpression).getValue());
        }
    }
    if (!xform.checkPropertyList(cNode, immutables, "knownImmutables", anno, "immutable class", false)) return immutables;

    return immutables;
}
 
Example 7
Source File: AutoImplementASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode anno = (AnnotationNode) nodes[0];
    if (!MY_TYPE.equals(anno.getClassNode())) return;

    if (parent instanceof ClassNode) {
        ClassNode cNode = (ClassNode) parent;
        if (!checkNotInterface(cNode, MY_TYPE_NAME)) return;
        ClassNode exception = getMemberClassValue(anno, "exception");
        if (exception != null && Undefined.isUndefinedException(exception)) {
            exception = null;
        }
        String message = getMemberStringValue(anno, "message");
        Expression code = anno.getMember("code");
        if (code != null && !(code instanceof ClosureExpression)) {
            addError("Expected closure value for annotation parameter 'code'. Found " + code, cNode);
            return;
        }
        createMethods(cNode, exception, message, (ClosureExpression) code);
        if (code != null) {
            anno.setMember("code", new ClosureExpression(Parameter.EMPTY_ARRAY, EmptyStatement.INSTANCE));
        }
    }
}
 
Example 8
Source File: ASTTransformationVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private List<AnnotationNode> distinctAnnotations(AnnotatedNode node) {
    List<AnnotationNode> result = new LinkedList<>();
    AnnotationNode resultAnnotationNode = null;
    int resultIndex = -1;

    for (AnnotationNode annotationNode : node.getAnnotations()) {
        int index = COMPILEDYNAMIC_AND_COMPILESTATIC_AND_TYPECHECKED.indexOf(annotationNode.getClassNode().getName());
        if (-1 != index) {
            if (1 == index) { // CompileStatic
                Expression value = annotationNode.getMember("value");
                if (null != value && "groovy.transform.TypeCheckingMode.SKIP".equals(value.getText())) {
                    index = 0; // `CompileStatic` with "SKIP" `value` is actually `CompileDynamic`
                }
            }

            if (null == resultAnnotationNode || index < resultIndex) {
                resultAnnotationNode = annotationNode;
                resultIndex = index;
            }
            continue;
        }
        result.add(annotationNode);
    }

    if (null != resultAnnotationNode) result.add(resultAnnotationNode);

    return result;
}
 
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: ASTTransformationCollectorCodeVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void mergeParameters(final AnnotationNode to, final AnnotationNode from) {
    for (String name : from.getMembers().keySet()) {
        if (to.getMember(name) == null) {
            to.setMember(name, from.getMember(name));
        }
    }
}
 
Example 11
Source File: GrabAnnotationTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void checkForInitContextClassLoader(AnnotationNode node) {
    Object val = node.getMember("initContextClassLoader");
    if (!(val instanceof ConstantExpression)) return;
    Object initContextClassLoaderObject = ((ConstantExpression)val).getValue();
    if (!(initContextClassLoaderObject instanceof Boolean)) return;
    initContextClassLoader = (Boolean) initContextClassLoaderObject;
}
 
Example 12
Source File: PackageScopeASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode node = (AnnotationNode) nodes[0];
    boolean legacyMode = LEGACY_TYPE_NAME.equals(node.getClassNode().getName());
    if (!MY_TYPE.equals(node.getClassNode()) && !legacyMode) return;

    Expression value = node.getMember("value");
    if (parent instanceof ClassNode) {
        List<groovy.transform.PackageScopeTarget> targets;
        if (value == null) targets = Collections.singletonList(legacyMode ? PackageScopeTarget.FIELDS : PackageScopeTarget.CLASS);
        else targets = determineTargets(value);
        visitClassNode((ClassNode) parent, targets);
        parent.getAnnotations();
    } else {
        if (value != null) {
            addError("Error during " + MY_TYPE_NAME
                    + " processing: " + TARGET_CLASS_NAME + " only allowed at class level.", parent);
            return;
        }
        if (parent instanceof MethodNode) {
            visitMethodNode((MethodNode) parent);
        } else if (parent instanceof FieldNode) {
            visitFieldNode((FieldNode) parent);
        }
    }
}
 
Example 13
Source File: Traits.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Collects all the self types that a type should extend or implement, given
 * the traits is implements.
 * @param receiver a class node that may implement a trait
 * @param selfTypes a collection where the list of self types will be written
 * @param checkInterfaces should the interfaces that the node implements be collected too
 * @param checkSuper should we collect from the superclass too
 * @return the selfTypes collection itself
 * @since 2.4.0
 */
public static LinkedHashSet<ClassNode> collectSelfTypes(
        ClassNode receiver,
        LinkedHashSet<ClassNode> selfTypes,
        boolean checkInterfaces,
        boolean checkSuper) {
    if (Traits.isTrait(receiver)) {
        List<AnnotationNode> annotations = receiver.getAnnotations(SELFTYPE_CLASSNODE);
        for (AnnotationNode annotation : annotations) {
            Expression value = annotation.getMember("value");
            if (value instanceof ClassExpression) {
                selfTypes.add(value.getType());
            } else if (value instanceof ListExpression) {
                List<Expression> expressions = ((ListExpression) value).getExpressions();
                for (Expression expression : expressions) {
                    if (expression instanceof ClassExpression) {
                        selfTypes.add(expression.getType());
                    }
                }
            }
        }
    }
    if (checkInterfaces) {
        ClassNode[] interfaces = receiver.getInterfaces();
        for (ClassNode anInterface : interfaces) {
            collectSelfTypes(anInterface, selfTypes, true, checkSuper);
        }
    }

    if (checkSuper) {
        ClassNode superClass = receiver.getSuperClass();
        if (superClass != null) {
            collectSelfTypes(superClass, selfTypes, checkInterfaces, true);
        }
    }
    return selfTypes;
}
 
Example 14
Source File: AnnotationCollectorTransform.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static ClassNode getSerializeClass(ClassNode alias) {
    List<AnnotationNode> annotations = alias.getAnnotations(ClassHelper.make(AnnotationCollector.class));
    if (!annotations.isEmpty()) {
        AnnotationNode annotationNode = annotations.get(0);
        Expression member = annotationNode.getMember("serializeClass");
        if (member instanceof ClassExpression) {
            ClassExpression ce = (ClassExpression) member;
            if (!ce.getType().getName().equals(AnnotationCollector.class.getName())) {
                alias = ce.getType();
            }
        }
    }
    return alias;
}
 
Example 15
Source File: AbstractInterruptibleASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected static ClassNode getClassAnnotationParameter(AnnotationNode node, String parameterName, ClassNode defaultValue) {
    Expression member = node.getMember(parameterName);
    if (member != null) {
        if (member instanceof ClassExpression) {
            try {
                return member.getType();
            } catch (Exception e) {
                internalError("Expecting class value for " + parameterName + " annotation parameter. Found " + member + "member");
            }
        } else {
            internalError("Expecting class value for " + parameterName + " annotation parameter. Found " + member + "member");
        }
    }
    return defaultValue;
}
 
Example 16
Source File: GrabAnnotationTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void extractGrab(Expression init, ConstantExpression ce) {
    if (ce.getValue() instanceof AnnotationNode) {
        AnnotationNode annotation = (AnnotationNode) ce.getValue();
        if ((init != null) && (annotation.getMember("initClass") != null)) {
            annotation.setMember("initClass", init);
        }
        String name = annotation.getClassNode().getName();
        if ((GRAB_CLASS_NAME.equals(name))
                || (allowShortGrab && GRAB_SHORT_NAME.equals(name))
                || (grabAliases.contains(name))) {
            grabAnnotations.add(annotation);
        }
        if ((GRABEXCLUDE_CLASS_NAME.equals(name))
                || (allowShortGrabExcludes && GRABEXCLUDE_SHORT_NAME.equals(name))
                || (grabExcludeAliases.contains(name))) {
            grabExcludeAnnotations.add(annotation);
        }
        if ((GRABCONFIG_CLASS_NAME.equals(name))
                || (allowShortGrabConfig && GRABCONFIG_SHORT_NAME.equals(name))
                || (grabConfigAliases.contains(name))) {
            grabConfigAnnotations.add(annotation);
        }
        if ((GRABRESOLVER_CLASS_NAME.equals(name))
                || (allowShortGrabResolver && GRABRESOLVER_SHORT_NAME.equals(name))
                || (grabResolverAliases.contains(name))) {
            grabResolverAnnotations.add(annotation);
        }
    }
}
 
Example 17
Source File: CategoryASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static ClassNode getTargetClass(SourceUnit source, AnnotationNode annotation) {
    Expression value = annotation.getMember("value");
    if (!(value instanceof ClassExpression)) {
        //noinspection ThrowableInstanceNeverThrown
        source.getErrorCollector().addErrorAndContinue("@groovy.lang.Category must define 'value' which is the class to apply this category to", annotation, source);
        return null;
    } else {
        ClassExpression ce = (ClassExpression) value;
        return ce.getType();
    }
}
 
Example 18
Source File: GrabAnnotationTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void checkForDisableChecksums(AnnotationNode node) {
    Object val = node.getMember(DISABLE_CHECKSUMS_SETTING);
    if (!(val instanceof ConstantExpression)) return;
    Object disableChecksumsValue = ((ConstantExpression)val).getValue();
    if (!(disableChecksumsValue instanceof Boolean)) return;
    disableChecksums = (Boolean) disableChecksumsValue;
}
 
Example 19
Source File: GrabAnnotationTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void addGrabResolverAsStaticInitIfNeeded(ClassNode grapeClassNode, AnnotationNode node,
                                                  List<Statement> grabResolverInitializers, Map<String, Object> grabResolverMap) {
    if ((node.getMember("initClass") == null)
        || (node.getMember("initClass") == ConstantExpression.TRUE))
    {
        MapExpression resolverArgs = new MapExpression();
        for (Map.Entry<String, Object> next : grabResolverMap.entrySet()) {
            resolverArgs.addMapEntryExpression(constX(next.getKey()), constX(next.getValue()));
        }
        grabResolverInitializers.add(stmt(callX(grapeClassNode, "addResolver", args(resolverArgs))));
    }
}
 
Example 20
Source File: AbstractASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
public Object getMemberValue(AnnotationNode node, String name) {
    final Expression member = node.getMember(name);
    if (member instanceof ConstantExpression) return ((ConstantExpression) member).getValue();
    return null;
}