Java Code Examples for org.codehaus.groovy.ast.ConstructorNode#getParameters()

The following examples show how to use org.codehaus.groovy.ast.ConstructorNode#getParameters() . 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: 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 3
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 4
Source File: Methods.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static boolean isSameConstructor(ConstructorNode constructor, ConstructorCallExpression call) {
    if (constructor.getDeclaringClass().getNameWithoutPackage().equals(call.getType().getNameWithoutPackage())) {
        // not comparing parameter types for now, only their count
        // is it even possible to make some check for parameter types?
        if (getParameterCount(call) == constructor.getParameters().length) {
            return true;
        }
    }
    return false;
}
 
Example 5
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static ClassNode getConstructorArgumentType(Expression arg, ConstructorNode node) {
    if (!(arg instanceof VariableExpression)) return arg.getType();
    VariableExpression vexp = (VariableExpression) arg;
    String name = vexp.getName();
    for (Parameter param : node.getParameters()) {
        if (param.getName().equals(name)) {
            return param.getType();
        }
    }
    return vexp.getType();
}
 
Example 6
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 7
Source File: InvocationWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static ConstructorNode getMatchingConstructor(final List<ConstructorNode> constructors, final List<Expression> argumentList) {
    ConstructorNode lastMatch = null;
    for (ConstructorNode cn : constructors) {
        Parameter[] params = cn.getParameters();
        // if number of parameters does not match we have no match
        if (argumentList.size() != params.length) continue;
        if (lastMatch == null) {
            lastMatch = cn;
        } else {
            // we already had a match so we don't make a direct call at all
            return null;
        }
    }
    return lastMatch;
}
 
Example 8
Source File: InvocationWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected boolean writeAICCall(final ConstructorCallExpression call) {
    if (!call.isUsingAnonymousInnerClass()) return false;
    ConstructorNode cn = call.getType().getDeclaredConstructors().get(0);
    OperandStack os = controller.getOperandStack();

    String ownerDescriptor = prepareConstructorCall(cn);

    List<Expression> args = makeArgumentList(call.getArguments()).getExpressions();
    Parameter[] params = cn.getParameters();
    // if a this appears as parameter here, then it should be
    // not static, unless we are in a static method. But since
    // ACG#visitVariableExpression does the opposite for this case, we
    // push here an explicit this. This should not have any negative effect
    // sine visiting a method call or property with implicit this will push
    // a new value for this again.
    controller.getCompileStack().pushImplicitThis(true);
    for (int i = 0, n = params.length; i < n; i += 1) {
        Parameter p = params[i];
        Expression arg = args.get(i);
        if (arg instanceof VariableExpression) {
            VariableExpression var = (VariableExpression) arg;
            loadVariableWithReference(var);
        } else {
            arg.visit(controller.getAcg());
        }
        os.doGroovyCast(p.getType());
    }
    controller.getCompileStack().popImplicitThis();
    finnishConstructorCall(cn, ownerDescriptor, args.size());
    return true;
}
 
Example 9
Source File: InnerClassCompletionVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void addThisReference(ConstructorNode node) {
    if (!shouldHandleImplicitThisForInnerClass(classNode)) return;

    // add "this$0" field init

    //add this parameter to node
    Parameter[] params = node.getParameters();
    Parameter[] newParams = new Parameter[params.length + 1];
    System.arraycopy(params, 0, newParams, 1, params.length);
    String name = getUniqueName(params, node);

    Parameter thisPara = new Parameter(classNode.getOuterClass().getPlainNodeReference(), name);
    newParams[0] = thisPara;
    node.setParameters(newParams);

    BlockStatement block = getCodeAsBlock(node);
    BlockStatement newCode = block();
    addFieldInit(thisPara, thisField, newCode);
    ConstructorCallExpression cce = getFirstIfSpecialConstructorCall(block);
    if (cce == null) {
        cce = ctorSuperX(new TupleExpression());
        block.getStatements().add(0, stmt(cce));
    }
    if (shouldImplicitlyPassThisPara(cce)) {
        // add thisPara to this(...)
        TupleExpression args = (TupleExpression) cce.getArguments();
        List<Expression> expressions = args.getExpressions();
        VariableExpression ve = varX(thisPara.getName());
        ve.setAccessedVariable(thisPara);
        expressions.add(0, ve);
    }
    if (cce.isSuperCall()) {
        // we have a call to super here, so we need to add
        // our code after that
        block.getStatements().add(1, newCode);
    }
    node.setCode(block);
}
 
Example 10
Source File: InheritConstructorsASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void addConstructorUnlessAlreadyExisting(ClassNode classNode, ConstructorNode consNode, boolean copyConstructorAnnotations, boolean copyParameterAnnotations) {
    Parameter[] origParams = consNode.getParameters();
    if (consNode.isPrivate()) return;
    Parameter[] params = new Parameter[origParams.length];
    Map<String, ClassNode> genericsSpec = createGenericsSpec(classNode);
    extractSuperClassGenerics(classNode, classNode.getSuperClass(), genericsSpec);
    List<Expression> theArgs = buildParams(origParams, params, genericsSpec, copyParameterAnnotations);
    if (isExisting(classNode, params)) return;
    ConstructorNode added = addGeneratedConstructor(classNode, consNode.getModifiers(), params, consNode.getExceptions(), block(ctorSuperS(args(theArgs))));
    if (copyConstructorAnnotations) {
        added.addAnnotations(copyAnnotatedNodeAnnotations(consNode, ANNOTATION, false));
    }
}
 
Example 11
Source File: MapConstructorASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void doAddConstructor(final ClassNode cNode, final ConstructorNode constructorNode) {
    markAsGenerated(cNode, constructorNode);
    cNode.addConstructor(constructorNode);
    // GROOVY-5814: Immutable is not compatible with @CompileStatic
    Parameter argsParam = null;
    for (Parameter p : constructorNode.getParameters()) {
        if ("args".equals(p.getName())) {
            argsParam = p;
            break;
        }
    }
    if (argsParam != null) {
        final Parameter arg = argsParam;
        ClassCodeVisitorSupport variableExpressionFix = new ClassCodeVisitorSupport() {
            @Override
            protected SourceUnit getSourceUnit() {
                return cNode.getModule().getContext();
            }

            @Override
            public void visitVariableExpression(final VariableExpression expression) {
                super.visitVariableExpression(expression);
                if ("args".equals(expression.getName())) {
                    expression.setAccessedVariable(arg);
                }
            }
        };
        variableExpressionFix.visitConstructor(constructorNode);
    }
}
 
Example 12
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 13
Source File: VariableScopeVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void addConstructorOccurrences(ConstructorNode constructor, ClassNode findingNode) {
    for (Parameter parameter : constructor.getParameters()) {
        addOccurrences(parameter.getType(), findingNode);
    }

    for (AnnotationNode annotation : constructor.getAnnotations(findingNode)) {
        addAnnotationOccurrences(annotation, findingNode);
    }
}
 
Example 14
Source File: VariableFinderVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void visitConstructor(ConstructorNode node) {
    if (!blocks.remove(node)) {
        return;
    }

    for (Parameter param : node.getParameters()) {
        variables.put(param.getName(), param);
    }

    super.visitConstructor(node);
}
 
Example 15
Source File: ASTNodeVisitor.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
public void visitConstructor(ConstructorNode node) {
	pushASTNode(node);
	try {
		super.visitConstructor(node);
		for (Parameter parameter : node.getParameters()) {
			visitParameter(parameter);
		}
	} finally {
		popASTNode();
	}
}
 
Example 16
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 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"))))));
}
 
Example 18
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void visitAttributeOrProperty(final PropertyExpression pexp, final MethodCallerMultiAdapter adapter) {
    ClassNode classNode = controller.getClassNode();
    String propertyName = pexp.getPropertyAsString();
    Expression objectExpression = pexp.getObjectExpression();

    if (objectExpression instanceof ClassExpression && "this".equals(propertyName)) {
        // we have something like A.B.this, and need to make it
        // into this.this$0.this$0, where this.this$0 returns
        // A.B and this.this$0.this$0 return A.
        ClassNode type = objectExpression.getType();
        if (controller.getCompileStack().isInSpecialConstructorCall() && type.equals(classNode.getOuterClass())) {
            // Outer.this in a special constructor call
            ConstructorNode ctor = controller.getConstructorNode();
            Expression receiver = !classNode.isStaticClass() ? new VariableExpression(ctor.getParameters()[0]) : new ClassExpression(type);
            receiver.setSourcePosition(pexp);
            receiver.visit(this);
            return;
        }

        MethodVisitor mv = controller.getMethodVisitor();
        mv.visitVarInsn(ALOAD, 0);
        ClassNode iterType = classNode;
        while (!iterType.equals(type)) {
            String ownerName = BytecodeHelper.getClassInternalName(iterType);
            if (iterType.getOuterClass() == null) break;
            FieldNode thisField = iterType.getField("this$0");
            iterType = iterType.getOuterClass();
            if (thisField == null) {
                // closure within inner class
                while (ClassHelper.isGeneratedFunction(iterType)) {
                    // GROOVY-8881: cater for closures within closures - getThisObject is already outer class of all closures
                    iterType = iterType.getOuterClass();
                }
                mv.visitMethodInsn(INVOKEVIRTUAL, BytecodeHelper.getClassInternalName(ClassHelper.CLOSURE_TYPE), "getThisObject", "()Ljava/lang/Object;", false);
                mv.visitTypeInsn(CHECKCAST, BytecodeHelper.getClassInternalName(iterType));
            } else {
                ClassNode thisFieldType = thisField.getType();
                if (ClassHelper.CLOSURE_TYPE.equals(thisFieldType)) {
                    mv.visitFieldInsn(GETFIELD, ownerName, "this$0", BytecodeHelper.getTypeDescription(ClassHelper.CLOSURE_TYPE));
                    mv.visitMethodInsn(INVOKEVIRTUAL, BytecodeHelper.getClassInternalName(ClassHelper.CLOSURE_TYPE), "getThisObject", "()Ljava/lang/Object;", false);
                    mv.visitTypeInsn(CHECKCAST, BytecodeHelper.getClassInternalName(iterType));
                } else {
                    String typeName = BytecodeHelper.getTypeDescription(iterType);
                    mv.visitFieldInsn(GETFIELD, ownerName, "this$0", typeName);
                }
            }
        }
        controller.getOperandStack().push(type);
        return;
    }

    if (propertyName != null) {
        // TODO: spread safe should be handled inside
        if (adapter == getProperty && !pexp.isSpreadSafe()) {
            controller.getCallSiteWriter().makeGetPropertySite(objectExpression, propertyName, pexp.isSafe(), pexp.isImplicitThis());
        } else if (adapter == getGroovyObjectProperty && !pexp.isSpreadSafe()) {
            controller.getCallSiteWriter().makeGroovyObjectGetPropertySite(objectExpression, propertyName, pexp.isSafe(), pexp.isImplicitThis());
        } else {
            controller.getCallSiteWriter().fallbackAttributeOrPropertySite(pexp, objectExpression, propertyName, adapter);
        }
    } else {
        controller.getCallSiteWriter().fallbackAttributeOrPropertySite(pexp, objectExpression, null, adapter);
    }
}
 
Example 19
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);
}