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

The following examples show how to use org.codehaus.groovy.ast.MethodNode#isStatic() . 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: StaticTypesMethodReferenceExpressionWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static Integer matchingScore(MethodNode mn, Expression typeOrTargetRef) {
    ClassNode typeOrTargetRefType = typeOrTargetRef.getType();

    int score = 9;
    for (ClassNode cn = mn.getDeclaringClass(); null != cn && !cn.equals(typeOrTargetRefType); cn = cn.getSuperClass()) {
        score--;
    }
    if (score < 0) {
        score = 0;
    }
    score *= 10;

    boolean isClassExpr = isClassExpr(typeOrTargetRef);
    boolean isStaticMethod = mn.isStatic();

    if (isClassExpr && isStaticMethod || !isClassExpr && !isStaticMethod) {
        score += 9;
    }

    if (isExtensionMethod(mn)) {
        score += 100;
    }

    return score;
}
 
Example 2
Source File: MemoizedASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static MethodNode buildDelegatingMethod(final MethodNode annotatedMethod, final ClassNode ownerClassNode) {
    Statement code = annotatedMethod.getCode();
    int access = ACC_PROTECTED;
    if (annotatedMethod.isStatic()) {
        access = ACC_PRIVATE | ACC_STATIC;
    }
    MethodNode method = new MethodNode(
            buildUniqueName(ownerClassNode, METHOD_LABEL, annotatedMethod),
            access,
            annotatedMethod.getReturnType(),
            cloneParams(annotatedMethod.getParameters()),
            annotatedMethod.getExceptions(),
            code
    );
    method.addAnnotations(filterAnnotations(annotatedMethod.getAnnotations()));
    return method;
}
 
Example 3
Source File: SemanticAnalysisVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void visitMethod(MethodNode node) {
    if (isInSource(node)) {
        OffsetRange range = ASTUtils.getRange(node, doc);
        EnumSet<ColoringAttributes> attributes = EnumSet.of(ColoringAttributes.METHOD);

        if (node.isStatic()) {
            attributes.add(ColoringAttributes.STATIC);
        }
        highlights.put(range, attributes);
    }
    super.visitMethod(node);
}
 
Example 4
Source File: InitializerStrategy.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void createBuilderForAnnotatedMethod(BuilderASTTransformation transform, MethodNode mNode, AnnotationNode anno, boolean useSetters) {
    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);
    }
    if (mNode instanceof ConstructorNode) {
        mNode.setModifiers(ACC_PRIVATE);
    } else {
        if (!mNode.isStatic()) {
            transform.addError("Error during " + BuilderASTTransformation.MY_TYPE_NAME +
                    " processing: method builders only allowed on static methods", anno);
        }
        mNode.setModifiers(ACC_SYNTHETIC | ACC_PRIVATE | ACC_STATIC);
    }
    ClassNode buildee = mNode.getDeclaringClass();
    Parameter[] parameters = mNode.getParameters();
    if (parameters.length == 0) {
        transform.addError("Error during " + BuilderASTTransformation.MY_TYPE_NAME +
                " processing: at least one parameter is required for this strategy", anno);
    }
    ClassNode builder = createInnerHelperClass(buildee, getBuilderClassName(buildee, anno), parameters.length);
    List<FieldNode> convertedFields = convertParamsToFields(builder, parameters);

    buildCommon(buildee, anno, convertedFields, builder);
    if (mNode instanceof ConstructorNode) {
        createBuildeeConstructors(transform, buildee, builder, convertedFields, false, useSetters);
    } else {
        createBuildeeMethods(buildee, mNode, builder, convertedFields);
    }
}
 
Example 5
Source File: BuilderASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean checkStatic(MethodNode mNode, String annotationName) {
    if (!mNode.isStatic() && !mNode.isStaticConstructor() && !(mNode instanceof ConstructorNode)) {
        addError("Error processing method '" + mNode.getName() + "'. " +
                annotationName + " not allowed for instance methods.", mNode);
        return false;
    }
    return true;
}
 
Example 6
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
static Map<GenericsTypeName, GenericsType> extractGenericsParameterMapOfThis(final MethodNode mn) {
    if (mn == null) return null;

    Map<GenericsTypeName, GenericsType> map;
    if (mn.isStatic()) {
        map = new HashMap<>();
    } else {
        map = getGenericsParameterMapOfThis(mn.getDeclaringClass());
    }

    return mergeGenerics(map, mn.getGenericsTypes());
}
 
Example 7
Source File: MopWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Filters a list of method for MOP methods. For all methods that are no
 * MOP methods a MOP method is created if the method is not public and the
 * call would be a call on "this" (isThis == true). If the call is not on
 * "this", then the call is a call on "super" and all methods are used,
 * unless they are already a MOP method.
 *
 * @param methods unfiltered list of methods for MOP
 * @param isThis  if true, then we are creating a MOP method on "this", "super" else
 *
 * @see #generateMopCalls(LinkedList, boolean)
 */
private void visitMopMethodList(List<MethodNode> methods, boolean isThis, Set<MopKey> useOnlyIfDeclaredHereToo, List<String> orNameMentionedHere) {
    Map<MopKey, MethodNode> mops = new HashMap<>();
    LinkedList<MethodNode> mopCalls = new LinkedList<>();
    for (MethodNode mn : methods) {
        // mop methods are helper for this and super calls and do direct calls
        // to the target methods. Such a method cannot be abstract or a bridge
        if ((mn.getModifiers() & (ACC_ABSTRACT | ACC_BRIDGE)) != 0) continue;
        if (mn.isStatic()) continue;
        // no this$ methods for non-private isThis=true
        // super$ method for non-private isThis=false
        // --> results in XOR
        boolean isPrivate = Modifier.isPrivate(mn.getModifiers());
        if (isThis ^ isPrivate) continue;
        String methodName = mn.getName();
        if (isMopMethod(methodName)) {
            mops.put(new MopKey(methodName, mn.getParameters()), mn);
            continue;
        }
        if (methodName.startsWith("<")) continue;
        if (!useOnlyIfDeclaredHereToo.contains(new MopKey(methodName, mn.getParameters())) &&
                !orNameMentionedHere.contains(methodName)) {
            continue;
        }
        String name = getMopMethodName(mn, isThis);
        MopKey key = new MopKey(name, mn.getParameters());
        if (mops.containsKey(key)) continue;
        mops.put(key, mn);
        mopCalls.add(mn);
    }
    generateMopCalls(mopCalls, isThis);
    mopCalls.clear();
    mops.clear();
}
 
Example 8
Source File: TraitASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private MethodNode processMethod(ClassNode traitClass, ClassNode traitHelperClass, MethodNode methodNode, ClassNode fieldHelper, Collection<String> knownFields) {
    Parameter[] initialParams = methodNode.getParameters();
    Parameter[] newParams = new Parameter[initialParams.length + 1];
    newParams[0] = createSelfParameter(traitClass, methodNode.isStatic());
    System.arraycopy(initialParams, 0, newParams, 1, initialParams.length);
    final int mod = methodNode.isPrivate() ? ACC_PRIVATE : ACC_PUBLIC | (methodNode.isFinal() ? ACC_FINAL : 0);
    MethodNode mNode = new MethodNode(
            methodNode.getName(),
            mod | ACC_STATIC,
            methodNode.getReturnType(),
            newParams,
            methodNode.getExceptions(),
            processBody(new VariableExpression(newParams[0]), methodNode.getCode(), traitClass, traitHelperClass, fieldHelper, knownFields)
    );
    mNode.setSourcePosition(methodNode);
    mNode.addAnnotations(filterAnnotations(methodNode.getAnnotations()));
    mNode.setGenericsTypes(methodNode.getGenericsTypes());
    if (methodNode.isAbstract()) {
        mNode.setModifiers(ACC_PUBLIC | ACC_ABSTRACT);
    } else {
        methodNode.addAnnotation(new AnnotationNode(Traits.IMPLEMENTED_CLASSNODE));
    }
    methodNode.setCode(null);

    if (!methodNode.isPrivate() && !methodNode.isStatic()) {
        methodNode.setModifiers(ACC_PUBLIC | ACC_ABSTRACT);
    }
    return mNode;
}
 
Example 9
Source File: NamedVariantASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean processDelegateParam(final MethodNode mNode, final Parameter mapParam, final ArgumentListExpression args, final List<String> propNames, final Parameter fromParam) {
    if (isInnerClass(fromParam.getType())) {
        if (mNode.isStatic()) {
            addError("Error during " + NAMED_VARIANT + " processing. Delegate type '" + fromParam.getType().getNameWithoutPackage() + "' is an inner class which is not supported.", mNode);
            return false;
        }
    }

    Set<String> names = new HashSet<>();
    List<PropertyNode> props = getAllProperties(names, fromParam.getType(), true, false, false, true, false, true);
    for (String next : names) {
        if (hasDuplicates(mNode, propNames, next)) return false;
    }
    List<MapEntryExpression> entries = new ArrayList<>();
    for (PropertyNode pNode : props) {
        String name = pNode.getName();
        // create entry [name: __namedArgs.getOrDefault('name', initialValue)]
        Expression defaultValue = Optional.ofNullable(pNode.getInitialExpression()).orElseGet(() -> getDefaultExpression(pNode.getType()));
        entries.add(entryX(constX(name), callX(varX(mapParam), "getOrDefault", args(constX(name), defaultValue))));
        // create annotation @NamedParam(value='name', type=DelegateType)
        AnnotationNode namedParam = new AnnotationNode(NAMED_PARAM_TYPE);
        namedParam.addMember("value", constX(name));
        namedParam.addMember("type", classX(pNode.getType()));
        mapParam.addAnnotation(namedParam);
    }
    Expression delegateMap = mapX(entries);
    args.addExpression(castX(fromParam.getType(), delegateMap));
    return true;
}
 
Example 10
Source File: GroovyNodeToStringUtils.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
public static String methodToString(MethodNode methodNode, ASTNodeVisitor ast) {
	if (methodNode instanceof ConstructorNode) {
		return constructorToString((ConstructorNode) methodNode, ast);
	}
	StringBuilder builder = new StringBuilder();
	if (methodNode.isPublic()) {
		if (!methodNode.isSyntheticPublic()) {
			builder.append("public ");
		}
	} else if (methodNode.isProtected()) {
		builder.append("protected ");
	} else if (methodNode.isPrivate()) {
		builder.append("private ");
	}

	if (methodNode.isStatic()) {
		builder.append("static ");
	}

	if (methodNode.isFinal()) {
		builder.append("final ");
	}
	ClassNode returnType = methodNode.getReturnType();
	builder.append(returnType.getNameWithoutPackage());
	builder.append(" ");
	builder.append(methodNode.getName());
	builder.append("(");
	builder.append(parametersToString(methodNode.getParameters(), ast));
	builder.append(")");
	return builder.toString();
}
 
Example 11
Source File: Verifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void storeMissingCovariantMethods(List declaredMethods, Map methodsToAdd, Map genericsSpec, List<MethodNode> methodNodeList) {
    for (Object declaredMethod : declaredMethods) {
        MethodNode method = (MethodNode) declaredMethod;
        if (method.isStatic()) continue;
        storeMissingCovariantMethods(methodNodeList, method, methodsToAdd, genericsSpec, false);
    }
}
 
Example 12
Source File: ClassCompletionVerifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void checkMethodsForIncorrectModifiers(ClassNode cn) {
    if (!cn.isInterface()) return;
    for (MethodNode method : cn.getMethods()) {
        if (method.isFinal()) {
            addError("The " + getDescription(method) + " from " + getDescription(cn) +
                    " must not be final. It is by definition abstract.", method);
        }
        if (method.isStatic() && !isConstructor(method)) {
            addError("The " + getDescription(method) + " from " + getDescription(cn) +
                    " must not be static. Only fields may be static in an interface.", method);
        }
    }
}
 
Example 13
Source File: Verifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void adjustTypesIfStaticMainMethod(MethodNode node) {
    if (node.getName().equals("main") && node.isStatic()) {
        Parameter[] params = node.getParameters();
        if (params.length == 1) {
            Parameter param = params[0];
            if (param.getType() == null || param.getType() == ClassHelper.OBJECT_TYPE) {
                param.setType(ClassHelper.STRING_TYPE.makeArray());
                ClassNode returnType = node.getReturnType();
                if (returnType == ClassHelper.OBJECT_TYPE) {
                    node.setReturnType(ClassHelper.VOID_TYPE);
                }
            }
        }
    }
}
 
Example 14
Source File: MemoizedASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
public void visit(ASTNode[] nodes, final SourceUnit source) {
    init(nodes, source);
    AnnotationNode annotationNode = (AnnotationNode) nodes[0];
    AnnotatedNode annotatedNode = (AnnotatedNode) nodes[1];
    if (MY_TYPE.equals(annotationNode.getClassNode()) && annotatedNode instanceof MethodNode) {
        MethodNode methodNode = (MethodNode) annotatedNode;
        if (methodNode.isAbstract()) {
            addError("Annotation " + MY_TYPE_NAME + " cannot be used for abstract methods.", methodNode);
            return;
        }
        if (methodNode.isVoidMethod()) {
            addError("Annotation " + MY_TYPE_NAME + " cannot be used for void methods.", methodNode);
            return;
        }

        ClassNode ownerClassNode = methodNode.getDeclaringClass();
        MethodNode delegatingMethod = buildDelegatingMethod(methodNode, ownerClassNode);
        addGeneratedMethod(ownerClassNode, delegatingMethod);

        int modifiers = FieldNode.ACC_PRIVATE | FieldNode.ACC_FINAL;
        if (methodNode.isStatic()) {
            modifiers = modifiers | FieldNode.ACC_STATIC;
        }

        int protectedCacheSize = getMemberIntValue(annotationNode, PROTECTED_CACHE_SIZE_NAME);
        int maxCacheSize = getMemberIntValue(annotationNode, MAX_CACHE_SIZE_NAME);
        MethodCallExpression memoizeClosureCallExpression =
                buildMemoizeClosureCallExpression(delegatingMethod, protectedCacheSize, maxCacheSize);

        String memoizedClosureFieldName = buildUniqueName(ownerClassNode, CLOSURE_LABEL, methodNode);
        FieldNode memoizedClosureField = new FieldNode(memoizedClosureFieldName, modifiers,
                newClass(ClassHelper.CLOSURE_TYPE), null, memoizeClosureCallExpression);
        ownerClassNode.addField(memoizedClosureField);

        BlockStatement newCode = new BlockStatement();
        MethodCallExpression closureCallExpression = callX(
                fieldX(memoizedClosureField), CLOSURE_CALL_METHOD_NAME, args(methodNode.getParameters()));
        closureCallExpression.setImplicitThis(false);
        newCode.addStatement(returnS(closureCallExpression));
        methodNode.setCode(newCode);
        VariableScopeVisitor visitor = new VariableScopeVisitor(source, ownerClassNode instanceof InnerClassNode);
        if (ownerClassNode instanceof InnerClassNode) {
            visitor.visitClass(((InnerClassNode) ownerClassNode).getOuterMostClass());
        } else {
            visitor.visitClass(ownerClassNode);
        }
    }
}
 
Example 15
Source File: StaticTypesMethodReferenceExpressionWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static boolean isTypeReferingInstanceMethod(Expression typeOrTargetRef, MethodNode mn) {  // class::instanceMethod
    return (!mn.isStatic() || (isExtensionMethod(mn) && !((ExtensionMethodNode) mn).isStaticExtension()))
            && isClassExpr(typeOrTargetRef);
}
 
Example 16
Source File: InvocationWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected boolean writeDirectMethodCall(final MethodNode target, final boolean implicitThis, final Expression receiver, final TupleExpression args) {
    if (target == null) return false;

    String methodName = target.getName();
    CompileStack compileStack = controller.getCompileStack();
    OperandStack operandStack = controller.getOperandStack();
    ClassNode declaringClass = target.getDeclaringClass();
    ClassNode classNode = controller.getClassNode();

    MethodVisitor mv = controller.getMethodVisitor();
    int opcode = INVOKEVIRTUAL;
    if (target.isStatic()) {
        opcode = INVOKESTATIC;
    } else if (declaringClass.isInterface()) {
        opcode = INVOKEINTERFACE;
    } else if (target.isPrivate() || AsmClassGenerator.isSuperExpression(receiver)) {
        opcode = INVOKESPECIAL;
    }

    // handle receiver
    int argumentsToRemove = 0;
    if (opcode != INVOKESTATIC) {
        if (receiver != null) {
            // load receiver if not static invocation
            // todo: fix inner class case
            if (implicitThis
                    && classNode.getOuterClass() != null
                    && !classNode.isDerivedFrom(declaringClass)
                    && !classNode.implementsInterface(declaringClass)) {
                // we are calling an outer class method
                compileStack.pushImplicitThis(false);
                if (controller.isInGeneratedFunction()) {
                    new VariableExpression("thisObject").visit(controller.getAcg());
                } else {
                    Expression expr = new PropertyExpression(new ClassExpression(declaringClass), "this");
                    expr.visit(controller.getAcg());
                }
            } else {
                compileStack.pushImplicitThis(implicitThis);
                receiver.visit(controller.getAcg());
            }
            operandStack.doGroovyCast(declaringClass);
            compileStack.popImplicitThis();
            argumentsToRemove += 1;
        } else {
            mv.visitIntInsn(ALOAD,0);
            operandStack.push(classNode);
            argumentsToRemove += 1;
        }
    }

    int stackSize = operandStack.getStackLength();

    String owner = BytecodeHelper.getClassInternalName(declaringClass);
    ClassNode receiverType = receiver != null ? controller.getTypeChooser().resolveType(receiver, classNode) : declaringClass;
    if (opcode == INVOKEVIRTUAL && ClassHelper.OBJECT_TYPE.equals(declaringClass)) {
        // avoid using a narrowed type if the method is defined on object because it can interfere
        // with delegate type inference in static compilation mode and trigger a ClassCastException
        receiverType = declaringClass;
    }
    if (opcode == INVOKEVIRTUAL) {
        if (!receiverType.equals(declaringClass)
                && !ClassHelper.OBJECT_TYPE.equals(declaringClass)
                && !receiverType.isArray()
                && !receiverType.isInterface()
                && !ClassHelper.isPrimitiveType(receiverType) // e.g int.getClass()
                && receiverType.isDerivedFrom(declaringClass)) {

            owner = BytecodeHelper.getClassInternalName(receiverType);
            ClassNode top = operandStack.getTopOperand();
            if (!receiverType.equals(top)) {
                mv.visitTypeInsn(CHECKCAST, owner);
            }
        } else if (target.isPublic()
                && (!receiverType.equals(declaringClass) && !Modifier.isPublic(declaringClass.getModifiers()))
                && receiverType.isDerivedFrom(declaringClass) && !Objects.equals(receiverType.getPackageName(), classNode.getPackageName())) {
            // GROOVY-6962: package private class, public method
            owner = BytecodeHelper.getClassInternalName(receiverType);
        }
    }

    loadArguments(args.getExpressions(), target.getParameters());

    String desc = BytecodeHelper.getMethodDescriptor(target.getReturnType(), target.getParameters());
    mv.visitMethodInsn(opcode, owner, methodName, desc, declaringClass.isInterface());
    ClassNode ret = target.getReturnType().redirect();
    if (ret == ClassHelper.VOID_TYPE) {
        ret = ClassHelper.OBJECT_TYPE;
        mv.visitInsn(ACONST_NULL);
    }
    argumentsToRemove += (operandStack.getStackLength()-stackSize);
    controller.getOperandStack().remove(argumentsToRemove);
    controller.getOperandStack().push(ret);
    return true;
}
 
Example 17
Source File: ClassCompletionVerifier.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void checkNoStaticMethodWithSameSignatureAsNonStatic(final ClassNode node) {
    ClassNode parent = node.getSuperClass();
    Map<String, MethodNode> result;
    // start with methods from the parent if any
    if (parent != null) {
        result = parent.getDeclaredMethodsMap();
    } else {
        result = new HashMap<String, MethodNode>();
    }
    // add in unimplemented abstract methods from the interfaces
    ClassNodeUtils.addDeclaredMethodsFromInterfaces(node, result);
    for (MethodNode methodNode : node.getMethods()) {
        MethodNode mn = result.get(methodNode.getTypeDescriptor());
        if (mn != null && (mn.isStatic() ^ methodNode.isStatic()) && !methodNode.isStaticConstructor()) {
            if (!mn.isAbstract()) continue;
            ClassNode declaringClass = mn.getDeclaringClass();
            ClassNode cn = declaringClass.getOuterClass();
            if (cn == null && declaringClass.isResolved()) {
                // in case of a precompiled class, the outerclass is unknown
                Class typeClass = declaringClass.getTypeClass();
                typeClass = typeClass.getEnclosingClass();
                if (typeClass != null) {
                    cn = ClassHelper.make(typeClass);
                }
            }
            if (!Traits.isTrait(cn)) {
                ASTNode errorNode = methodNode;
                String name = mn.getName();
                if (errorNode.getLineNumber() == -1) {
                    // try to get a better error message location based on the property
                    for (PropertyNode propertyNode : node.getProperties()) {
                        if (name.startsWith("set") || name.startsWith("get") || name.startsWith("is")) {
                            String propName = Verifier.capitalize(propertyNode.getField().getName());
                            String shortName = name.substring(name.startsWith("is") ? 2 : 3);
                            if (propName.equals(shortName)) {
                                errorNode = propertyNode;
                                break;
                            }
                        }
                    }
                }
                addError("The " + getDescription(methodNode) + " is already defined in " + getDescription(node) +
                        ". You cannot have both a static and an instance method with the same signature", errorNode);
            }
        }
        result.put(methodNode.getTypeDescriptor(), methodNode);
    }
}
 
Example 18
Source File: BeanUtils.java    From groovy with Apache License 2.0 4 votes vote down vote up
public static void addPseudoProperties(ClassNode origType, ClassNode cNode, List<PropertyNode> result, Set<String> names, boolean includeStatic, boolean includePseudoGetters, boolean includePseudoSetters) {
    if (!includePseudoGetters && !includePseudoSetters) return;
    List<MethodNode> methods = cNode.getAllDeclaredMethods();
    for (MethodNode mNode : methods) {
        if (!includeStatic && mNode.isStatic()) continue;
        if (hasAnnotation(mNode, INTERNAL_TYPE)) continue;
        String name = mNode.getName();
        if ((name.length() <= 3 && !name.startsWith(IS_PREFIX)) || name.equals("getClass") || name.equals("getMetaClass") || name.equals("getDeclaringClass")) {
            // Optimization: skip invalid propertyNames
            continue;
        }
        if (mNode.getDeclaringClass() != origType && mNode.isPrivate()) {
            // skip private super methods
            continue;
        }
        int paramCount = mNode.getParameters().length;
        ClassNode paramType = mNode.getReturnType();
        String propName = null;
        Statement getter = null;
        Statement setter = null;
        if (paramCount == 0) {
            if (includePseudoGetters && name.startsWith(GET_PREFIX)) {
                // Simple getter
                propName = decapitalize(name.substring(3));
                getter = mNode.getCode();
            } else if (includePseudoGetters && name.startsWith(IS_PREFIX) && paramType.equals(ClassHelper.boolean_TYPE)) {
                // boolean getter
                propName = decapitalize(name.substring(2));
                getter = mNode.getCode();
            }
        } else if (paramCount == 1) {
            if (includePseudoSetters && name.startsWith(SET_PREFIX)) {
                // Simple setter
                propName = decapitalize(name.substring(3));
                setter = mNode.getCode();
                paramType = mNode.getParameters()[0].getType();

            }
        }
        if (propName != null) {
            addIfMissing(cNode, result, names, mNode, paramType, propName, getter, setter);
        }
    }
}
 
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: 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;
}