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

The following examples show how to use org.codehaus.groovy.ast.MethodNode#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: MethodNodeUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Return the method node's descriptor which includes its return type,
 * name and parameter types without generics.
 *
 * @param mNode the method node
 * @return the method node's descriptor
 */
public static String methodDescriptor(MethodNode mNode) {
    StringBuilder sb = new StringBuilder(mNode.getName().length() + mNode.getParameters().length * 10);
    sb.append(mNode.getReturnType().getName());
    sb.append(' ');
    sb.append(mNode.getName());
    sb.append('(');
    for (int i = 0; i < mNode.getParameters().length; i++) {
        if (i > 0) {
            sb.append(", ");
        }
        Parameter p = mNode.getParameters()[i];
        sb.append(ClassNodeUtils.formatTypeName(p.getType()));
    }
    sb.append(')');
    return sb.toString();
}
 
Example 2
Source File: TraitComposer.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a method to dispatch to "super traits" in a "stackable" fashion. The generated method looks like this:
 * <p>
 * <code>ReturnType trait$super$method(Class clazz, Arg1 arg1, Arg2 arg2, ...) {
 *     if (SomeTrait.is(A) { return SomeOtherTrait$Trait$Helper.method(this, arg1, arg2) }
 *     super.method(arg1,arg2)
 * }</code>
 * </p>
 * @param targetNode
 * @param forwarderMethod
 * @param interfacesToGenerateForwarderFor
 * @param genericsSpec
 */
private static void doCreateSuperForwarder(ClassNode targetNode, MethodNode forwarderMethod, ClassNode[] interfacesToGenerateForwarderFor, Map<String,ClassNode> genericsSpec) {
    Parameter[] parameters = forwarderMethod.getParameters();
    Parameter[] superForwarderParams = new Parameter[parameters.length];
    for (int i = 0; i < parameters.length; i++) {
        Parameter parameter = parameters[i];
        ClassNode originType = parameter.getOriginType();
        superForwarderParams[i] = new Parameter(correctToGenericsSpecRecurse(genericsSpec, originType), parameter.getName());
    }
    for (int i = 0; i < interfacesToGenerateForwarderFor.length; i++) {
        final ClassNode current = interfacesToGenerateForwarderFor[i];
        final ClassNode next = i < interfacesToGenerateForwarderFor.length - 1 ? interfacesToGenerateForwarderFor[i + 1] : null;
        String forwarderName = Traits.getSuperTraitMethodName(current, forwarderMethod.getName());
        if (targetNode.getDeclaredMethod(forwarderName, superForwarderParams) == null) {
            ClassNode returnType = correctToGenericsSpecRecurse(genericsSpec, forwarderMethod.getReturnType());
            Statement delegate = next == null ? createSuperFallback(forwarderMethod, returnType) : createDelegatingForwarder(forwarderMethod, next);
            MethodNode methodNode = targetNode.addMethod(forwarderName, Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, returnType, superForwarderParams, ClassNode.EMPTY_ARRAY, delegate);
            methodNode.setGenericsTypes(forwarderMethod.getGenericsTypes());
        }
    }
}
 
Example 3
Source File: AbstractExtensionMethodCache.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void accumulate(Map<String, List<MethodNode>> accumulator, boolean isStatic, MethodNode metaMethod,
                               Function<MethodNode, String> mapperFunction) {

    Parameter[] types = metaMethod.getParameters();
    Parameter[] parameters = new Parameter[types.length - 1];
    System.arraycopy(types, 1, parameters, 0, parameters.length);
    ExtensionMethodNode node = new ExtensionMethodNode(
            metaMethod,
            metaMethod.getName(),
            metaMethod.getModifiers(),
            metaMethod.getReturnType(),
            parameters,
            ClassNode.EMPTY_ARRAY, null,
            isStatic);
    node.setGenericsTypes(metaMethod.getGenericsTypes());
    ClassNode declaringClass = types[0].getType();
    node.setDeclaringClass(declaringClass);

    String key = mapperFunction.apply(metaMethod);

    List<MethodNode> nodes = accumulator.computeIfAbsent(key, k -> new ArrayList<>());
    nodes.add(node);
}
 
Example 4
Source File: StaticTypesClosureWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
protected ClassNode createClosureClass(final ClosureExpression expression, final int mods) {
    ClassNode closureClass = super.createClosureClass(expression, mods);
    List<MethodNode> methods = closureClass.getDeclaredMethods("call");
    List<MethodNode> doCall = closureClass.getMethods("doCall");
    if (doCall.size() != 1) {
        throw new GroovyBugError("Expected to find one (1) doCall method on generated closure, but found " + doCall.size());
    }
    MethodNode doCallMethod = doCall.get(0);
    if (methods.isEmpty() && doCallMethod.getParameters().length == 1) {
        createDirectCallMethod(closureClass, doCallMethod);
    }
    MethodTargetCompletionVisitor visitor = new MethodTargetCompletionVisitor(doCallMethod);
    Object dynamic = expression.getNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION);
    if (dynamic != null) {
        doCallMethod.putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, dynamic);
    }
    for (MethodNode method : methods) {
        visitor.visitMethod(method);
    }
    closureClass.putNodeMetaData(StaticCompilationMetadataKeys.STATIC_COMPILE_NODE, Boolean.TRUE);
    return closureClass;
}
 
Example 5
Source File: StaticVerifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitConstructorOrMethod(MethodNode node, boolean isConstructor) {
    MethodNode oldMethodNode = methodNode;
    methodNode = node;
    super.visitConstructorOrMethod(node, isConstructor);
    if (isConstructor) {
        for (Parameter param : node.getParameters()) {
            if (param.hasInitialExpression()) {
                // initial expression will be argument to special constructor call
                boolean oldIsSpecialConstructorCall = inSpecialConstructorCall;
                inSpecialConstructorCall = true;
                param.getInitialExpression().visit(this);
                inSpecialConstructorCall = oldIsSpecialConstructorCall;
            }
        }
    }
    methodNode = oldMethodNode;
}
 
Example 6
Source File: ASTNodeVisitor.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
public void visitMethod(MethodNode node) {
	pushASTNode(node);
	try {
		super.visitMethod(node);
		for (Parameter parameter : node.getParameters()) {
			visitParameter(parameter);
		}
	} finally {
		popASTNode();
	}
}
 
Example 7
Source File: MethodNodeUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Return the method node's descriptor including its
 * name and parameter types without generics.
 *
 * @param mNode the method node
 * @return the method node's abbreviated descriptor excluding the return type
 */
public static String methodDescriptorWithoutReturnType(MethodNode mNode) {
    StringBuilder sb = new StringBuilder();
    sb.append(mNode.getName()).append(':');
    for (Parameter p : mNode.getParameters()) {
        sb.append(ClassNodeUtils.formatTypeName(p.getType())).append(',');
    }
    return sb.toString();
}
 
Example 8
Source File: GroovydocVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void setConstructorOrMethodCommon(MethodNode node, SimpleGroovyExecutableMemberDoc methOrCons) {
    methOrCons.setRawCommentText(getDocContent(node.getGroovydoc()));
    processModifiers(methOrCons, node, node.getModifiers());
    processAnnotations(methOrCons, node);
    if (node.isAbstract()) {
        methOrCons.setAbstract(true);
    }
    for (Parameter param : node.getParameters()) {
        SimpleGroovyParameter p = new SimpleGroovyParameter(param.getName());
        p.setType(new SimpleGroovyType(makeType(param.getType())));
        processAnnotations(p, param);
        methOrCons.add(p);
    }
}
 
Example 9
Source File: ClassCompletionVerifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void checkMethodsForOverridingFinal(ClassNode cn) {
    for (MethodNode method : cn.getMethods()) {
        Parameter[] params = method.getParameters();
        for (MethodNode superMethod : cn.getSuperClass().getMethods(method.getName())) {
            Parameter[] superParams = superMethod.getParameters();
            if (!hasEqualParameterTypes(params, superParams)) continue;
            if (!superMethod.isFinal()) break;
            addInvalidUseOfFinalError(method, params, superMethod.getDeclaringClass());
            return;
        }
    }
}
 
Example 10
Source File: GenericsUtils.java    From groovy with Apache License 2.0 5 votes vote down vote up
public static MethodNode correctToGenericsSpec(Map<String, ClassNode> genericsSpec, MethodNode mn) {
    if (genericsSpec == null) return mn;
    if (mn.getGenericsTypes() != null) genericsSpec = addMethodGenerics(mn, genericsSpec);
    ClassNode correctedType = correctToGenericsSpecRecurse(genericsSpec, mn.getReturnType());
    Parameter[] origParameters = mn.getParameters();
    Parameter[] newParameters = new Parameter[origParameters.length];
    for (int i = 0; i < origParameters.length; i++) {
        Parameter origParameter = origParameters[i];
        newParameters[i] = new Parameter(correctToGenericsSpecRecurse(genericsSpec, origParameter.getType()), origParameter.getName(), origParameter.getInitialExpression());
    }
    return new MethodNode(mn.getName(), mn.getModifiers(), correctedType, newParameters, mn.getExceptions(), mn.getCode());
}
 
Example 11
Source File: GenericsVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitMethod(MethodNode node) {
    Parameter[] parameters = node.getParameters();
    for (Parameter param : parameters) {
        ClassNode paramType = param.getType();
        checkGenericsUsage(paramType, paramType.redirect());
    }
    ClassNode returnType = node.getReturnType();
    checkGenericsUsage(returnType, returnType.redirect());
    super.visitMethod(node);
}
 
Example 12
Source File: TransformationHandler.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String[] getMethodParams(MethodNode method) {
    String[] parameters = new String[method.getParameters().length];
    for (int i = 0; i < parameters.length; i++) {
        parameters[i] = method.getParameters()[i].getName();
    }
    return parameters;
}
 
Example 13
Source File: DefaultStrategy.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void buildMethod(BuilderASTTransformation transform, MethodNode mNode, AnnotationNode anno) {
    if (transform.getMemberValue(anno, "includes") != null || transform.getMemberValue(anno, "excludes") != null) {
        transform.addError("Error during " + BuilderASTTransformation.MY_TYPE_NAME +
                " processing: includes/excludes only allowed on classes", anno);
    }
    ClassNode buildee = mNode.getDeclaringClass();
    ClassNode builder = createBuilder(anno, buildee);
    createBuilderFactoryMethod(anno, buildee, builder);
    for (Parameter parameter : mNode.getParameters()) {
        builder.addField(createFieldCopy(buildee, parameter));
        addGeneratedMethod(builder, createBuilderMethodForProp(builder, new PropertyInfo(parameter.getName(), parameter.getType()), getPrefix(anno)));
    }
    addGeneratedMethod(builder, createBuildMethodForMethod(anno, buildee, mNode, mNode.getParameters()));
}
 
Example 14
Source File: Verifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static boolean equalParametersWithGenerics(MethodNode m1, MethodNode m2, Map genericsSpec) {
    Parameter[] p1 = m1.getParameters();
    Parameter[] p2 = m2.getParameters();
    if (p1.length != p2.length) return false;
    for (int i = 0; i < p2.length; i++) {
        ClassNode type = p2[i].getType();
        ClassNode genericsType = correctToGenericsSpec(genericsSpec, type);
        ClassNode parameterType = p1[i].getType();
        if (!parameterType.equals(genericsType)) return false;
    }
    return true;
}
 
Example 15
Source File: Verifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void addPropertyMethod(MethodNode method) {
    classNode.addMethod(method);
    markAsGenerated(classNode, method);
    // GROOVY-4415 / GROOVY-4645: check that there's no abstract method which corresponds to this one
    String methodName = method.getName();
    Parameter[] parameters = method.getParameters();
    ClassNode methodReturnType = method.getReturnType();
    for (MethodNode node : classNode.getAbstractMethods()) {
        if (!node.getDeclaringClass().equals(classNode)) continue;
        if (node.getName().equals(methodName) && node.getParameters().length == parameters.length) {
            if (parameters.length == 1) {
                // setter
                ClassNode abstractMethodParameterType = node.getParameters()[0].getType();
                ClassNode methodParameterType = parameters[0].getType();
                if (!methodParameterType.isDerivedFrom(abstractMethodParameterType) && !methodParameterType.implementsInterface(abstractMethodParameterType)) {
                    continue;
                }
            }
            ClassNode nodeReturnType = node.getReturnType();
            if (!methodReturnType.isDerivedFrom(nodeReturnType) && !methodReturnType.implementsInterface(nodeReturnType)) {
                continue;
            }
            // matching method, remove abstract status and use the same body
            node.setModifiers(node.getModifiers() ^ ACC_ABSTRACT);
            node.setCode(method.getCode());
        }
    }
}
 
Example 16
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
protected void visitConstructorOrMethod(final MethodNode node, final boolean isConstructor) {
    VariableScope oldScope = currentScope;
    currentScope = node.getVariableScope();
    Map<GenericsTypeName, GenericsType> oldPNames = genericParameterNames;
    genericParameterNames = node.isStatic() && !Traits.isTrait(node.getDeclaringClass())
            ? new HashMap<>() : new HashMap<>(genericParameterNames);

    resolveGenericsHeader(node.getGenericsTypes());

    Parameter[] paras = node.getParameters();
    for (Parameter p : paras) {
        p.setInitialExpression(transform(p.getInitialExpression()));
        resolveOrFail(p.getType(), p.getType());
        visitAnnotations(p);
    }
    ClassNode[] exceptions = node.getExceptions();
    for (ClassNode t : exceptions) {
        resolveOrFail(t, node);
    }
    resolveOrFail(node.getReturnType(), node);

    MethodNode oldCurrentMethod = currentMethod;
    currentMethod = node;
    super.visitConstructorOrMethod(node, isConstructor);

    currentMethod = oldCurrentMethod;
    genericParameterNames = oldPNames;
    currentScope = oldScope;
}
 
Example 17
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Collection<MethodNode> removeCovariantsAndInterfaceEquivalents(final Collection<MethodNode> collection) {
    if (collection.size() <= 1) return collection;
    List<MethodNode> toBeRemoved = new LinkedList<>();
    List<MethodNode> list = new LinkedList<>(new LinkedHashSet<>(collection));
    for (int i = 0, n = list.size(); i < n - 1; i += 1) {
        MethodNode one = list.get(i);
        if (toBeRemoved.contains(one)) continue;
        for (int j = i + 1; j < n; j += 1) {
            MethodNode two = list.get(j);
            if (toBeRemoved.contains(two)) continue;
            if (one.getParameters().length == two.getParameters().length) {
                if (areOverloadMethodsInSameClass(one, two)) {
                    if (ParameterUtils.parametersEqual(one.getParameters(), two.getParameters())) {
                        removeMethodWithSuperReturnType(toBeRemoved, one, two);
                    } else {
                        // this is an imperfect solution to determining if two methods are
                        // equivalent, for example String#compareTo(Object) and String#compareTo(String)
                        // in that case, Java marks the Object version as synthetic
                        removeSyntheticMethodIfOne(toBeRemoved, one, two);
                    }
                } else if (areEquivalentInterfaceMethods(one, two)) {
                    // GROOVY-6970: choose between equivalent interface methods
                    removeMethodInSuperInterface(toBeRemoved, one, two);
                }
            }
        }
    }
    if (toBeRemoved.isEmpty()) return list;
    List<MethodNode> result = new LinkedList<>(list);
    result.removeAll(toBeRemoved);
    return result;
}
 
Example 18
Source File: MethodInference.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static MethodNode tryFindPossibleMethod(ClassNode callerType, String methodName, List<ClassNode> paramTypes, boolean isStatic) {
    int count = paramTypes.size();

    MethodNode res = null;
    ClassNode node = callerType;
    do {
        for (MethodNode method : node.getMethods(methodName)) {
            if (isStatic && !method.isStatic()) {
                continue;
            }
            if (method.getParameters().length == count) {
                boolean match = true;
                for (int i = 0; i != count; ++i) {
                    if (!paramTypes.get(i).isDerivedFrom(method.getParameters()[i].getType())) {
                        match = false;
                        break;
                    }
                }

                if (match) {
                    if (res == null) {
                        res = method;
                    } else {
                        if (res.getParameters().length != count) {
                            return null;
                        }
                        if (node.equals(callerType)) {
                            return null;
                        }

                        match = true;
                        for (int i = 0; i != count; ++i) {
                            if (!res.getParameters()[i].getType().equals(method.getParameters()[i].getType())) {
                                match = false;
                                break;
                            }
                        }
                        if (!match) {
                            return null;
                        }
                    }
                }
            }
        }
        node = node.getSuperClass();
    } while (node != null);

    return res;
}
 
Example 19
Source File: ClassNodeUtils.java    From groovy with Apache License 2.0 4 votes vote down vote up
/**
 * Returns true if the given method has a possibly matching static method with the given name and arguments.
 * Handles default arguments and optionally spread expressions.
 *
 * @param cNode     the ClassNode of interest
 * @param name      the name of the method of interest
 * @param arguments the arguments to match against
 * @param trySpread whether to try to account for SpreadExpressions within the arguments
 * @return true if a matching method was found
 */
public static boolean hasPossibleStaticMethod(ClassNode cNode, String name, Expression arguments, boolean trySpread) {
    int count = 0;
    boolean foundSpread = false;

    if (arguments instanceof TupleExpression) {
        TupleExpression tuple = (TupleExpression) arguments;
        for (Expression arg : tuple.getExpressions()) {
            if (arg instanceof SpreadExpression) {
                foundSpread = true;
            } else {
                count++;
            }
        }
    } else if (arguments instanceof MapExpression) {
        count = 1;
    }

    for (MethodNode method : cNode.getMethods(name)) {
        if (method.isStatic()) {
            Parameter[] parameters = method.getParameters();
            // do fuzzy match for spread case: count will be number of non-spread args
            if (trySpread && foundSpread && parameters.length >= count) return true;

            if (parameters.length == count) return true;

            // handle varargs case
            if (parameters.length > 0 && parameters[parameters.length - 1].getType().isArray()) {
                if (count >= parameters.length - 1) return true;
                // fuzzy match any spread to a varargs
                if (trySpread && foundSpread) return true;
            }

            // handle parameters with default values
            int nonDefaultParameters = 0;
            for (Parameter parameter : parameters) {
                if (!parameter.hasInitialExpression()) {
                    nonDefaultParameters++;
                }
            }

            if (count < parameters.length && nonDefaultParameters <= count) {
                return true;
            }
            // TODO handle spread with nonDefaultParams?
        }
    }
    return false;
}
 
Example 20
Source File: ClosureSignatureHint.java    From groovy with Apache License 2.0 2 votes vote down vote up
/**
 * A helper method which will extract the n-th generic type from the n-th parameter of a method node.
 * @param node the method node from which the generic type should be picked
 * @param parameterIndex the index of the parameter in the method parameter list
 * @param gtIndex the index of the generic type to extract
 * @return the generic type, or {@link org.codehaus.groovy.ast.ClassHelper#OBJECT_TYPE} if it doesn't exist.
 */
public static ClassNode pickGenericType(MethodNode node, int parameterIndex, int gtIndex) {
    final Parameter[] parameters = node.getParameters();
    final ClassNode type = parameters[parameterIndex].getOriginType();
    return pickGenericType(type, gtIndex);
}