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

The following examples show how to use org.codehaus.groovy.ast.MethodNode#setCode() . 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: NotYetImplementedASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    init(nodes, source);
    AnnotationNode anno = (AnnotationNode) nodes[0];
    MethodNode methodNode = (MethodNode) nodes[1];

    ClassNode exception = getMemberClassValue(anno, "exception");
    if (exception == null) {
        exception = DEFAULT_THROW_TYPE;
    }
    ConstructorNode cons = exception.getDeclaredConstructor(new Parameter[]{new Parameter(ClassHelper.STRING_TYPE, "dummy")});
    if (cons == null) {
        addError("Error during @NotYetImplemented processing: supplied exception " + exception.getNameWithoutPackage() + " doesn't have expected String constructor", methodNode);
    }

    if (methodNode.getCode() instanceof BlockStatement && !methodNode.getCode().isEmpty()) {
        // wrap code in try/catch with return for failure path followed by throws for success path

        TryCatchStatement tryCatchStatement = tryCatchS(methodNode.getCode());
        tryCatchStatement.addCatch(catchS(param(CATCH_TYPE, "ignore"), ReturnStatement.RETURN_NULL_OR_VOID));

        ThrowStatement throwStatement = throwS(ctorX(exception, args(constX("Method is marked with @NotYetImplemented but passes unexpectedly"))));

        methodNode.setCode(block(tryCatchStatement, throwStatement));
    }
}
 
Example 2
Source File: NullCheckASTTransformation.java    From groovy with Apache License 2.0 6 votes vote down vote up
private void adjustMethod(MethodNode mn, boolean includeGenerated) {
    BlockStatement newCode = getCodeAsBlock(mn);
    if (mn.getParameters().length == 0) return;
    boolean generated = isGenerated(mn);
    int startingIndex = 0;
    if (!includeGenerated && generated) return;
    if (isMarkedAsProcessed(mn)) return;
    if (mn instanceof ConstructorNode) {
        // some transform has been here already and we assume it knows what it is doing
        if (mn.getFirstStatement() instanceof BytecodeSequence) return;
        // ignore any constructors calling this(...) or super(...)
        ConstructorCallExpression cce = ConstructorNodeUtils.getFirstIfSpecialConstructorCall(mn.getCode());
        if (cce != null) {
            if (generated) {
                return;
            } else {
                startingIndex = 1; // skip over this/super() call
            }
        }
    }
    for (Parameter p : mn.getParameters()) {
        if (ClassHelper.isPrimitiveType(p.getType())) continue;
        newCode.getStatements().add(startingIndex, ifS(isNullX(varX(p)), makeThrowStmt(p.getName())));
    }
    mn.setCode(newCode);
}
 
Example 3
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 4
Source File: ReadWriteLockASTTransformation.java    From groovy with Apache License 2.0 5 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];
    final boolean isWriteLock;
    if (READ_LOCK_TYPE.equals(node.getClassNode())) {
        isWriteLock = false;
    } else if (WRITE_LOCK_TYPE.equals(node.getClassNode())) {
        isWriteLock = true;
    } else {
        throw new GroovyBugError("Internal error: expecting [" + READ_LOCK_TYPE.getName() + ", " + WRITE_LOCK_TYPE.getName() + "]" + " but got: " + node.getClassNode().getName());
    }

    String myTypeName = "@" + node.getClassNode().getNameWithoutPackage();

    String value = getMemberStringValue(node, "value");

    if (parent instanceof MethodNode) {
        MethodNode mNode = (MethodNode) parent;
        ClassNode cNode = mNode.getDeclaringClass();
        FieldNode lockExpr = determineLock(value, cNode, mNode.isStatic(), myTypeName);
        if (lockExpr == null) return;

        // get lock type
        final MethodCallExpression lockType = callX(varX(lockExpr), isWriteLock ? "writeLock" : "readLock");
        lockType.setImplicitThis(false);

        MethodCallExpression acquireLock = callX(lockType, "lock");
        acquireLock.setImplicitThis(false);

        MethodCallExpression releaseLock = callX(lockType, "unlock");
        releaseLock.setImplicitThis(false);

        Statement originalCode = mNode.getCode();

        mNode.setCode(block(
                stmt(acquireLock),
                new TryCatchStatement(originalCode, stmt(releaseLock))));
    }
}
 
Example 5
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 6
Source File: ReturnAdder.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Adds return statements to given method whenever an implicit return is detected.
 */
public void visitMethod(final MethodNode node) {
    if (!node.isVoidMethod()) {
        Statement code = node.getCode();
        if (code != null) { // happens with @interface methods
            code = addReturnsIfNeeded(code, node.getVariableScope());
            if (doAdd) node.setCode(code);
        }
    }
}
 
Example 7
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 8
Source File: BindableASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void wrapSetterMethod(ClassNode classNode, String propertyName) {
    String getterName = "get" + capitalize(propertyName);
    MethodNode setter = classNode.getSetterMethod(getSetterName(propertyName));

    if (setter != null) {
        // Get the existing code block
        Statement code = setter.getCode();

        Expression oldValue = localVarX("$oldValue");
        Expression newValue = localVarX("$newValue");
        BlockStatement block = new BlockStatement();

        // create a local variable to hold the old value from the getter
        block.addStatement(declS(oldValue, callThisX(getterName)));

        // call the existing block, which will presumably set the value properly
        block.addStatement(code);

        // get the new value to emit in the event
        block.addStatement(declS(newValue, callThisX(getterName)));

        // add the firePropertyChange method call
        block.addStatement(stmt(callThisX("firePropertyChange", args(constX(propertyName), oldValue, newValue))));

        // replace the existing code block with our new one
        setter.setCode(block);
    }
}
 
Example 9
Source File: VetoableASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Wrap an existing setter.
 */
private static void wrapSetterMethod(ClassNode classNode, boolean bindable, String propertyName) {
    String getterName = "get" + capitalize(propertyName);
    MethodNode setter = classNode.getSetterMethod(getSetterName(propertyName));

    if (setter != null) {
        // Get the existing code block
        Statement code = setter.getCode();

        Expression oldValue = localVarX("$oldValue");
        Expression newValue = localVarX("$newValue");
        Expression proposedValue = varX(setter.getParameters()[0].getName());
        BlockStatement block = new BlockStatement();

        // create a local variable to hold the old value from the getter
        block.addStatement(declS(oldValue, callThisX(getterName)));

        // add the fireVetoableChange method call
        block.addStatement(stmt(callThisX("fireVetoableChange", args(
                constX(propertyName), oldValue, proposedValue))));

        // call the existing block, which will presumably set the value properly
        block.addStatement(code);

        if (bindable) {
            // get the new value to emit in the event
            block.addStatement(declS(newValue, callThisX(getterName)));

            // add the firePropertyChange method call
            block.addStatement(stmt(callThisX("firePropertyChange", args(constX(propertyName), oldValue, newValue))));
        }

        // replace the existing code block with our new one
        setter.setCode(block);
    }
}
 
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: Java8.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static void setMethodDefaultValue(MethodNode mn, Method m) {
    ConstantExpression cExp = new ConstantExpression(m.getDefaultValue());
    mn.setCode(new ReturnStatement(cExp));
    mn.setAnnotationDefault(true);
}