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

The following examples show how to use org.codehaus.groovy.ast.expr.Expression#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: SqlWhereVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void visitBinaryExpression(BinaryExpression expression) {
    Expression left = expression.getLeftExpression();
    Expression right = expression.getRightExpression();
    boolean leaf = (right instanceof ConstantExpression || left instanceof ConstantExpression);

    if (!leaf) buffer.append("(");
    left.visit(this);
    buffer.append(" ");

    Token token = expression.getOperation();
    buffer.append(tokenAsSql(token));

    buffer.append(" ");
    right.visit(this);
    if (!leaf) buffer.append(")");
}
 
Example 2
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 6 votes vote down vote up
void visitTupleExpression(final TupleExpression expression, final boolean useWrapper) {
    MethodVisitor mv = controller.getMethodVisitor();
    int size = expression.getExpressions().size();

    BytecodeHelper.pushConstant(mv, size);
    mv.visitTypeInsn(ANEWARRAY, "java/lang/Object");

    for (int i = 0; i < size; i += 1) {
        mv.visitInsn(DUP);
        BytecodeHelper.pushConstant(mv, i);
        Expression argument = expression.getExpression(i);
        argument.visit(this);
        controller.getOperandStack().box();
        if (useWrapper && argument instanceof CastExpression) loadWrapper(argument);

        mv.visitInsn(AASTORE);
        controller.getOperandStack().remove(1);
    }
}
 
Example 3
Source File: StaticTypesUnaryExpressionHelper.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void writeNotExpression(final NotExpression expression) {
    TypeChooser typeChooser = controller.getTypeChooser();
    Expression subExpression = expression.getExpression();
    ClassNode classNode = controller.getClassNode();
    if (typeChooser.resolveType(subExpression, classNode) == boolean_TYPE) {
        subExpression.visit(controller.getAcg());
        controller.getOperandStack().doGroovyCast(boolean_TYPE);
        BytecodeExpression bytecodeExpression = bytecodeX(mv -> {
            Label ne = new Label();
            mv.visitJumpInsn(IFNE, ne);
            mv.visitInsn(ICONST_1);
            Label out = new Label();
            mv.visitJumpInsn(GOTO, out);
            mv.visitLabel(ne);
            mv.visitInsn(ICONST_0);
            mv.visitLabel(out);
        });
        bytecodeExpression.visit(controller.getAcg());
        controller.getOperandStack().remove(1);
        return;
    }
    super.writeNotExpression(expression);
}
 
Example 4
Source File: InvokeDynamicWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void makeIndyCall(MethodCallerMultiAdapter adapter, Expression receiver, boolean implicitThis, boolean safe, String methodName, Expression arguments) {
    OperandStack operandStack = controller.getOperandStack();

    StringBuilder sig = new StringBuilder(prepareIndyCall(receiver, implicitThis));

    // load arguments
    int numberOfArguments = 1;
    ArgumentListExpression ae = makeArgumentList(arguments);
    boolean containsSpreadExpression = AsmClassGenerator.containsSpreadExpression(arguments);
    AsmClassGenerator acg = controller.getAcg();
    if (containsSpreadExpression) {
        acg.despreadList(ae.getExpressions(), true);
        sig.append(getTypeDescription(Object[].class));
    } else {
        for (Expression arg : ae.getExpressions()) {
            arg.visit(acg);
            if (arg instanceof CastExpression) {
                operandStack.box();
                acg.loadWrapper(arg);
                sig.append(getTypeDescription(Wrapper.class));
            } else {
                sig.append(getTypeDescription(operandStack.getTopOperand()));
            }
            numberOfArguments++;
        }
    }

    sig.append(")Ljava/lang/Object;");
    String callSiteName = METHOD.getCallSiteName();
    if (adapter == null) callSiteName = INIT.getCallSiteName();
    int flags = getMethodCallFlags(adapter, safe, containsSpreadExpression);
    finishIndyCall(BSM, callSiteName, sig.toString(), numberOfArguments, methodName, flags);
}
 
Example 5
Source File: SecureASTCustomizer.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitMethodCallExpression(final MethodCallExpression call) {
    assertExpressionAuthorized(call);
    Expression receiver = call.getObjectExpression();
    final String typeName = receiver.getType().getName();
    if (allowedReceivers != null && !allowedReceivers.contains(typeName)) {
        throw new SecurityException("Method calls not allowed on [" + typeName + "]");
    } else if (disallowedReceivers != null && disallowedReceivers.contains(typeName)) {
        throw new SecurityException("Method calls not allowed on [" + typeName + "]");
    }
    receiver.visit(this);
    final Expression method = call.getMethod();
    checkConstantTypeIfNotMethodNameOrProperty(method);
    call.getArguments().visit(this);
}
 
Example 6
Source File: StaticTypesStatementWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void writeEnumerationBasedForEachLoop(
        CompileStack compileStack,
        OperandStack operandStack,
        MethodVisitor mv,
        ForStatement loop,
        Expression collectionExpression,
        ClassNode collectionType,
        Parameter loopVariable) {
    // Declare the loop counter.
    BytecodeVariable variable = compileStack.defineVariable(loopVariable, false);

    collectionExpression.visit(controller.getAcg());

    // Then get the iterator and generate the loop control

    int enumIdx = compileStack.defineTemporaryVariable("$enum", ENUMERATION_CLASSNODE, true);

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

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

    mv.visitVarInsn(ALOAD, enumIdx);
    ENUMERATION_NEXT_METHOD.call(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);

}
 
Example 7
Source File: PathFinderVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void visitPropertyExpression(PropertyExpression node) {

    // XXX PropertyExpression has wrong offsets, e.g. 4-4 for 'this.field1 = 77'
    // and was never added to path,
    // therefore let's check if its children are wraping given position
    // and add it then

    Expression objectExpression = node.getObjectExpression();
    Expression property = node.getProperty();

    if (isInside(node, line, column, false)) {
        path.add(node);
    } else {
        boolean nodeAdded = false;
        if (isInside(objectExpression, line, column, false)) {
            path.add(node);
            nodeAdded = true;
        }
        if (isInside(property, line, column, false)) {
            if (!nodeAdded) {
                path.add(node);
            }
        }
    }

    objectExpression.visit(this);
    property.visit(this);
}
 
Example 8
Source File: MethodPointerExpressionWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void writeMethodPointerExpression(MethodPointerExpression expression) {
    Expression subExpression = expression.getExpression();
    subExpression.visit(controller.getAcg());
    controller.getOperandStack().box();
    controller.getOperandStack().pushDynamicName(expression.getMethodName());
    getMethodPointer.call(controller.getMethodVisitor());
    controller.getOperandStack().replace(ClassHelper.CLOSURE_TYPE,2);
}
 
Example 9
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 10
Source File: BinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
protected void assignToArray(final Expression orig, final Expression receiver, final Expression index, final Expression rhsValueLoader, final boolean safe) {
    ClassNode current = controller.getClassNode();
    ClassNode arrayType = controller.getTypeChooser().resolveType(receiver, current);
    ClassNode arrayComponentType = arrayType.getComponentType();
    int operationType = getOperandType(arrayComponentType);
    BinaryExpressionWriter bew = binExpWriter[operationType];
    AsmClassGenerator acg = controller.getAcg();

    if (bew.arraySet(true) && arrayType.isArray() && !safe) {
        OperandStack operandStack   =   controller.getOperandStack();

        // load the array
        receiver.visit(acg);
        operandStack.doGroovyCast(arrayType);

        // load index
        index.visit(acg);
        operandStack.doGroovyCast(int_TYPE);

        // load rhs
        rhsValueLoader.visit(acg);
        operandStack.doGroovyCast(arrayComponentType);

        // store value in array
        bew.arraySet(false);

        // load return value && correct operand stack stack
        operandStack.remove(3);
        rhsValueLoader.visit(acg);
    } else {
        super.assignToArray(orig, receiver, index, rhsValueLoader, safe);
    }
}
 
Example 11
Source File: ClassCodeVisitorSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitProperty(PropertyNode node) {
    visitAnnotations(node);
    Statement statement = node.getGetterBlock();
    visitClassCodeContainer(statement);

    statement = node.getSetterBlock();
    visitClassCodeContainer(statement);

    Expression init = node.getInitialExpression();
    if (init != null) init.visit(this);
}
 
Example 12
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 5 votes vote down vote up
private boolean checkStaticOuterField(final PropertyExpression pexp, final String propertyName) {
    for (final ClassNode outer : controller.getClassNode().getOuterClasses()) {
        FieldNode field = outer.getDeclaredField(propertyName);
        if (field != null) {
            if (!field.isStatic()) break;

            Expression outerClass = classX(outer);
            outerClass.setNodeMetaData(PROPERTY_OWNER, outer);
            outerClass.setSourcePosition(pexp.getObjectExpression());

            Expression outerField = attrX(outerClass, pexp.getProperty());
            outerField.setSourcePosition(pexp);
            outerField.visit(this);
            return true;
        } else {
            field = outer.getField(propertyName); // checks supers
            if (field != null && !field.isPrivate() && (field.isPublic() || field.isProtected()
                    || Objects.equals(field.getDeclaringClass().getPackageName(), outer.getPackageName()))) {
                if (!field.isStatic()) break;

                Expression upperClass = classX(field.getDeclaringClass());
                upperClass.setNodeMetaData(PROPERTY_OWNER, field.getDeclaringClass());
                upperClass.setSourcePosition(pexp.getObjectExpression());

                Expression upperField = propX(upperClass, pexp.getProperty());
                upperField.setSourcePosition(pexp);
                upperField.visit(this);
                return true;
            }
        }
    }
    return false;
}
 
Example 13
Source File: StatementWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void writeReturn(final ReturnStatement statement) {
    controller.getAcg().onLineNumber(statement, "visitReturnStatement");
    writeStatementLabel(statement);
    MethodVisitor mv = controller.getMethodVisitor();
    OperandStack operandStack = controller.getOperandStack();
    ClassNode returnType = controller.getReturnType();

    if (returnType == ClassHelper.VOID_TYPE) {
        if (!(statement.isReturningNullOrVoid())) {
            //TODO: move to Verifier
            controller.getAcg().throwException("Cannot use return statement with an expression on a method that returns void");
        }
        controller.getCompileStack().applyBlockRecorder();
        mv.visitInsn(RETURN);
        return;
    }

    Expression expression = statement.getExpression();
    expression.visit(controller.getAcg());

    operandStack.doGroovyCast(returnType);

    if (controller.getCompileStack().hasBlockRecorder()) {
        ClassNode type = operandStack.getTopOperand();
        int returnValueIdx = controller.getCompileStack().defineTemporaryVariable("returnValue", returnType, true);
        controller.getCompileStack().applyBlockRecorder();
        operandStack.load(type, returnValueIdx);
        controller.getCompileStack().removeVar(returnValueIdx);
    }

    BytecodeHelper.doReturn(mv, returnType);
    operandStack.remove(1);
}
 
Example 14
Source File: BinaryExpressionHelper.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void evaluateCompareExpression(final MethodCaller compareMethod, final BinaryExpression expression) {
    ClassNode classNode = controller.getClassNode();
    Expression leftExp = expression.getLeftExpression();
    Expression rightExp = expression.getRightExpression();
    ClassNode leftType = controller.getTypeChooser().resolveType(leftExp, classNode);
    ClassNode rightType = controller.getTypeChooser().resolveType(rightExp, classNode);

    boolean done = false;
    if (ClassHelper.isPrimitiveType(leftType) && ClassHelper.isPrimitiveType(rightType)) {
        BinaryExpressionMultiTypeDispatcher helper = new BinaryExpressionMultiTypeDispatcher(controller);
        done = helper.doPrimitiveCompare(leftType, rightType, expression);
    }
    if (!done) {
        AsmClassGenerator acg = controller.getAcg();
        OperandStack operandStack = controller.getOperandStack();

        leftExp.visit(acg);
        operandStack.box();
        rightExp.visit(acg);
        operandStack.box();

        compareMethod.call(controller.getMethodVisitor());
        ClassNode resType = ClassHelper.boolean_TYPE;
        if (compareMethod == findRegexMethod) {
            resType = ClassHelper.OBJECT_TYPE;
        }
        operandStack.replace(resType, 2);
    }
}
 
Example 15
Source File: VariableScopeVisitor.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitConstructorCallExpression(final ConstructorCallExpression expression) {
    boolean oldInSpecialCtorFlag = inSpecialConstructorCall;
    inSpecialConstructorCall |= expression.isSpecialCall();
    super.visitConstructorCallExpression(expression);
    inSpecialConstructorCall = oldInSpecialCtorFlag;

    if (!expression.isUsingAnonymousInnerClass()) return;

    pushState();
    InnerClassNode innerClass = (InnerClassNode) expression.getType();
    innerClass.setVariableScope(currentScope);
    currentScope.setClassScope(innerClass);
    currentScope.setInStaticContext(false);
    for (MethodNode method : innerClass.getMethods()) {
        Parameter[] parameters = method.getParameters();
        if (parameters.length == 0) {
            parameters = null; // null means no implicit "it"
        }
        visitClosureExpression(new ClosureExpression(parameters, method.getCode()));
    }

    for (FieldNode field : innerClass.getFields()) {
        Expression initExpression = field.getInitialExpression();
        pushState(field.isStatic());
        if (initExpression != null) {
            if (initExpression.isSynthetic() && initExpression instanceof VariableExpression
                    && ((VariableExpression) initExpression).getAccessedVariable() instanceof Parameter) {
                // GROOVY-6834: accessing a parameter which is not yet seen in scope
                popState();
                continue;
            }
            initExpression.visit(this);
        }
        popState();
    }

    for (Statement initStatement : innerClass.getObjectInitializerStatements()) {
        initStatement.visit(this);
    }
    markClosureSharedVariables();
    popState();
}
 
Example 16
Source File: BinaryExpressionMultiTypeDispatcher.java    From groovy with Apache License 2.0 4 votes vote down vote up
private boolean doAssignmentToArray(final BinaryExpression binExp) {
    if (!isAssignmentToArray(binExp)) return false;
    // we need to handle only assignment to arrays combined with an operation
    // special here. e.g x[a] += b

    int operation = removeAssignment(binExp.getOperation().getType());
    ClassNode current =  controller.getClassNode();

    Expression leftExp = binExp.getLeftExpression();
    ClassNode leftType = controller.getTypeChooser().resolveType(leftExp, current);
    Expression rightExp = binExp.getRightExpression();
    ClassNode rightType = controller.getTypeChooser().resolveType(rightExp, current);

    int operationType = getOperandType(leftType);
    BinaryExpressionWriter bew = binExpWriter[operationType];

    boolean simulationSuccess = bew.arrayGet(LEFT_SQUARE_BRACKET, true);
    simulationSuccess = simulationSuccess && bew.write(operation, true);
    simulationSuccess = simulationSuccess && bew.arraySet(true);
    if (!simulationSuccess) return false;

    AsmClassGenerator acg = controller.getAcg();
    OperandStack operandStack = controller.getOperandStack();
    CompileStack compileStack = controller.getCompileStack();

    // for x[a] += b we have the structure:
    //   x = left(left(binExp))), b = right(binExp), a = right(left(binExp)))
    // for array set we need these values on stack: array, index, right
    // for array get we need these values on stack: array, index
    // to eval the expression we need x[a] = x[a]+b
    // -> arraySet(x,a, x[a]+b)
    // -> arraySet(x,a, arrayGet(x,a,b))
    // --> x,a, x,a, b as operands
    // --> load x, load a, DUP2, call arrayGet, load b, call operation,call arraySet
    // since we cannot DUP2 here easily we will save the subscript and DUP x
    // --> sub=a, load x, DUP, load sub, call arrayGet, load b, call operation, load sub, call arraySet

    BinaryExpression arrayWithSubscript = (BinaryExpression) leftExp;
    Expression subscript = arrayWithSubscript.getRightExpression();

    // load array index: sub=a [load x, DUP, load sub, call arrayGet, load b, call operation, load sub, call arraySet]
    subscript.visit(acg);
    operandStack.doGroovyCast(int_TYPE);
    int subscriptValueId = compileStack.defineTemporaryVariable("$sub", ClassHelper.int_TYPE, true);

    // load array: load x and DUP [load sub, call arrayGet, load b, call operation, load sub, call arraySet]
    arrayWithSubscript.getLeftExpression().visit(acg);
    operandStack.doGroovyCast(leftType.makeArray());
    operandStack.dup();

    // array get: load sub, call arrayGet [load b, call operation, load sub, call arraySet]
    operandStack.load(ClassHelper.int_TYPE, subscriptValueId);
    bew.arrayGet(LEFT_SQUARE_BRACKET, false);
    operandStack.replace(leftType, 2);

    // complete rhs: load b, call operation [load sub, call arraySet]
    binExp.getRightExpression().visit(acg);
    if (! (bew instanceof BinaryObjectExpressionHelper)) {
        // in primopts we convert to the left type for supported binary operations
        operandStack.doGroovyCast(leftType);
    }
    bew.write(operation, false);

    // let us save that value for the return
    operandStack.dup();
    int resultValueId = compileStack.defineTemporaryVariable("$result", rightType, true);

    // array set: load sub, call arraySet []
    operandStack.load(ClassHelper.int_TYPE, subscriptValueId);
    operandStack.swap();
    bew.arraySet(false);
    operandStack.remove(3); // 3 operands, the array, the index and the value!

    // load return value
    operandStack.load(rightType, resultValueId);

    // cleanup
    compileStack.removeVar(resultValueId);
    compileStack.removeVar(subscriptValueId);
    return true;
}
 
Example 17
Source File: StaticTypesCallSiteWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void writeListDotProperty(final Expression receiver, final String propertyName, final MethodVisitor mv, final boolean safe) {
    ClassNode componentType = receiver.getNodeMetaData(StaticCompilationMetadataKeys.COMPONENT_TYPE);
    if (componentType == null) {
        componentType = OBJECT_TYPE;
    }
    // for lists, replace list.foo with:
    // def result = new ArrayList(list.size())
    // for (e in list) { result.add (e.foo) }
    // result
    CompileStack compileStack = controller.getCompileStack();

    Label exit = new Label();
    if (safe) {
        receiver.visit(controller.getAcg());
        Label doGet = new Label();
        mv.visitJumpInsn(IFNONNULL, doGet);
        controller.getOperandStack().remove(1);
        mv.visitInsn(ACONST_NULL);
        mv.visitJumpInsn(GOTO, exit);
        mv.visitLabel(doGet);
    }

    Variable tmpList = varX("tmpList", ClassHelper.make(ArrayList.class));
    int var = compileStack.defineTemporaryVariable(tmpList, false);
    Variable iterator = varX("iterator", Iterator_TYPE);
    int it = compileStack.defineTemporaryVariable(iterator, false);
    Variable nextVar = varX("next", componentType);
    final int next = compileStack.defineTemporaryVariable(nextVar, false);

    mv.visitTypeInsn(NEW, "java/util/ArrayList");
    mv.visitInsn(DUP);
    receiver.visit(controller.getAcg());
    mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "size", "()I", true);
    controller.getOperandStack().remove(1);
    mv.visitMethodInsn(INVOKESPECIAL, "java/util/ArrayList", "<init>", "(I)V", false);
    mv.visitVarInsn(ASTORE, var);
    Label l1 = new Label();
    mv.visitLabel(l1);
    receiver.visit(controller.getAcg());
    mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "iterator", "()Ljava/util/Iterator;", true);
    controller.getOperandStack().remove(1);
    mv.visitVarInsn(ASTORE, it);
    Label l2 = new Label();
    mv.visitLabel(l2);
    mv.visitVarInsn(ALOAD, it);
    mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Iterator", "hasNext", "()Z", true);
    Label l3 = new Label();
    mv.visitJumpInsn(IFEQ, l3);
    mv.visitVarInsn(ALOAD, it);
    mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Iterator", "next", "()Ljava/lang/Object;", true);
    mv.visitTypeInsn(CHECKCAST, BytecodeHelper.getClassInternalName(componentType));
    mv.visitVarInsn(ASTORE, next);
    Label l4 = new Label();
    mv.visitLabel(l4);
    mv.visitVarInsn(ALOAD, var);
    PropertyExpression pexp = propX(
            bytecodeX(componentType, v -> v.visitVarInsn(ALOAD, next)),
            propertyName
    );
    pexp.visit(controller.getAcg());
    controller.getOperandStack().box();
    controller.getOperandStack().remove(1);
    mv.visitMethodInsn(INVOKEINTERFACE, "java/util/List", "add", "(Ljava/lang/Object;)Z", true);
    mv.visitInsn(POP);
    Label l5 = new Label();
    mv.visitLabel(l5);
    mv.visitJumpInsn(GOTO, l2);
    mv.visitLabel(l3);
    mv.visitVarInsn(ALOAD, var);
    if (safe) {
        mv.visitLabel(exit);
    }
    controller.getOperandStack().push(ClassHelper.make(ArrayList.class));
    controller.getCompileStack().removeVar(next);
    controller.getCompileStack().removeVar(it);
    controller.getCompileStack().removeVar(var);
}
 
Example 18
Source File: ClassCodeVisitorSupport.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitField(FieldNode node) {
    visitAnnotations(node);
    Expression init = node.getInitialExpression();
    if (init != null) init.visit(this);
}
 
Example 19
Source File: ListOfExpressionsExpression.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(final GroovyCodeVisitor visitor) {
    for (Expression expression : expressions) {
        expression.visit(visitor);
    }
}
 
Example 20
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);
}