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

The following examples show how to use org.codehaus.groovy.ast.MethodNode#isAbstract() . 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: SynchronizedASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotatedNode parent = (AnnotatedNode) nodes[1];
    AnnotationNode node = (AnnotationNode) nodes[0];
    if (!MY_TYPE.equals(node.getClassNode())) return;
    String value = getMemberStringValue(node, "value");

    if (parent instanceof MethodNode) {
        MethodNode mNode = (MethodNode) parent;
        if (mNode.isAbstract()) {
            addError("Error during " + MY_TYPE_NAME + " processing: annotation not allowed on abstract method '" + mNode.getName() + "'", mNode);
            return;
        }
        ClassNode cNode = mNode.getDeclaringClass();
        String lockExpr = determineLock(value, cNode, mNode);
        if (lockExpr == null) return;
        Statement origCode = mNode.getCode();
        Statement newCode = new SynchronizedStatement(varX(lockExpr), origCode);
        mNode.setCode(newCode);
    }
}
 
Example 2
Source File: ClassCompletionVerifier.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void checkNoAbstractMethodsNonabstractClass(ClassNode node) {
    if (isAbstract(node.getModifiers())) return;
    for (MethodNode method : node.getAbstractMethods()) {
        MethodNode sameArgsMethod = node.getMethod(method.getName(), method.getParameters());
        if (null == sameArgsMethod) {
            sameArgsMethod = ClassHelper.GROOVY_OBJECT_TYPE.getMethod(method.getName(), method.getParameters());
            if (null != sameArgsMethod && !sameArgsMethod.isAbstract() && method.getReturnType().equals(sameArgsMethod.getReturnType())) {
                return;
            }
        }

        if (sameArgsMethod==null || method.getReturnType().equals(sameArgsMethod.getReturnType())) {
            addError("Can't have an abstract method in a non-abstract class." +
                    " The " + getDescription(node) + " must be declared abstract or" +
                    " the " + getDescription(method) + " must be implemented.", node);
        } else {
            addError("Abstract "+getDescription(method)+" is not implemented but a " +
                            "method of the same name but different return type is defined: "+
                            (sameArgsMethod.isStatic()?"static ":"")+
                            getDescription(sameArgsMethod), method
            );
        }
    }
}
 
Example 3
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 4
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 5
Source File: AutoImplementASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void createMethods(ClassNode cNode, ClassNode exception, String message, ClosureExpression code) {
    for (MethodNode candidate : getAllCorrectedMethodsMap(cNode).values()) {
        if (candidate.isAbstract()) {
            addGeneratedMethod(cNode, candidate.getName(), Opcodes.ACC_PUBLIC, candidate.getReturnType(),
                    candidate.getParameters(), candidate.getExceptions(),
                    methodBody(exception, message, code, candidate.getReturnType()));
        }
    }
}
 
Example 6
Source File: ClassCompletionVerifier.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void checkAbstractDeclaration(MethodNode methodNode) {
    if (!methodNode.isAbstract()) return;
    if (isAbstract(currentClass.getModifiers())) return;
    addError("Can't have an abstract method in a non-abstract class." +
            " The " + getDescription(currentClass) + " must be declared abstract or the method '" +
            methodNode.getTypeDescriptor() + "' must not be abstract.", methodNode);
}
 
Example 7
Source File: EnumVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void checkForAbstractMethods(final ClassNode enumClass) {
    for (MethodNode method : enumClass.getMethods()) {
        if (method.isAbstract()) {
            // make the class abstract also; see Effective Java p.152
            enumClass.setModifiers(enumClass.getModifiers() | ACC_ABSTRACT);
            break;
        }
    }
}
 
Example 8
Source File: JavaStubGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean isCandidateTraitMethod(ClassNode trait, MethodNode traitMethod) {
    boolean precompiled = trait.redirect() instanceof DecompiledClassNode;
    if (!precompiled) return !traitMethod.isAbstract();
    List<MethodNode> helperMethods = Traits.findHelper(trait).getMethods();
    for (MethodNode helperMethod : helperMethods) {
        boolean isSynthetic = (traitMethod.getModifiers() & Opcodes.ACC_SYNTHETIC) != 0;
        if (helperMethod.getName().equals(traitMethod.getName()) && !isSynthetic && !traitMethod.getName().contains("$")) {
            Parameter[] origParams = helperMethod.getParameters();
            Parameter[] newParams = Arrays.copyOfRange(origParams, 1, origParams.length);
            if (sameParameterTypes(newParams, traitMethod.getParameters())) return true;
        }
    }
    return false;
}
 
Example 9
Source File: FromAbstractTypeMethods.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static List<ClassNode[]> extractSignaturesFromMethods(final ClassNode cn) {
    List<MethodNode> methods = cn.getAllDeclaredMethods();
    List<ClassNode[]> signatures = new LinkedList<ClassNode[]>();
    for (MethodNode method : methods) {
        if (!method.isSynthetic() && method.isAbstract()) {
            extractParametersFromMethod(signatures, method);
        }
    }
    return signatures;
}
 
Example 10
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 11
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 12
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
protected void visitConstructorOrMethod(final MethodNode node, final boolean isConstructor) {
    controller.resetLineNumber();
    Parameter[] parameters = node.getParameters();
    String methodType = BytecodeHelper.getMethodDescriptor(node.getReturnType(), parameters);
    String signature = BytecodeHelper.getGenericsMethodSignature(node);
    int modifiers = node.getModifiers();
    if (isVargs(node.getParameters())) modifiers |= ACC_VARARGS;
    MethodVisitor mv = classVisitor.visitMethod(modifiers, node.getName(), methodType, signature, buildExceptions(node.getExceptions()));
    controller.setMethodVisitor(mv);

    visitAnnotations(node, mv);
    for (int i = 0, n = parameters.length; i < n; i += 1) {
        visitParameterAnnotations(parameters[i], i, mv);
    }

    // add parameter names to the MethodVisitor (jdk8+ only)
    if (Optional.ofNullable(controller.getClassNode().getCompileUnit())
            .orElseGet(context::getCompileUnit).getConfig().getParameters()) {
        for (Parameter parameter : parameters) {
            // TODO: handle ACC_SYNTHETIC for enum method parameters?
            mv.visitParameter(parameter.getName(), 0);
        }
    }

    if (controller.getClassNode().isAnnotationDefinition() && !node.isStaticConstructor()) {
        visitAnnotationDefault(node, mv);
    } else if (!node.isAbstract()) {
        Statement code = node.getCode();
        mv.visitCode();

        BytecodeInstruction instruction; // fast path for getters, setters, etc.
        if (code instanceof BytecodeSequence && (instruction = ((BytecodeSequence) code).getBytecodeInstruction()) != null) {
           instruction.visit(mv);
        } else {
            visitStdMethod(node, isConstructor, parameters, code);
        }

        try {
            mv.visitMaxs(0, 0);
        } catch (Exception e) {
            Writer writer = null;
            if (mv instanceof TraceMethodVisitor) {
                TraceMethodVisitor tracer = (TraceMethodVisitor) mv;
                writer = new StringBuilderWriter();
                PrintWriter p = new PrintWriter(writer);
                tracer.p.print(p);
                p.flush();
            }
            StringBuilder message = new StringBuilder(64);
            message.append("ASM reporting processing error for ");
            message.append(controller.getClassNode().toString()).append("#").append(node.getName());
            message.append(" with signature ").append(node.getTypeDescriptor());
            message.append(" in ").append(sourceFile).append(":").append(node.getLineNumber());
            if (writer != null) {
                message.append("\nLast known generated bytecode in last generated method or constructor:\n");
                message.append(writer);
            }
            throw new GroovyRuntimeException(message.toString(), e);
        }
    }
    mv.visitEnd();
}