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

The following examples show how to use org.codehaus.groovy.ast.MethodNode#getReturnType() . 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: BytecodeHelper.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static String getGenericsMethodSignature(MethodNode node) {
    GenericsType[] generics = node.getGenericsTypes();
    Parameter[] param = node.getParameters();
    ClassNode returnType = node.getReturnType();

    if (generics == null && !hasGenerics(param) && !hasGenerics(returnType)) return null;

    StringBuilder ret = new StringBuilder(100);
    getGenericsTypeSpec(ret, generics);

    GenericsType[] paramTypes = new GenericsType[param.length];
    for (int i = 0; i < param.length; i++) {
        ClassNode pType = param[i].getType();
        if (pType.getGenericsTypes() == null || !pType.isGenericsPlaceHolder()) {
            paramTypes[i] = new GenericsType(pType);
        } else {
            paramTypes[i] = pType.getGenericsTypes()[0];
        }
    }
    addSubTypes(ret, paramTypes, "(", ")");
    addSubTypes(ret, new GenericsType[]{new GenericsType(returnType)}, "", "");
    return ret.toString();
}
 
Example 2
Source File: GenericsUtils.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static ClassNode resolveClassNode(final SourceUnit sourceUnit, final CompilationUnit compilationUnit, final MethodNode mn, final ASTNode usage, final ClassNode parsedNode) {
    ClassNode dummyClass = new ClassNode("dummy", 0, ClassHelper.OBJECT_TYPE);
    dummyClass.setModule(new ModuleNode(sourceUnit));
    dummyClass.setGenericsTypes(mn.getDeclaringClass().getGenericsTypes());
    MethodNode dummyMN = new MethodNode(
            "dummy",
            0,
            parsedNode,
            Parameter.EMPTY_ARRAY,
            ClassNode.EMPTY_ARRAY,
            EmptyStatement.INSTANCE
    );
    dummyMN.setGenericsTypes(mn.getGenericsTypes());
    dummyClass.addMethod(dummyMN);
    ResolveVisitor visitor = new ResolveVisitor(compilationUnit) {
        @Override
        public void addError(final String msg, final ASTNode expr) {
            sourceUnit.addError(new IncorrectTypeHintException(mn, msg, usage.getLineNumber(), usage.getColumnNumber()));
        }
    };
    visitor.startResolving(dummyClass, sourceUnit);
    return dummyMN.getReturnType();
}
 
Example 3
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 4
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 6 votes vote down vote up
public static List<MethodNode> findSetters(final ClassNode cn, final String setterName, final boolean voidOnly) {
    List<MethodNode> result = null;
    for (MethodNode method : cn.getDeclaredMethods(setterName)) {
        if (setterName.equals(method.getName())
                && (!voidOnly || VOID_TYPE == method.getReturnType())
                && method.getParameters().length == 1) {
            if (result == null) {
                result = new LinkedList<>();
            }
            result.add(method);
        }
    }
    if (result == null) {
        ClassNode parent = cn.getSuperClass();
        if (parent != null) {
            return findSetters(parent, setterName, voidOnly);
        }
        return Collections.emptyList();
    }
    return result;
}
 
Example 5
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 6
Source File: MethodCallExpressionTransformer.java    From groovy with Apache License 2.0 6 votes vote down vote up
private static MethodCallExpression transformToMopSuperCall(final ClassNode superCallReceiver, final MethodCallExpression expr) {
    MethodNode mn = expr.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET);
    String mopName = MopWriter.getMopMethodName(mn, false);
    MethodNode direct = new MethodNode(
            mopName,
            ACC_PUBLIC | ACC_SYNTHETIC,
            mn.getReturnType(),
            mn.getParameters(),
            mn.getExceptions(),
            EmptyStatement.INSTANCE
    );
    direct.setDeclaringClass(superCallReceiver);
    MethodCallExpression result = new MethodCallExpression(
            new VariableExpression("this"),
            mopName,
            expr.getArguments()
    );
    result.setImplicitThis(true);
    result.setSpreadSafe(false);
    result.setSafe(false);
    result.setSourcePosition(expr);
    result.setMethodTarget(direct);
    return result;
}
 
Example 7
Source File: GroovyVirtualSourceProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void genMethod(ClassNode clazz, MethodNode methodNode, PrintWriter out, boolean ignoreSynthetic) {
    String name = methodNode.getName();
    if ((ignoreSynthetic && methodNode.isSynthetic()) || name.startsWith("super$")) { // NOI18N
        return;
    }
// </netbeans>
    if (methodNode.getName().equals("<clinit>")) {
        return;
    }
    if (!clazz.isInterface()) {
        printModifiers(out, methodNode.getModifiers());
    }
    printType(methodNode.getReturnType(), out);
    out.print(" ");
    out.print(methodNode.getName());

    printParams(methodNode, out);

    ClassNode[] exceptions = methodNode.getExceptions();
    if (exceptions != null && exceptions.length > 0) {
        out.print(" throws ");
        for (int i = 0; i < exceptions.length; i++) {
            if (i > 0) {
                out.print(", ");
            }
            printType(exceptions[i], out);
        }
    }

    if ((methodNode.getModifiers() & Opcodes.ACC_ABSTRACT) != 0) {
        out.println(";");
    } else {
        out.print(" { ");
        ClassNode retType = methodNode.getReturnType();
        printReturn(out, retType);
        out.println("}");
    }
}
 
Example 8
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 9
Source File: AnnotationVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private ClassNode getAttributeType(AnnotationNode node, String attrName) {
    ClassNode classNode = node.getClassNode();
    List methods = classNode.getMethods(attrName);
    // if size is >1, then the method was overwritten or something, we ignore that
    // if it is an error, we have to test it at another place. But size==0 is
    // an error, because it means that no such attribute exists.
    if (methods.isEmpty()) {
        addError("'" + attrName + "'is not part of the annotation " + classNode.getNameWithoutPackage(), node);
        return ClassHelper.OBJECT_TYPE;
    }
    MethodNode method = (MethodNode) methods.get(0);
    return method.getReturnType();
}
 
Example 10
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 11
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void removeMethodWithSuperReturnType(final List<MethodNode> toBeRemoved, final MethodNode one, final MethodNode two) {
    ClassNode oneRT = one.getReturnType();
    ClassNode twoRT = two.getReturnType();
    if (isCovariant(oneRT, twoRT)) {
        toBeRemoved.add(two);
    } else if (isCovariant(twoRT, oneRT)) {
        toBeRemoved.add(one);
    }
}
 
Example 12
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 13
Source File: MethodSignatureBuilder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public MethodSignatureBuilder appendReturnType(MethodCallExpression methodCall) {
    builder.append(" : "); // NOI18N

    final MethodNode methodTarget = methodCall.getMethodTarget();
    if (methodTarget != null && methodTarget.getReturnType() != null) {
        builder.append(methodTarget.getReturnType().getNameWithoutPackage());
    } else {
        // We don't know exact return type - just show an Object for now
        builder.append("Object"); // NOI18N
    }
    return this;
}
 
Example 14
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 15
Source File: BaseScriptASTTransformation.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void changeBaseScriptType(final AnnotatedNode parent, final ClassNode cNode, final ClassNode baseScriptType) {
    if (!cNode.isScriptBody()) {
        addError("Annotation " + MY_TYPE_NAME + " can only be used within a Script.", parent);
        return;
    }

    if (!baseScriptType.isScript()) {
        addError("Declared type " + baseScriptType + " does not extend groovy.lang.Script class!", parent);
        return;
    }

    cNode.setSuperClass(baseScriptType);

    // Method in base script that will contain the script body code.
    MethodNode runScriptMethod = ClassHelper.findSAM(baseScriptType);

    // If they want to use a name other than than "run", then make the change.
    if (isCustomScriptBodyMethod(runScriptMethod)) {
        MethodNode defaultMethod = cNode.getDeclaredMethod("run", Parameter.EMPTY_ARRAY);
        // GROOVY-6706: Sometimes an NPE is thrown here.
        // The reason is that our transform is getting called more than once sometimes.  
        if (defaultMethod != null) {
            cNode.removeMethod(defaultMethod);
            MethodNode methodNode = new MethodNode(runScriptMethod.getName(), runScriptMethod.getModifiers() & ~ACC_ABSTRACT
                    , runScriptMethod.getReturnType(), runScriptMethod.getParameters(), runScriptMethod.getExceptions()
                    , defaultMethod.getCode());
            // The AST node metadata has the flag that indicates that this method is a script body.
            // It may also be carrying data for other AST transforms.
            methodNode.copyNodeMetaData(defaultMethod);
            addGeneratedMethod(cNode, methodNode);
        }
    }

    // If the new script base class does not have a contextual constructor (g.l.Binding), then we won't either.
    // We have to do things this way (and rely on just default constructors) because the logic that generates
    // the constructors for our script class have already run.
    if (cNode.getSuperClass().getDeclaredConstructor(CONTEXT_CTOR_PARAMETERS) == null) {
        ConstructorNode orphanedConstructor = cNode.getDeclaredConstructor(CONTEXT_CTOR_PARAMETERS);
        cNode.removeConstructor(orphanedConstructor);
    }
}
 
Example 16
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 17
Source File: ASTTransformer.java    From pom-manipulation-ext with Apache License 2.0 4 votes vote down vote up
private void changeBaseScriptType(final AnnotatedNode parent, final ClassNode cNode, final ClassNode baseScriptType) {
    if (!cNode.isScriptBody()) {
        addError( "Annotation " + getType() + " can only be used within a Script.", parent);
        return;
    }

    if (!baseScriptType.isScript()) {
        addError("Declared type " + baseScriptType + " does not extend groovy.lang.Script class!", parent);
        return;
    }

    List<AnnotationNode> annotations = parent.getAnnotations( DEPRECATED_COMMAND_TYPE );
    if (cNode.getAnnotations( DEPRECATED_COMMAND_TYPE ).isEmpty()) { // #388 prevent "Duplicate annotation for class" AnnotationFormatError
        cNode.addAnnotations(annotations);
    }
    annotations = parent.getAnnotations( COMMAND_TYPE );
    if (cNode.getAnnotations( COMMAND_TYPE ).isEmpty()) { // #388 prevent "Duplicate annotation for class" AnnotationFormatError

        cNode.addAnnotations(annotations);
    }

    cNode.setSuperClass(baseScriptType);

    // Method in base script that will contain the script body code.
    MethodNode runScriptMethod = ClassHelper.findSAM(baseScriptType);

    // If they want to use a name other than than "run", then make the change.
    if (isCustomScriptBodyMethod(runScriptMethod)) {
        MethodNode defaultMethod = cNode.getDeclaredMethod("run", Parameter.EMPTY_ARRAY);
        // GROOVY-6706: Sometimes an NPE is thrown here.
        // The reason is that our transform is getting called more than once sometimes.
        if (defaultMethod != null) {
            cNode.removeMethod(defaultMethod);
            MethodNode methodNode = new MethodNode(runScriptMethod.getName(), runScriptMethod.getModifiers() & ~ACC_ABSTRACT
                            , runScriptMethod.getReturnType(), runScriptMethod.getParameters(), runScriptMethod.getExceptions()
                            , defaultMethod.getCode());
            // The AST node metadata has the flag that indicates that this method is a script body.
            // It may also be carrying data for other AST transforms.
            methodNode.copyNodeMetaData(defaultMethod);
            addGeneratedMethod(cNode, methodNode);
        }
    }

    // If the new script base class does not have a contextual constructor (g.l.Binding), then we won't either.
    // We have to do things this way (and rely on just default constructors) because the logic that generates
    // the constructors for our script class have already run.
    if (cNode.getSuperClass().getDeclaredConstructor(CONTEXT_CTOR_PARAMETERS) == null) {
        ConstructorNode orphanedConstructor = cNode.getDeclaredConstructor(CONTEXT_CTOR_PARAMETERS);
        cNode.removeConstructor(orphanedConstructor);
    }
}
 
Example 18
Source File: MethodInference.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@CheckForNull
private static ClassNode findReturnTypeFor(
        @NonNull ClassNode callerType, 
        @NonNull String methodName,
        @NonNull Expression arguments,
        @NonNull AstPath path,
        @NonNull boolean isStatic,
        @NonNull BaseDocument baseDocument,
        @NonNull int offset
        ) {

    List<ClassNode> paramTypes = new ArrayList<>();
    if (arguments instanceof ArgumentListExpression) {
        ArgumentListExpression argExpression = (ArgumentListExpression) arguments;
        for (Expression e : argExpression.getExpressions()) {
            if (e instanceof VariableExpression) {
                ModuleNode moduleNode = (ModuleNode) path.root();
                int newOffset = ASTUtils.getOffset(baseDocument, e.getLineNumber(), e.getColumnNumber());
                AstPath newPath = new AstPath(moduleNode, newOffset, baseDocument);
                TypeInferenceVisitor tiv = new TypeInferenceVisitor(moduleNode.getContext(), newPath, baseDocument, newOffset);
                tiv.collect();
                ClassNode guessedType = tiv.getGuessedType();
                if (null == guessedType) {
                    System.out.println("Bad guessed type");
                } else {
                    paramTypes.add(tiv.getGuessedType());
                }
            } else if(e instanceof ConstantExpression) {
                paramTypes.add(((ConstantExpression)e).getType());
            } else if (e instanceof MethodCallExpression) {
                paramTypes.add(findCallerType(e, path, baseDocument, offset));
            } else if (e instanceof BinaryExpression) {
                BinaryExpression binExpression = (BinaryExpression) e;
                paramTypes.add(binExpression.getType());
            } else if (e instanceof ClassExpression) {
                ClassExpression classExpression = (ClassExpression) e;
                // This should be Class<classExpression.getType()>
                paramTypes.add(GenericsUtils.makeClassSafeWithGenerics(Class.class, classExpression.getType()));
            } else {
                System.out.println(e.getClass());
            }
        }
    }

    MethodNode possibleMethod = tryFindPossibleMethod(callerType, methodName, paramTypes, isStatic);
    if (possibleMethod != null) {
        return possibleMethod.getReturnType();
    }
    return null;
}
 
Example 19
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void visitStdMethod(final MethodNode node, final boolean isConstructor, final Parameter[] parameters, final Statement code) {
    controller.getCompileStack().init(node.getVariableScope(), parameters);
    controller.getCallSiteWriter().makeSiteEntry();

    MethodVisitor mv = controller.getMethodVisitor();
    if (isConstructor && (code == null || !((ConstructorNode) node).firstStatementIsSpecialConstructorCall())) {
        boolean hasCallToSuper = false;
        if (code != null && isInnerClass()) {
            // GROOVY-4471: if the class is an inner class node, there are chances that
            // the call to super is already added so we must ensure not to add it twice
            if (code instanceof BlockStatement) {
                hasCallToSuper = ((BlockStatement) code).getStatements().stream()
                    .map(statement -> statement instanceof ExpressionStatement ? ((ExpressionStatement) statement).getExpression() : null)
                    .anyMatch(expression -> expression instanceof ConstructorCallExpression && ((ConstructorCallExpression) expression).isSuperCall());
            }
        }
        if (!hasCallToSuper) {
            // invokes the super class constructor
            mv.visitVarInsn(ALOAD, 0);
            mv.visitMethodInsn(INVOKESPECIAL, controller.getInternalBaseClassName(), "<init>", "()V", false);
        }
    }

    // handle body
    super.visitConstructorOrMethod(node, isConstructor);

    controller.getCompileStack().clear();
    if (node.isVoidMethod()) {
        mv.visitInsn(RETURN);
    } else {
        ClassNode type = node.getReturnType();
        if (ClassHelper.isPrimitiveType(type)) {
            mv.visitLdcInsn(0);
            controller.getOperandStack().push(ClassHelper.int_TYPE);
            controller.getOperandStack().doGroovyCast(type);
            BytecodeHelper.doReturn(mv, type);
            controller.getOperandStack().remove(1);
        } else {
            mv.visitInsn(ACONST_NULL);
            BytecodeHelper.doReturn(mv, type);
        }
    }
}
 
Example 20
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void printMethod(PrintWriter out, ClassNode clazz, MethodNode methodNode) {
    if (methodNode.getName().equals("<clinit>")) return;
    if (methodNode.isPrivate() || !Utilities.isJavaIdentifier(methodNode.getName())) return;
    if (methodNode.isSynthetic() && methodNode.getName().equals("$getStaticMetaClass")) return;

    printAnnotations(out, methodNode);
    if (!isInterfaceOrTrait(clazz)) {
        int modifiers = methodNode.getModifiers();
        if (isDefaultTraitImpl(methodNode)) {
            modifiers ^= Opcodes.ACC_ABSTRACT;
        }
        printModifiers(out, modifiers & ~(clazz.isEnum() ? Opcodes.ACC_ABSTRACT : 0));
    }

    printGenericsBounds(out, methodNode.getGenericsTypes());
    out.print(" ");
    printType(out, methodNode.getReturnType());
    out.print(" ");
    out.print(methodNode.getName());

    printParams(out, methodNode);

    ClassNode[] exceptions = methodNode.getExceptions();
    printExceptions(out, exceptions);

    if (Traits.isTrait(clazz)) {
        out.println(";");
    } else if (isAbstract(methodNode) && !clazz.isEnum()) {
        if (clazz.isAnnotationDefinition() && methodNode.hasAnnotationDefault()) {
            Statement fs = methodNode.getFirstStatement();
            if (fs instanceof ExpressionStatement) {
                ExpressionStatement es = (ExpressionStatement) fs;
                Expression re = es.getExpression();
                out.print(" default ");
                ClassNode rt = methodNode.getReturnType();
                boolean classReturn = ClassHelper.CLASS_Type.equals(rt) || (rt.isArray() && ClassHelper.CLASS_Type.equals(rt.getComponentType()));
                if (re instanceof ListExpression) {
                    out.print("{ ");
                    ListExpression le = (ListExpression) re;
                    boolean first = true;
                    for (Expression expression : le.getExpressions()) {
                        if (first) first = false;
                        else out.print(", ");
                        printValue(out, expression, classReturn);
                    }
                    out.print(" }");
                } else {
                    printValue(out, re, classReturn);
                }
            }
        }
        out.println(";");
    } else {
        out.print(" { ");
        ClassNode retType = methodNode.getReturnType();
        printReturn(out, retType);
        out.println("}");
    }
}