org.codehaus.groovy.ast.AnnotationNode Java Examples

The following examples show how to use org.codehaus.groovy.ast.AnnotationNode. 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: ASTTransformationCollectorCodeVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static void mergeCollectedAnnotations(final AnnotationCollectorMode mode, final Map<Integer, List<AnnotationNode>> existing, final List<AnnotationNode> replacements) {
    switch (mode) {
        case PREFER_COLLECTOR:
            deleteExisting(false, existing, replacements);
            break;
        case PREFER_COLLECTOR_MERGED:
            deleteExisting(true, existing, replacements);
            break;
        case PREFER_EXPLICIT:
            deleteReplacement(false, existing, replacements);
            break;
        case PREFER_EXPLICIT_MERGED:
            deleteReplacement(true, existing, replacements);
            break;
        default:
            // nothing to do
    }
}
 
Example #2
Source File: InitializerStrategy.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void createBuilderForAnnotatedClass(BuilderASTTransformation transform, ClassNode buildee, AnnotationNode anno, boolean useSetters, boolean allNames, boolean force) {
    List<String> excludes = new ArrayList<String>();
    List<String> includes = new ArrayList<String>();
    includes.add(Undefined.STRING);
    if (!getIncludeExclude(transform, anno, buildee, excludes, includes)) return;
    if (includes.size() == 1 && Undefined.isUndefined(includes.get(0))) includes = null;
    List<FieldNode> fields = getFields(transform, anno, buildee);
    List<FieldNode> filteredFields = filterFields(fields, includes, excludes, allNames);
    if (filteredFields.isEmpty()) {
        transform.addError("Error during " + BuilderASTTransformation.MY_TYPE_NAME +
                " processing: at least one property is required for this strategy", anno);
    }
    ClassNode builder = createInnerHelperClass(buildee, getBuilderClassName(buildee, anno), filteredFields.size());
    addFields(buildee, filteredFields, builder);

    buildCommon(buildee, anno, filteredFields, builder);
    boolean needsConstructor = !AnnotatedNodeUtils.hasAnnotation(buildee, TUPLECONS_TYPE) || force;
    createBuildeeConstructors(transform, buildee, builder, filteredFields, needsConstructor, useSetters);
}
 
Example #3
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 #4
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void visitAnnotationArrayElement(final Expression expr, final int arrayElementType, final AnnotationVisitor av) {
    switch (arrayElementType) {
        case 1:
            AnnotationNode atAttr = (AnnotationNode) ((AnnotationConstantExpression) expr).getValue();
            AnnotationVisitor av2 = av.visitAnnotation(null, BytecodeHelper.getTypeDescription(atAttr.getClassNode()));
            visitAnnotationAttributes(atAttr, av2);
            av2.visitEnd();
            break;
        case 2:
            av.visit(null, ((ConstantExpression) expr).getValue());
            break;
        case 3:
            av.visit(null, Type.getType(BytecodeHelper.getTypeDescription(expr.getType())));
            break;
        case 4:
            PropertyExpression propExpr = (PropertyExpression) expr;
            av.visitEnum(null,
                    BytecodeHelper.getTypeDescription(propExpr.getObjectExpression().getType()),
                    String.valueOf(((ConstantExpression) propExpr.getProperty()).getValue()));
            break;
    }
}
 
Example #5
Source File: VetoableASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void addListenerToProperty(SourceUnit source, AnnotationNode node, AnnotatedNode parent) {
    ClassNode declaringClass = parent.getDeclaringClass();
    FieldNode field = ((FieldNode) parent);
    String fieldName = field.getName();
    for (PropertyNode propertyNode : declaringClass.getProperties()) {
        boolean bindable = BindableASTTransformation.hasBindableAnnotation(parent)
                || BindableASTTransformation.hasBindableAnnotation(parent.getDeclaringClass());

        if (propertyNode.getName().equals(fieldName)) {
            if (field.isStatic()) {
                //noinspection ThrowableInstanceNeverThrown
                source.getErrorCollector().addErrorAndContinue("@groovy.beans.Vetoable cannot annotate a static property.", node, source);
            } else {
                createListenerSetter(source, bindable, declaringClass, propertyNode);
            }
            return;
        }
    }
    //noinspection ThrowableInstanceNeverThrown
    source.getErrorCollector().addErrorAndContinue("@groovy.beans.Vetoable must be on a property, not a field.  Try removing the private, protected, or public modifier.", node, source);
}
 
Example #6
Source File: BindableASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void addListenerToProperty(SourceUnit source, AnnotationNode node, ClassNode declaringClass, FieldNode field) {
    String fieldName = field.getName();
    for (PropertyNode propertyNode : declaringClass.getProperties()) {
        if (propertyNode.getName().equals(fieldName)) {
            if (field.isStatic()) {
                //noinspection ThrowableInstanceNeverThrown
                source.getErrorCollector().addErrorAndContinue("@groovy.beans.Bindable cannot annotate a static property.", node, source);
            } else {
                if (needsPropertyChangeSupport(declaringClass, source)) {
                    addPropertyChangeSupport(declaringClass);
                }
                createListenerSetter(declaringClass, propertyNode);
            }
            return;
        }
    }
    //noinspection ThrowableInstanceNeverThrown
    source.getErrorCollector().addErrorAndContinue("@groovy.beans.Bindable must be on a property, not a field.  Try removing the private, protected, or public modifier.", node, source);
}
 
Example #7
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 #8
Source File: ExternalizeVerifierASTTransformation.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 (!hasNoArgConstructor(cNode)) {
            addError(MY_TYPE_NAME + ": An Externalizable class requires a no-arg constructor but none found", cNode);
        }
        if (!implementsExternalizable(cNode)) {
            addError(MY_TYPE_NAME + ": An Externalizable class must implement the Externalizable interface", cNode);
        }
        boolean includeFields = memberHasValue(anno, "includeFields", true);
        boolean checkPropertyTypes = memberHasValue(anno, "checkPropertyTypes", true);
        List<String> excludes = getMemberStringList(anno, "excludes");
        if (!checkPropertyList(cNode, excludes, "excludes", anno, MY_TYPE_NAME, includeFields)) return;
        List<FieldNode> list = getInstancePropertyFields(cNode);
        if (includeFields) {
            list.addAll(getInstanceNonPropertyFields(cNode));
        }
        checkProps(list, excludes, checkPropertyTypes);
    }
}
 
Example #9
Source File: NotYetImplementedASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotationNode anno = (AnnotationNode) nodes[0];
    MethodNode methodNode = (MethodNode) nodes[1];

    ClassNode exception = getMemberClassValue(anno, "exception");
    if (exception == null) {
        exception = DEFAULT_THROW_TYPE;
    }
    ConstructorNode cons = exception.getDeclaredConstructor(new Parameter[]{new Parameter(ClassHelper.STRING_TYPE, "dummy")});
    if (cons == null) {
        addError("Error during @NotYetImplemented processing: supplied exception " + exception.getNameWithoutPackage() + " doesn't have expected String constructor", methodNode);
    }

    if (methodNode.getCode() instanceof BlockStatement && !methodNode.getCode().isEmpty()) {
        // wrap code in try/catch with return for failure path followed by throws for success path

        TryCatchStatement tryCatchStatement = tryCatchS(methodNode.getCode());
        tryCatchStatement.addCatch(catchS(param(CATCH_TYPE, "ignore"), ReturnStatement.RETURN_NULL_OR_VOID));

        ThrowStatement throwStatement = throwS(ctorX(exception, args(constX("Method is marked with @NotYetImplemented but passes unexpectedly"))));

        methodNode.setCode(block(tryCatchStatement, throwStatement));
    }
}
 
Example #10
Source File: NamedVariantASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private boolean processExplicitNamedParam(final MethodNode mNode, final Parameter mapParam, final BlockStatement inner, final ArgumentListExpression args, final List<String> propNames, final Parameter fromParam) {
    AnnotationNode namedParam = fromParam.getAnnotations(NAMED_PARAM_TYPE).get(0);
    boolean required = memberHasValue(namedParam, "required", true);
    if (getMemberStringValue(namedParam, "value") == null) {
        namedParam.addMember("value", constX(fromParam.getName()));
    }
    String name = getMemberStringValue(namedParam, "value");
    if (getMemberValue(namedParam, "type") == null) {
        namedParam.addMember("type", classX(fromParam.getType()));
    }
    if (hasDuplicates(mNode, propNames, name)) return false;
    // TODO: Check specified type is assignable from declared param type?
    //ClassNode type = getMemberClassValue(namedParam, "type");
    if (required) {
        if (fromParam.hasInitialExpression()) {
            addError("Error during " + NAMED_VARIANT + " processing. A required parameter can't have an initial value.", mNode);
            return false;
        }
        inner.addStatement(new AssertStatement(boolX(callX(varX(mapParam), "containsKey", args(constX(name)))),
                plusX(constX("Missing required named argument '" + name + "'. Keys found: "), callX(varX(mapParam), "keySet"))));
    }
    args.addExpression(propX(varX(mapParam), name));
    mapParam.addAnnotation(namedParam);
    fromParam.getAnnotations().remove(namedParam);
    return true;
}
 
Example #11
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 #12
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static Expression transformInlineConstants(final Expression exp) {
    if (exp instanceof AnnotationConstantExpression) {
        ConstantExpression ce = (ConstantExpression) exp;
        if (ce.getValue() instanceof AnnotationNode) {
            // replicate a little bit of AnnotationVisitor here
            // because we can't wait until later to do this
            AnnotationNode an = (AnnotationNode) ce.getValue();
            for (Map.Entry<String, Expression> member : an.getMembers().entrySet()) {
                member.setValue(transformInlineConstants(member.getValue()));
            }
        }
    } else {
        return ExpressionUtils.transformInlineConstants(exp);
    }
    return exp;
}
 
Example #13
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 #14
Source File: ImmutablePropertyUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static List<String> getKnownImmutableClasses(AbstractASTTransformation xform, ClassNode cNode) {
    List<AnnotationNode> annotations = cNode.getAnnotations(ImmutablePropertyUtils.IMMUTABLE_OPTIONS_TYPE);
    AnnotationNode anno = annotations.isEmpty() ? null : annotations.get(0);
    final List<String> immutableClasses = new ArrayList<String>();

    if (anno == null) return immutableClasses;
    final Expression expression = anno.getMember(MEMBER_KNOWN_IMMUTABLE_CLASSES);
    if (expression == null) return immutableClasses;

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

    final ListExpression listExpression = (ListExpression) expression;
    for (Expression listItemExpression : listExpression.getExpressions()) {
        if (listItemExpression instanceof ClassExpression) {
            immutableClasses.add(listItemExpression.getType().getName());
        }
    }

    return immutableClasses;
}
 
Example #15
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 #16
Source File: PropertyHandler.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static PropertyHandler createPropertyHandler(AbstractASTTransformation xform, GroovyClassLoader loader, ClassNode cNode) {
    List<AnnotationNode> annotations = cNode.getAnnotations(PROPERTY_OPTIONS_TYPE);
    AnnotationNode anno = annotations.isEmpty() ? null : annotations.get(0);
    if (anno == null) return new groovy.transform.options.DefaultPropertyHandler();

    ClassNode handlerClass = xform.getMemberClassValue(anno, "propertyHandler", ClassHelper.make(groovy.transform.options.DefaultPropertyHandler.class));

    if (handlerClass == null) {
        xform.addError("Couldn't determine propertyHandler class", anno);
        return null;
    }

    String className = handlerClass.getName();
    try {
        Object instance = loader.loadClass(className).getDeclaredConstructor().newInstance();
        if (!PropertyHandler.class.isAssignableFrom(instance.getClass())) {
            xform.addError("The propertyHandler class '" + handlerClass.getName() + "' on " + xform.getAnnotationName() + " is not a propertyHandler", anno);
            return null;
        }

        return (PropertyHandler) instance;
    } catch (Exception e) {
        xform.addError("Can't load propertyHandler '" + className + "' " + e, anno);
        return null;
    }
}
 
Example #17
Source File: DefaultStrategy.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void buildClass(BuilderASTTransformation transform, ClassNode buildee, AnnotationNode anno) {
        List<String> excludes = new ArrayList<String>();
        List<String> includes = new ArrayList<String>();
        includes.add(Undefined.STRING);
        if (!getIncludeExclude(transform, anno, buildee, excludes, includes)) return;
        if (includes.size() == 1 && Undefined.isUndefined(includes.get(0))) includes = null;
        ClassNode builder = createBuilder(anno, buildee);
        createBuilderFactoryMethod(anno, buildee, builder);
//        List<FieldNode> fields = getFields(transform, anno, buildee);
        boolean allNames = transform.memberHasValue(anno, "allNames", true);
        boolean allProperties = !transform.memberHasValue(anno, "allProperties", false);
        List<PropertyInfo> props = getPropertyInfos(transform, anno, buildee, excludes, includes, allNames, allProperties);
        for (PropertyInfo pi : props) {
            ClassNode correctedType = getCorrectedType(buildee, pi.getType(), builder);
            String fieldName = pi.getName();
            builder.addField(createFieldCopy(buildee, fieldName, correctedType));
            addGeneratedMethod(builder, createBuilderMethodForProp(builder, new PropertyInfo(fieldName, correctedType), getPrefix(anno)));
        }
        addGeneratedMethod(builder, createBuildMethod(anno, buildee, props));
    }
 
Example #18
Source File: AutoCloneASTTransformation.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 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;
        cNode.addInterface(CLONEABLE_TYPE);
        boolean includeFields = memberHasValue(anno, "includeFields", true);
        AutoCloneStyle style = getStyle(anno, "style");
        List<String> excludes = getMemberStringList(anno, "excludes");
        if (!checkPropertyList(cNode, excludes, "excludes", anno, MY_TYPE_NAME, includeFields)) return;
        List<FieldNode> list = getInstancePropertyFields(cNode);
        if (includeFields) {
            list.addAll(getInstanceNonPropertyFields(cNode));
        }
        if (style == null) style = AutoCloneStyle.CLONE;
        switch (style) {
            case COPY_CONSTRUCTOR:
                createCloneCopyConstructor(cNode, list, excludes);
                break;
            case SERIALIZATION:
                createCloneSerialization(cNode);
                break;
            case SIMPLE:
                createSimpleClone(cNode, list, excludes);
                break;
            default:
                createClone(cNode, list, excludes);
                break;
        }
    }
}
 
Example #19
Source File: ASTTransformationCollectorCodeVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Class<?> loadTransformClass(final String transformClass, final AnnotationNode annotation) {
    try {
        return transformLoader.loadClass(transformClass, false, true, false);
    } catch (ReflectiveOperationException | LinkageError e) {
        String error = "Could not find class for Transformation Processor " + transformClass + " declared by " + annotation.getClassNode().getName();
        source.getErrorCollector().addErrorAndContinue(new SimpleMessage(error, source));
    }
    return null;
}
 
Example #20
Source File: AutoCloneASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static AutoCloneStyle getStyle(AnnotationNode node, String name) {
    final Expression member = node.getMember(name);
    if (member instanceof PropertyExpression) {
        PropertyExpression prop = (PropertyExpression) member;
        Expression oe = prop.getObjectExpression();
        if (oe instanceof ClassExpression) {
            ClassExpression ce = (ClassExpression) oe;
            if (ce.getType().getName().equals("groovy.transform.AutoCloneStyle")) {
                return AutoCloneStyle.valueOf(prop.getPropertyAsString());
            }
        }
    }
    return null;
}
 
Example #21
Source File: SortableASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void createSortable(AnnotationNode anno, ClassNode classNode) {
    List<String> includes = getMemberStringList(anno, "includes");
    List<String> excludes = getMemberStringList(anno, "excludes");
    boolean reversed = memberHasValue(anno, "reversed", true);
    boolean includeSuperProperties = memberHasValue(anno, "includeSuperProperties", true);
    boolean allNames = memberHasValue(anno, "allNames", true);
    boolean allProperties = !memberHasValue(anno, "allProperties", false);
    if (!checkIncludeExcludeUndefinedAware(anno, excludes, includes, MY_TYPE_NAME)) return;
    if (!checkPropertyList(classNode, includes, "includes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return;
    if (!checkPropertyList(classNode, excludes, "excludes", anno, MY_TYPE_NAME, false, includeSuperProperties, allProperties)) return;
    if (classNode.isInterface()) {
        addError(MY_TYPE_NAME + " cannot be applied to interface " + classNode.getName(), anno);
    }
    List<PropertyNode> properties = findProperties(anno, classNode, includes, excludes, allProperties, includeSuperProperties, allNames);
    implementComparable(classNode);

    addGeneratedMethod(classNode,
            "compareTo",
            ACC_PUBLIC,
            ClassHelper.int_TYPE,
            params(param(newClass(classNode), OTHER)),
            ClassNode.EMPTY_ARRAY,
            createCompareToMethodBody(properties, reversed)
    );

    for (PropertyNode property : properties) {
        createComparatorFor(classNode, property, reversed);
    }
    new VariableScopeVisitor(sourceUnit, true).visitClass(classNode);
}
 
Example #22
Source File: AnnotationConstantExpression.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void visit(GroovyCodeVisitor visitor) {
    AnnotationNode node = (AnnotationNode) getValue();
    Map<String, Expression> attrs = node.getMembers();
    for (Expression expr : attrs.values()) {
        expr.visit(visitor);
    }
    super.visit(visitor);
}
 
Example #23
Source File: RulesVisitor.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void visitGeneratedClosure(ClassNode node) {
    MethodNode method = AstUtils.getGeneratedClosureImplMethod(node);
    Boolean isRulesBlock = method.getCode().getNodeMetaData(AST_NODE_METADATA_KEY);
    if (isRulesBlock != null) {
        AnnotationNode markerAnnotation = new AnnotationNode(ANNOTATION_CLASS_NODE);
        node.addAnnotation(markerAnnotation);
    }
}
 
Example #24
Source File: FieldASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static boolean acceptableTransform(AnnotationNode annotation) {
    // TODO also check for phase after sourceUnit.getPhase()? but will be ignored anyway?
    // TODO we should only copy those annotations with FIELD_TARGET but haven't visited annotations
    // and gathered target info at this phase, so we can't do this:
    // return annotation.isTargetAllowed(AnnotationNode.FIELD_TARGET);
    // instead just don't copy ourselves for now
    return !annotation.getClassNode().equals(MY_TYPE);
}
 
Example #25
Source File: TraitComposer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static SyntaxException createException(ClassNode trait, ClassNode targetNode, MethodNode forwarder, MethodNode existingMethod) {
    String middle;
    ASTNode errorTarget;
    if (existingMethod.getLineNumber() == -1) {
        // came from a trait
        errorTarget = targetNode;
        List<AnnotationNode> allAnnos = existingMethod.getAnnotations(Traits.TRAITBRIDGE_CLASSNODE);
        AnnotationNode bridgeAnno = allAnnos == null ? null : allAnnos.get(0);
        String fromTrait = null;
        if (bridgeAnno != null) {
            Expression traitClass = bridgeAnno.getMember("traitClass");
            if (traitClass instanceof ClassExpression) {
                ClassExpression ce = (ClassExpression) traitClass;
                fromTrait = ce.getType().getNameWithoutPackage();
            }
        }
        middle = "in '" + targetNode.getNameWithoutPackage();
        if (fromTrait != null) {
            middle += "' from trait '" + fromTrait;
        }
    } else {
        errorTarget = existingMethod;
        middle = "declared in '" + targetNode.getNameWithoutPackage();
    }
    String message = "The static '" + forwarder.getName() + "' method " + middle +
            "' conflicts with the instance method having the same signature from trait '" + trait.getNameWithoutPackage() + "'";
    return new SyntaxException(message, errorTarget);
}
 
Example #26
Source File: UnionTypeClassNode.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public List<AnnotationNode> getAnnotations() {
    List<AnnotationNode> nodes = new LinkedList<AnnotationNode>();
    for (ClassNode delegate : delegates) {
        List<AnnotationNode> annotations = delegate.getAnnotations();
        if (annotations != null) nodes.addAll(annotations);
    }
    return nodes;
}
 
Example #27
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 #28
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 #29
Source File: ASTHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
public PackageNode setPackage(String packageName, List<AnnotationNode> annotations) {
    this.packageName = packageName;
    if (packageName != null && packageName.length() > 0) {
        packageName += '.';
    }
    PackageNode packageNode = new PackageNode(packageName);
    packageNode.addAnnotations(annotations);
    output.setPackage(packageNode);
    return packageNode;
}
 
Example #30
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));
}