Java Code Examples for org.codehaus.groovy.ast.expr.MethodCallExpression#setMethodTarget()

The following examples show how to use org.codehaus.groovy.ast.expr.MethodCallExpression#setMethodTarget() . 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: 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 2
Source File: StaticTypesBinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
protected void writePostOrPrefixMethod(final int op, final String method, final Expression expression, final Expression orig) {
    MethodNode mn = orig.getNodeMetaData(DIRECT_METHOD_CALL_TARGET);
    if (mn != null) {
        controller.getOperandStack().pop();
        MethodCallExpression call = callX(expression, method);
        call.setMethodTarget(mn);
        call.visit(controller.getAcg());
        return;
    }

    ClassNode top = controller.getOperandStack().getTopOperand();
    if (ClassHelper.isPrimitiveType(top) && (ClassHelper.isNumberType(top) || char_TYPE.equals(top))) {
        MethodVisitor mv = controller.getMethodVisitor();
        visitInsnByType(top, mv, ICONST_1, LCONST_1, FCONST_1, DCONST_1);
        if ("next".equals(method)) {
            visitInsnByType(top, mv, IADD, LADD, FADD, DADD);
        } else {
            visitInsnByType(top, mv, ISUB, LSUB, FSUB, DSUB);
        }
        return;
    }

    super.writePostOrPrefixMethod(op, method, expression, orig);
}
 
Example 3
Source File: ResolveVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected Expression transformMethodCallExpression(final MethodCallExpression mce) {
    Expression args = transform(mce.getArguments());
    Expression method = transform(mce.getMethod());
    Expression object = transform(mce.getObjectExpression());

    resolveGenericsTypes(mce.getGenericsTypes());

    MethodCallExpression ret = new MethodCallExpression(object, method, args);
    ret.setGenericsTypes(mce.getGenericsTypes());
    ret.setMethodTarget(mce.getMethodTarget());
    ret.setImplicitThis(mce.isImplicitThis());
    ret.setSpreadSafe(mce.isSpreadSafe());
    ret.setSafe(mce.isSafe());
    return ret;
}
 
Example 4
Source File: BinaryExpressionTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static Expression convertInOperatorToTernary(final BinaryExpression bin, final Expression rightExpression, final Expression leftExpression) {
    MethodCallExpression call = callX(rightExpression, "isCase", leftExpression);
    call.setMethodTarget(bin.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET));
    call.setSourcePosition(bin);
    call.copyNodeMetaData(bin);
    Expression tExp = ternaryX(
            boolX(binX(rightExpression, Token.newSymbol("==", -1, -1), nullX())),
            binX(leftExpression, Token.newSymbol("==", -1, -1), nullX()),
            call
    );
    return tExp;
}
 
Example 5
Source File: StaticMethodCallExpressionTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
Expression transformStaticMethodCallExpression(final StaticMethodCallExpression orig) {
    MethodNode target = (MethodNode) orig.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET);
    if (target != null) {
        MethodCallExpression call = new MethodCallExpression(
                new ClassExpression(orig.getOwnerType()),
                orig.getMethod(),
                orig.getArguments()
        );
        call.setMethodTarget(target);
        call.setSourcePosition(orig);
        call.copyNodeMetaData(orig);
        return transformer.transform(call);
    }
    return transformer.superTransform(orig);
}
 
Example 6
Source File: StaticCompilationVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitMethodCallExpression(final MethodCallExpression call) {
    super.visitMethodCallExpression(call);

    MethodNode target = call.getNodeMetaData(DIRECT_METHOD_CALL_TARGET);
    if (target != null) {
        call.setMethodTarget(target);
        memorizeInitialExpressions(target);
    }

    if (call.getMethodTarget() == null && call.getLineNumber() > 0) {
        addError("Target method for method call expression hasn't been set", call);
    }
}
 
Example 7
Source File: StaticInvocationWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean makeDirectCall(final Expression origin, final Expression receiver, final Expression message, final Expression arguments, final MethodCallerMultiAdapter adapter, final boolean implicitThis, final boolean containsSpreadExpression) {
    if (origin instanceof MethodCallExpression && isSuperExpression(receiver)) {
        ClassNode superClass = receiver.getNodeMetaData(StaticCompilationMetadataKeys.PROPERTY_OWNER);
        if (superClass != null && !controller.getCompileStack().isLHS()) {
            // GROOVY-7300
            MethodCallExpression mce = (MethodCallExpression) origin;
            MethodNode node = superClass.getDeclaredMethod(mce.getMethodAsString(), Parameter.EMPTY_ARRAY);
            mce.setMethodTarget(node);
        }
    }
    return super.makeDirectCall(origin, receiver, message, arguments, adapter, implicitThis, containsSpreadExpression);
}
 
Example 8
Source File: StaticTypesBinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean makeSetPrivateFieldWithBridgeMethod(final Expression receiver, final ClassNode receiverType, final String fieldName, final Expression arguments, final boolean safe, final boolean spreadSafe, final boolean implicitThis) {
    FieldNode field = receiverType.getField(fieldName);
    ClassNode outerClass = receiverType.getOuterClass();
    if (field == null && implicitThis && outerClass != null && !receiverType.isStaticClass()) {
        Expression pexp;
        if (controller.isInGeneratedFunction()) {
            MethodCallExpression mce = callThisX("getThisObject");
            mce.setImplicitThis(true);
            mce.setMethodTarget(CLOSURE_GETTHISOBJECT_METHOD);
            mce.putNodeMetaData(INFERRED_TYPE, controller.getOutermostClass());
            pexp = castX(controller.getOutermostClass(), mce);
        } else {
            pexp = propX(classX(outerClass), "this");
            ((PropertyExpression) pexp).setImplicitThis(true);
        }
        pexp.putNodeMetaData(INFERRED_TYPE, outerClass);
        pexp.setSourcePosition(receiver);
        return makeSetPrivateFieldWithBridgeMethod(pexp, outerClass, fieldName, arguments, safe, spreadSafe, true);
    }
    ClassNode classNode = controller.getClassNode();
    if (field != null && field.isPrivate() && !receiverType.equals(classNode)
            && (StaticInvocationWriter.isPrivateBridgeMethodsCallAllowed(receiverType, classNode)
                || StaticInvocationWriter.isPrivateBridgeMethodsCallAllowed(classNode,receiverType))) {
        Map<String, MethodNode> mutators = receiverType.redirect().getNodeMetaData(StaticCompilationMetadataKeys.PRIVATE_FIELDS_MUTATORS);
        if (mutators != null) {
            MethodNode methodNode = mutators.get(fieldName);
            if (methodNode != null) {
                MethodCallExpression call = callX(receiver, methodNode.getName(), args(field.isStatic() ? nullX() : receiver, arguments));
                call.setImplicitThis(implicitThis);
                call.setMethodTarget(methodNode);
                call.setSafe(safe);
                call.setSpreadSafe(spreadSafe);
                call.visit(controller.getAcg());
                return true;
            }
        }
    }
    return false;
}
 
Example 9
Source File: StaticTypesCallSiteWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void makeDynamicGetProperty(final Expression receiver, final String propertyName, final boolean safe) {
    MethodNode target = safe ? INVOKERHELPER_GETPROPERTYSAFE_METHOD : INVOKERHELPER_GETPROPERTY_METHOD;
    MethodCallExpression call = callX(
            classX(INVOKERHELPER_TYPE),
            target.getName(),
            args(receiver, constX(propertyName))
    );
    call.setImplicitThis(false);
    call.setMethodTarget(target);
    call.setSafe(false);
    call.visit(controller.getAcg());
}
 
Example 10
Source File: StaticTypesCallSiteWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void makeGroovyObjectGetPropertySite(final Expression receiver, final String propertyName, final boolean safe, final boolean implicitThis) {
    ClassNode receiverType = controller.getClassNode();
    if (!AsmClassGenerator.isThisExpression(receiver) || controller.isInGeneratedFunction()) {
        receiverType = controller.getTypeChooser().resolveType(receiver, receiverType);
    }

    String property = propertyName;
    if (implicitThis && controller.getInvocationWriter() instanceof StaticInvocationWriter) {
        Expression currentCall = ((StaticInvocationWriter) controller.getInvocationWriter()).getCurrentCall();
        if (currentCall != null && currentCall.getNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER) != null) {
            property = currentCall.getNodeMetaData(StaticTypesMarker.IMPLICIT_RECEIVER);
            String[] props = property.split("\\.");
            BytecodeExpression thisLoader = bytecodeX(CLOSURE_TYPE, mv -> mv.visitVarInsn(ALOAD, 0));
            PropertyExpression pexp = propX(thisLoader, constX(props[0]), safe);
            for (int i = 1, n = props.length; i < n; i += 1) {
                pexp.putNodeMetaData(StaticTypesMarker.INFERRED_TYPE, CLOSURE_TYPE);
                pexp = propX(pexp, props[i]);
            }
            pexp.visit(controller.getAcg());
            return;
        }
    }

    if (makeGetPropertyWithGetter(receiver, receiverType, property, safe, implicitThis)) return;
    if (makeGetPrivateFieldWithBridgeMethod(receiver, receiverType, property, safe, implicitThis)) return;
    if (makeGetField(receiver, receiverType, property, safe, implicitThis)) return;

    MethodCallExpression call = callX(receiver, "getProperty", args(constX(property)));
    call.setImplicitThis(implicitThis);
    call.setMethodTarget(GROOVYOBJECT_GETPROPERTY_METHOD);
    call.setSafe(safe);
    call.visit(controller.getAcg());
}
 
Example 11
Source File: StaticTypesClosureWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void createDirectCallMethod(final ClassNode closureClass, final MethodNode doCallMethod) {
    // in case there is no "call" method on the closure, we can create a "fast invocation" paths
    // to avoid going through ClosureMetaClass by call(Object...) method

    // we can't have a specialized version of call(Object...) because the dispatch logic in ClosureMetaClass
    // is too complex!

    // call(Object)
    Parameter args = new Parameter(ClassHelper.OBJECT_TYPE, "args");
    MethodCallExpression doCall1arg = new MethodCallExpression(
            new VariableExpression("this", closureClass),
            "doCall",
            new ArgumentListExpression(new VariableExpression(args))
    );
    doCall1arg.setImplicitThis(true);
    doCall1arg.setMethodTarget(doCallMethod);
    closureClass.addMethod(
            new MethodNode("call",
                    Opcodes.ACC_PUBLIC,
                    ClassHelper.OBJECT_TYPE,
                    new Parameter[]{args},
                    ClassNode.EMPTY_ARRAY,
                    new ReturnStatement(doCall1arg)));

    // call()
    MethodCallExpression doCallNoArgs = new MethodCallExpression(new VariableExpression("this", closureClass), "doCall", new ArgumentListExpression(new ConstantExpression(null)));
    doCallNoArgs.setImplicitThis(true);
    doCallNoArgs.setMethodTarget(doCallMethod);
    closureClass.addMethod(
            new MethodNode("call",
                    Opcodes.ACC_PUBLIC,
                    ClassHelper.OBJECT_TYPE,
                    Parameter.EMPTY_ARRAY,
                    ClassNode.EMPTY_ARRAY,
                    new ReturnStatement(doCallNoArgs)));
}
 
Example 12
Source File: StaticTypesClosureWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitMethodCallExpression(final MethodCallExpression call) {
    super.visitMethodCallExpression(call);
    MethodNode mn = call.getMethodTarget();
    if (mn == null) {
        call.setMethodTarget(doCallMethod);
    }
}
 
Example 13
Source File: SuperCallTraitTransformer.java    From groovy with Apache License 2.0 4 votes vote down vote up
private Expression transformBinaryExpression(final BinaryExpression exp) {
    Expression trn = super.transform(exp);
    if (trn instanceof BinaryExpression) {
        BinaryExpression bin = (BinaryExpression) trn;
        Expression leftExpression = bin.getLeftExpression();
        if (bin.getOperation().getType() == Types.EQUAL && leftExpression instanceof PropertyExpression) {
            ClassNode traitReceiver = null;
            PropertyExpression leftPropertyExpression = (PropertyExpression) leftExpression;
            if (isTraitSuperPropertyExpression(leftPropertyExpression.getObjectExpression())) {
                PropertyExpression pexp = (PropertyExpression) leftPropertyExpression.getObjectExpression();
                traitReceiver = pexp.getObjectExpression().getType();
            }
            if (traitReceiver!=null) {
                // A.super.foo = ...
                TraitHelpersTuple helpers = Traits.findHelpers(traitReceiver);
                ClassNode helper = helpers.getHelper();
                String setterName = MetaProperty.getSetterName(leftPropertyExpression.getPropertyAsString());
                List<MethodNode> methods = helper.getMethods(setterName);
                for (MethodNode method : methods) {
                    Parameter[] parameters = method.getParameters();
                    if (parameters.length==2 && parameters[0].getType().equals(traitReceiver)) {
                        ArgumentListExpression args = new ArgumentListExpression(
                                new VariableExpression("this"),
                                transform(exp.getRightExpression())
                        );
                        MethodCallExpression setterCall = new MethodCallExpression(
                                new ClassExpression(helper),
                                setterName,
                                args
                        );
                        setterCall.setMethodTarget(method);
                        setterCall.setImplicitThis(false);
                        return setterCall;
                    }
                }
                return bin;
            }
        }
    }
    return trn;
}
 
Example 14
Source File: StaticTypesBinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void transformSpreadOnLHS(final BinaryExpression expression) {
    PropertyExpression spreadExpression = (PropertyExpression) expression.getLeftExpression();
    Expression receiver = spreadExpression.getObjectExpression();

    int counter = labelCounter.incrementAndGet();
    CompileStack compileStack = controller.getCompileStack();
    OperandStack operandStack = controller.getOperandStack();

    // create an empty arraylist
    VariableExpression result = varX(this.getClass().getSimpleName() + "$spreadresult" + counter, ARRAYLIST_CLASSNODE);
    ConstructorCallExpression newArrayList = ctorX(ARRAYLIST_CLASSNODE);
    newArrayList.setNodeMetaData(DIRECT_METHOD_CALL_TARGET, ARRAYLIST_CONSTRUCTOR);
    Expression decl = declX(result, newArrayList);
    decl.visit(controller.getAcg());
    // if (receiver != null)
    receiver.visit(controller.getAcg());
    Label ifnull = compileStack.createLocalLabel("ifnull_" + counter);
    MethodVisitor mv = controller.getMethodVisitor();
    mv.visitJumpInsn(IFNULL, ifnull);
    operandStack.remove(1); // receiver consumed by if()
    Label nonull = compileStack.createLocalLabel("nonull_" + counter);
    mv.visitLabel(nonull);
    ClassNode componentType = StaticTypeCheckingVisitor.inferLoopElementType(
            controller.getTypeChooser().resolveType(receiver, controller.getClassNode()));
    Parameter iterator = new Parameter(componentType, "for$it$" + counter);
    VariableExpression iteratorAsVar = varX(iterator);
    PropertyExpression pexp = spreadExpression instanceof AttributeExpression
        ? new AttributeExpression(iteratorAsVar, spreadExpression.getProperty(), true)
        : new PropertyExpression(iteratorAsVar, spreadExpression.getProperty(), true);
    pexp.setImplicitThis(spreadExpression.isImplicitThis());
    pexp.setSourcePosition(spreadExpression);
    BinaryExpression assignment = binX(pexp, expression.getOperation(), expression.getRightExpression());
    MethodCallExpression add = callX(result, "add", assignment);
    add.setMethodTarget(ARRAYLIST_ADD_METHOD);
    // for (e in receiver) { result.add(e?.method(arguments) }
    ForStatement stmt = new ForStatement(
            iterator,
            receiver,
            stmt(add)
    );
    stmt.visit(controller.getAcg());
    // else { empty list }
    mv.visitLabel(ifnull);
    // end of if/else
    // return result list
    result.visit(controller.getAcg());
}
 
Example 15
Source File: StaticTypesStatementWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void writeIteratorBasedForEachLoop(
        CompileStack compileStack,
        OperandStack operandStack,
        MethodVisitor mv,
        ForStatement loop,
        Expression collectionExpression,
        ClassNode collectionType,
        Parameter loopVariable) {
    // Declare the loop counter.
    BytecodeVariable variable = compileStack.defineVariable(loopVariable, false);

    if (StaticTypeCheckingSupport.implementsInterfaceOrIsSubclassOf(collectionType, ITERABLE_CLASSNODE)) {
        MethodCallExpression iterator = new MethodCallExpression(collectionExpression, "iterator", new ArgumentListExpression());
        iterator.setMethodTarget(collectionType.getMethod("iterator", Parameter.EMPTY_ARRAY));
        iterator.setImplicitThis(false);
        iterator.visit(controller.getAcg());
    } else {
        collectionExpression.visit(controller.getAcg());
        mv.visitMethodInsn(INVOKESTATIC, "org/codehaus/groovy/runtime/DefaultGroovyMethods", "iterator", "(Ljava/lang/Object;)Ljava/util/Iterator;", false);
        operandStack.replace(ClassHelper.Iterator_TYPE);
    }

    // Then get the iterator and generate the loop control

    int iteratorIdx = compileStack.defineTemporaryVariable("iterator", ClassHelper.Iterator_TYPE, true);

    Label continueLabel = compileStack.getContinueLabel();
    Label breakLabel = compileStack.getBreakLabel();

    mv.visitLabel(continueLabel);
    mv.visitVarInsn(ALOAD, iteratorIdx);
    writeIteratorHasNext(mv);
    // note: ifeq tests for ==0, a boolean is 0 if it is false
    mv.visitJumpInsn(IFEQ, breakLabel);

    mv.visitVarInsn(ALOAD, iteratorIdx);
    writeIteratorNext(mv);
    operandStack.push(ClassHelper.OBJECT_TYPE);
    operandStack.storeVar(variable);

    // Generate the loop body
    loop.getLoopBlock().visit(controller.getAcg());

    mv.visitJumpInsn(GOTO, continueLabel);
    mv.visitLabel(breakLabel);
    compileStack.removeVar(iteratorIdx);
}