Java Code Examples for org.codehaus.groovy.ast.ClassNode#getDeclaredConstructors()

The following examples show how to use org.codehaus.groovy.ast.ClassNode#getDeclaredConstructors() . 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: GroovyVirtualSourceProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Parameter[] selectAccessibleConstructorFromSuper(ConstructorNode node) {
    ClassNode type = node.getDeclaringClass();
    ClassNode superType = type.getSuperClass();

    boolean hadPrivateConstructor = false;
    for (ConstructorNode c : superType.getDeclaredConstructors()) {
        // Only look at things we can actually call
        if (c.isPublic() || c.isProtected()) {
            return c.getParameters();
        }
    }

    // fall back for parameterless constructor
    if (superType.isPrimaryClassNode()) {
        return Parameter.EMPTY_ARRAY;
    }

    return null;
}
 
Example 2
Source File: ClassNodeUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Determine if an explicit (non-generated) constructor is in the class.
 *
 * @param xform if non null, add an error if an explicit constructor is found
 * @param cNode the type of the containing class
 * @return true if an explicit (non-generated) constructor was found
 */
public static boolean hasExplicitConstructor(AbstractASTTransformation xform, ClassNode cNode) {
    List<ConstructorNode> declaredConstructors = cNode.getDeclaredConstructors();
    for (ConstructorNode constructorNode : declaredConstructors) {
        // allow constructors added by other transforms if flagged as Generated
        if (isGenerated(constructorNode)) {
            continue;
        }
        if (xform != null) {
            xform.addError("Error during " + xform.getAnnotationName() +
                    " processing. Explicit constructors not allowed for class: " +
                    cNode.getNameWithoutPackage(), constructorNode);
        }
        return true;
    }
    return false;
}
 
Example 3
Source File: NullCheckASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode anno = (AnnotationNode) nodes[0];
    if (!NULL_CHECK_TYPE.equals(anno.getClassNode())) return;
    boolean includeGenerated = isIncludeGenerated(anno);

    if (parent instanceof ClassNode) {
        ClassNode cNode = (ClassNode) parent;
        if (!checkNotInterface(cNode, NULL_CHECK_NAME)) return;
        for (ConstructorNode cn : cNode.getDeclaredConstructors()) {
            adjustMethod(cn, includeGenerated);
        }
        for (MethodNode mn : cNode.getAllDeclaredMethods()) {
            adjustMethod(mn, includeGenerated);
        }
    } else if (parent instanceof MethodNode) {
        // handles constructor case too
        adjustMethod((MethodNode) parent, false);
    }
}
 
Example 4
Source File: InheritConstructorsASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void processClass(ClassNode cNode, AnnotationNode node) {
    if (cNode.isInterface()) {
        addError("Error processing interface '" + cNode.getName() +
                "'. " + ANNOTATION + " only allowed for classes.", cNode);
        return;
    }
    boolean copyConstructorAnnotations = memberHasValue(node, "constructorAnnotations", true);
    boolean copyParameterAnnotations = memberHasValue(node, "parameterAnnotations", true);
    ClassNode sNode = cNode.getSuperClass();
    List<AnnotationNode> superAnnotations = sNode.getAnnotations(INHERIT_CONSTRUCTORS_TYPE);
    if (superAnnotations.size() == 1) {
        // We need @InheritConstructors from parent classes processed first
        // so force that order here. The transformation is benign on an already
        // processed node so processing twice in any order won't matter bar
        // a very small time penalty.
        processClass(sNode, node);
    }
    for (ConstructorNode cn : sNode.getDeclaredConstructors()) {
        addConstructorUnlessAlreadyExisting(cNode, cn, copyConstructorAnnotations, copyParameterAnnotations);
    }
}
 
Example 5
Source File: Verifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected void addInitialization(final ClassNode node) {
    boolean addSwapInit = moveOptimizedConstantsInitialization(node);

    for (ConstructorNode cn : node.getDeclaredConstructors()) {
        addInitialization(node, cn);
    }

    if (addSwapInit) {
        BytecodeSequence seq = new BytecodeSequence(new BytecodeInstruction() {
            @Override
            public void visit(MethodVisitor mv) {
                mv.visitMethodInsn(INVOKESTATIC, BytecodeHelper.getClassInternalName(node), SWAP_INIT, "()V", false);
            }
        });

        List<Statement> swapCall = new ArrayList<>(1);
        swapCall.add(seq);
        node.addStaticInitializerStatements(swapCall, true);
    }
}
 
Example 6
Source File: FieldASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void adjustConstructorAndFields(int skipIndex, ClassNode type) {
    List<ConstructorNode> constructors = type.getDeclaredConstructors();
    if (constructors.size() == 1) {
        ConstructorNode constructor = constructors.get(0);
        Parameter[] params = constructor.getParameters();
        Parameter[] newParams = new Parameter[params.length - 1];
        int to = 0;
        for (int from = 0; from < params.length; from++) {
            if (from != skipIndex) {
                newParams[to++] = params[from];
            }
        }
        type.removeConstructor(constructor);
        // code doesn't mention the removed param at this point, okay to leave as is
        addGeneratedConstructor(type, constructor.getModifiers(), newParams, constructor.getExceptions(), constructor.getCode());
        type.removeField(variableName);
    }
}
 
Example 7
Source File: EnumCompletionVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Add map and no-arg constructor or mirror those of the superclass (i.e. base enum).
 */
private static void addImplicitConstructors(ClassNode enumClass, boolean aic) {
    if (aic) {
        ClassNode sn = enumClass.getSuperClass();
        List<ConstructorNode> sctors = new ArrayList<ConstructorNode>(sn.getDeclaredConstructors());
        if (sctors.isEmpty()) {
            addMapConstructors(enumClass);
        } else {
            for (ConstructorNode constructorNode : sctors) {
                ConstructorNode init = new ConstructorNode(ACC_PUBLIC, constructorNode.getParameters(), ClassNode.EMPTY_ARRAY, new BlockStatement());
                enumClass.addConstructor(init);
            }
        }
    } else {
        addMapConstructors(enumClass);
    }
}
 
Example 8
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Parameter[] selectAccessibleConstructorFromSuper(ConstructorNode node) {
    ClassNode type = node.getDeclaringClass();
    ClassNode superType = type.getUnresolvedSuperClass();

    Parameter[] bestMatch = null;
    for (ConstructorNode c : superType.getDeclaredConstructors()) {
        // Only look at things we can actually call
        if (!c.isPublic() && !c.isProtected()) continue;
        Parameter[] parameters = c.getParameters();
        // workaround for GROOVY-5859: remove generic type info
        Parameter[] copy = new Parameter[parameters.length];
        for (int i = 0; i < copy.length; i++) {
            Parameter orig = parameters[i];
            copy[i] = new Parameter(orig.getOriginType().getPlainNodeReference(), orig.getName());
        }
        if (noExceptionToAvoid(node,c)) return copy;
        if (bestMatch==null) bestMatch = copy;
    }
    if (bestMatch!=null) return bestMatch;

    // fall back for parameterless constructor
    if (superType.isPrimaryClassNode()) {
        return Parameter.EMPTY_ARRAY;
    }

    return null;
}
 
Example 9
Source File: GroovyVirtualSourceProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void getConstructors(ClassNode classNode, PrintWriter out) {
    List<ConstructorNode> constrs = classNode.getDeclaredConstructors();
    if (constrs != null) {
        for (ConstructorNode constrNode : constrs) {
            genConstructor(classNode, constrNode, out);
        }
    }
}
 
Example 10
Source File: InvocationWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static List<ConstructorNode> sortConstructors(final ConstructorCallExpression call, final ClassNode callNode) {
    // sort in a new list to prevent side effects
    List<ConstructorNode> constructors = new ArrayList<>(callNode.getDeclaredConstructors());
    constructors.sort((c0, c1) -> {
        String descriptor0 = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, c0.getParameters());
        String descriptor1 = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, c1.getParameters());
        return descriptor0.compareTo(descriptor1);
    });
    return constructors;
}
 
Example 11
Source File: OptimizingStatementWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static MethodNode selectConstructor(final ClassNode node, final Parameter[] parameters) {
    List<ConstructorNode> ctors = node.getDeclaredConstructors();
    MethodNode result = null;
    for (ConstructorNode ctor : ctors) {
        if (parametersEqual(ctor.getParameters(), parameters)) {
            result = ctor;
            break;
        }
    }
    return (result != null && result.isPublic() ? result : null);
}
 
Example 12
Source File: EnumCompletionVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void completeEnum(ClassNode enumClass) {
    boolean isAic = isAnonymousInnerClass(enumClass);
    if (enumClass.getDeclaredConstructors().isEmpty()) {
        addImplicitConstructors(enumClass, isAic);
    }

    for (ConstructorNode ctor : enumClass.getDeclaredConstructors()) {
        transformConstructor(ctor, isAic);
    }
}
 
Example 13
Source File: AutoFinalASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void processClass(ClassNode cNode, final ClassCodeVisitorSupport visitor) {
    if (!isEnabled(cNode)) return;
    if (cNode.isInterface()) {
        addError("Error processing interface '" + cNode.getName() +
                "'. " + MY_TYPE_NAME + " only allowed for classes.", cNode);
        return;
    }

    for (ConstructorNode cn : cNode.getDeclaredConstructors()) {
        if (hasNoExplicitAutoFinal(cn)) {
            processConstructorOrMethod(cn, visitor);
        }
    }

    for (MethodNode mn : cNode.getAllDeclaredMethods()) {
        if (hasNoExplicitAutoFinal(mn)) {
            processConstructorOrMethod(mn, visitor);
        }
    }

    Iterator<InnerClassNode> it = cNode.getInnerClasses();
    while (it.hasNext()) {
        InnerClassNode in = it.next();
        if (in.getAnnotations(MY_TYPE).isEmpty()) {
            processClass(in, visitor);
        }
    }

    visitor.visitClass(cNode);
}
 
Example 14
Source File: ClassNodeUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static boolean hasNoArgConstructor(ClassNode cNode) {
    List<ConstructorNode> constructors = cNode.getDeclaredConstructors();
    for (ConstructorNode next : constructors) {
        if (next.getParameters().length == 0) {
            return true;
        }
    }
    return false;
}
 
Example 15
Source File: ConstructorCallTransformer.java    From groovy with Apache License 2.0 4 votes vote down vote up
Expression transformConstructorCall(final ConstructorCallExpression expr) {
    ConstructorNode node = expr.getNodeMetaData(DIRECT_METHOD_CALL_TARGET);
    if (node == null) return expr;
    Parameter[] params = node.getParameters();
    if ((params.length == 1 || params.length == 2) // 2 is for inner class case
            && StaticTypeCheckingSupport.implementsInterfaceOrIsSubclassOf(params[params.length - 1].getType(), ClassHelper.MAP_TYPE)
            && node.getCode() == StaticTypeCheckingVisitor.GENERATED_EMPTY_STATEMENT) {
        Expression arguments = expr.getArguments();
        if (arguments instanceof TupleExpression) {
            TupleExpression tupleExpression = (TupleExpression) arguments;
            List<Expression> expressions = tupleExpression.getExpressions();
            if (expressions.size() == 1 || expressions.size() == 2) { // 2 = inner class case
                Expression expression = expressions.get(expressions.size() - 1);
                if (expression instanceof MapExpression) {
                    MapExpression map = (MapExpression) expression;
                    // check that the node doesn't belong to the list of declared constructors
                    ClassNode declaringClass = node.getDeclaringClass();
                    for (ConstructorNode constructorNode : declaringClass.getDeclaredConstructors()) {
                        if (constructorNode == node) {
                            return staticCompilationTransformer.superTransform(expr);
                        }
                    }
                    // replace call to <init>(Map) or <init>(this, Map)
                    // with a call to <init>() or <init>(this) + appropriate setters
                    // for example, foo(x:1, y:2) is replaced with:
                    // { def tmp = new Foo(); tmp.x = 1; tmp.y = 2; return tmp }()
                    MapStyleConstructorCall result = new MapStyleConstructorCall(
                            staticCompilationTransformer,
                            declaringClass,
                            map,
                            expr
                    );

                    return result;
                }
            }
        }

    }
    return staticCompilationTransformer.superTransform(expr);
}
 
Example 16
Source File: ClosureWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
public void writeClosure(final ClosureExpression expression) {
    CompileStack compileStack = controller.getCompileStack();
    MethodVisitor mv = controller.getMethodVisitor();
    ClassNode classNode = controller.getClassNode();
    AsmClassGenerator acg = controller.getAcg();

    // generate closure as public class to make sure it can be properly invoked by classes of the
    // Groovy runtime without circumventing JVM access checks (see CachedMethod for example).
    int mods = ACC_PUBLIC | ACC_FINAL;
    if (classNode.isInterface()) {
        mods |= ACC_STATIC;
    }
    ClassNode closureClass = getOrAddClosureClass(expression, mods);
    String closureClassinternalName = BytecodeHelper.getClassInternalName(closureClass);
    List<ConstructorNode> constructors = closureClass.getDeclaredConstructors();
    ConstructorNode node = constructors.get(0);

    Parameter[] localVariableParams = node.getParameters();

    mv.visitTypeInsn(NEW, closureClassinternalName);
    mv.visitInsn(DUP);
    if (controller.isStaticMethod() || compileStack.isInSpecialConstructorCall()) {
        (new ClassExpression(classNode)).visit(acg);
        (new ClassExpression(controller.getOutermostClass())).visit(acg);
    } else {
        mv.visitVarInsn(ALOAD, 0);
        controller.getOperandStack().push(ClassHelper.OBJECT_TYPE);
        loadThis();
    }

    // now let's load the various parameters we're passing
    // we start at index 2 because the first variable we pass
    // is the owner instance and at this point it is already
    // on the stack
    for (int i = 2; i < localVariableParams.length; i++) {
        Parameter param = localVariableParams[i];
        String name = param.getName();
        loadReference(name, controller);
        if (param.getNodeMetaData(ClosureWriter.UseExistingReference.class)==null) {
            param.setNodeMetaData(ClosureWriter.UseExistingReference.class,Boolean.TRUE);
        }
    }

    // we may need to pass in some other constructors
    //cv.visitMethodInsn(INVOKESPECIAL, innerClassinternalName, "<init>", prototype + ")V");
    mv.visitMethodInsn(INVOKESPECIAL, closureClassinternalName, "<init>", BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, localVariableParams), false);
    controller.getOperandStack().replace(ClassHelper.CLOSURE_TYPE, localVariableParams.length);
}
 
Example 17
Source File: AutoCloneASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static void createCloneCopyConstructor(ClassNode cNode, List<FieldNode> list, List<String> excludes) {
    if (cNode.getDeclaredConstructors().isEmpty()) {
        // add no-arg constructor
        BlockStatement noArgBody = new BlockStatement();
        noArgBody.addStatement(EmptyStatement.INSTANCE);
        addGeneratedConstructor(cNode, ACC_PUBLIC, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, noArgBody);
    }
    boolean hasThisCons = false;
    for (ConstructorNode consNode : cNode.getDeclaredConstructors()) {
        Parameter[] parameters = consNode.getParameters();
        if (parameters.length == 1 && parameters[0].getType().equals(cNode)) {
            hasThisCons = true;
        }
    }
    if (!hasThisCons) {
        BlockStatement initBody = new BlockStatement();
        Parameter initParam = param(GenericsUtils.nonGeneric(cNode), "other");
        final Expression other = varX(initParam);
        boolean hasParent = cNode.getSuperClass() != ClassHelper.OBJECT_TYPE;
        if (hasParent) {
            initBody.addStatement(stmt(ctorX(ClassNode.SUPER, other)));
        }
        for (FieldNode fieldNode : list) {
            String name = fieldNode.getName();
            if (excludes != null && excludes.contains(name)) continue;
            ClassNode fieldType = fieldNode.getType();
            Expression direct = propX(other, name);
            Expression to = propX(varX("this"), name);
            Statement assignDirect = assignS(to, direct);
            Statement assignCloned = assignS(to, castX(fieldType, callCloneDirectX(direct)));
            Statement assignClonedDynamic = assignS(to, castX(fieldType, callCloneDynamicX(direct)));
            if (isCloneableType(fieldType)) {
                initBody.addStatement(assignCloned);
            } else if (!possiblyCloneable(fieldType)) {
                initBody.addStatement(assignDirect);
            } else {
                initBody.addStatement(ifElseS(isInstanceOfX(direct, CLONEABLE_TYPE), assignClonedDynamic, assignDirect));
            }
        }
        addGeneratedConstructor(cNode, ACC_PROTECTED, params(initParam), ClassNode.EMPTY_ARRAY, initBody);
    }
    ClassNode[] exceptions = {make(CloneNotSupportedException.class)};
    addGeneratedMethod(cNode, "clone", ACC_PUBLIC, GenericsUtils.nonGeneric(cNode), Parameter.EMPTY_ARRAY, exceptions, block(stmt(ctorX(cNode, args(varX("this"))))));
}