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

The following examples show how to use org.codehaus.groovy.ast.expr.MethodCallExpression#visit() . 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: 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 2
Source File: BinaryExpressionHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void evaluateArrayAssignmentWithOperator(final String method, final BinaryExpression expression, final BinaryExpression leftBinExpr) {
    // e.g. x[a] += b
    // to avoid loading x and a twice we transform the expression to use
    // ExpressionAsVariableSlot
    // -> subscript=a, receiver=x, receiver[subscript]+b, =, receiver[subscript]
    // -> subscript=a, receiver=x, receiver#getAt(subscript)#plus(b), =, receiver#putAt(subscript)
    // -> subscript=a, receiver=x, receiver#putAt(subscript, receiver#getAt(subscript)#plus(b))
    // the result of x[a] += b is x[a]+b, thus:
    // -> subscript=a, receiver=x, receiver#putAt(subscript, ret=receiver#getAt(subscript)#plus(b)), ret
    ExpressionAsVariableSlot subscript = new ExpressionAsVariableSlot(controller, leftBinExpr.getRightExpression(), "subscript");
    ExpressionAsVariableSlot receiver  = new ExpressionAsVariableSlot(controller, leftBinExpr.getLeftExpression(), "receiver");
    MethodCallExpression getAt = callX(receiver, "getAt", args(subscript));
    MethodCallExpression operation = callX(getAt, method, expression.getRightExpression());
    ExpressionAsVariableSlot ret = new ExpressionAsVariableSlot(controller, operation, "ret");
    MethodCallExpression putAt = callX(receiver, "putAt", args(subscript, ret));

    AsmClassGenerator acg = controller.getAcg();
    putAt.visit(acg);
    OperandStack os = controller.getOperandStack();
    os.pop();
    os.load(ret.getType(), ret.getIndex());

    CompileStack compileStack = controller.getCompileStack();
    compileStack.removeVar(ret.getIndex());
    compileStack.removeVar(subscript.getIndex());
    compileStack.removeVar(receiver.getIndex());
}
 
Example 3
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 4
Source File: StaticTypesBinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
protected void assignToArray(final Expression parent, final Expression receiver, final Expression index, final Expression rhsValueLoader, final boolean safe) {
    ClassNode arrayType = controller.getTypeChooser().resolveType(receiver, controller.getClassNode());
    int operationType = getOperandType(arrayType.getComponentType());
    BinaryExpressionWriter bew = binExpWriter[operationType];

    if (bew.arraySet(true) && arrayType.isArray() && !safe) {
        super.assignToArray(parent, receiver, index, rhsValueLoader, safe);
    } else {
        /*
         * This code path is needed because ACG creates array access expressions
         */
        StaticTypeCheckingVisitor visitor = new StaticCompilationVisitor(controller.getSourceUnit(), controller.getClassNode());
        // GROOVY-6061
        if (rhsValueLoader instanceof VariableSlotLoader && parent instanceof BinaryExpression) {
            rhsValueLoader.putNodeMetaData(INFERRED_TYPE, controller.getTypeChooser().resolveType(parent, controller.getClassNode()));
        }
        // let's replace this assignment to a subscript operator with a method call
        // e.g. x[5] = 10
        // -> (x, [], 5), =, 10
        // -> methodCall(x, "putAt", [5, 10])
        MethodCallExpression call = callX(receiver, "putAt", args(index, rhsValueLoader));
        call.setSafe(safe);
        call.setSourcePosition(parent);
        visitor.visitMethodCallExpression(call);

        OperandStack operandStack = controller.getOperandStack();
        int height = operandStack.getStackLength();
        call.visit(controller.getAcg());
        operandStack.pop();
        operandStack.remove(operandStack.getStackLength() - height);

        // return value of assignment
        rhsValueLoader.visit(controller.getAcg());
    }
}
 
Example 5
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 6
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 7
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);
}
 
Example 8
Source File: StatementWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected void writeForInLoop(final ForStatement statement) {
    controller.getAcg().onLineNumber(statement, "visitForLoop");
    writeStatementLabel(statement);

    CompileStack compileStack = controller.getCompileStack();
    MethodVisitor mv = controller.getMethodVisitor();
    OperandStack operandStack = controller.getOperandStack();

    compileStack.pushLoop(statement.getVariableScope(), statement.getStatementLabels());

    // declare the loop counter
    BytecodeVariable variable = compileStack.defineVariable(statement.getVariable(), false);

    // then get the iterator and generate the loop control
    MethodCallExpression iterator = new MethodCallExpression(statement.getCollectionExpression(), "iterator", new ArgumentListExpression());
    iterator.visit(controller.getAcg());
    operandStack.doGroovyCast(ClassHelper.Iterator_TYPE);

    int iteratorIndex = compileStack.defineTemporaryVariable("iterator", ClassHelper.Iterator_TYPE, true);
    Label continueLabel = compileStack.getContinueLabel();
    Label breakLabel = compileStack.getBreakLabel();

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

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

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

    mv.visitJumpInsn(GOTO, continueLabel);
    mv.visitLabel(breakLabel);

    compileStack.removeVar(iteratorIndex);
    compileStack.pop();
}