Search in sources :

Example 1 with ForStatement

use of org.codehaus.groovy.ast.stmt.ForStatement in project groovy by apache.

the class StaticInvocationWriter method makeCall.

@Override
public void makeCall(final Expression origin, final Expression receiver, final Expression message, final Expression arguments, final MethodCallerMultiAdapter adapter, final boolean safe, final boolean spreadSafe, final boolean implicitThis) {
    ClassNode dynamicCallReturnType = origin.getNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION);
    if (dynamicCallReturnType != null) {
        StaticTypesWriterController staticController = (StaticTypesWriterController) controller;
        if (origin instanceof MethodCallExpression) {
            ((MethodCallExpression) origin).setMethodTarget(null);
        }
        InvocationWriter dynamicInvocationWriter = staticController.getRegularInvocationWriter();
        dynamicInvocationWriter.makeCall(origin, receiver, message, arguments, adapter, safe, spreadSafe, implicitThis);
        return;
    }
    if (tryImplicitReceiver(origin, message, arguments, adapter, safe, spreadSafe, implicitThis)) {
        return;
    }
    // if call is spread safe, replace it with a for in loop
    if (spreadSafe && origin instanceof MethodCallExpression) {
        // receiver expressions with side effects should not be visited twice, avoid by using a temporary variable
        Expression tmpReceiver = receiver;
        if (!(receiver instanceof VariableExpression) && !(receiver instanceof ConstantExpression)) {
            tmpReceiver = new TemporaryVariableExpression(receiver);
        }
        MethodVisitor mv = controller.getMethodVisitor();
        CompileStack compileStack = controller.getCompileStack();
        TypeChooser typeChooser = controller.getTypeChooser();
        OperandStack operandStack = controller.getOperandStack();
        ClassNode classNode = controller.getClassNode();
        int counter = labelCounter.incrementAndGet();
        // use a temporary variable for the arraylist in which the results of the spread call will be stored
        ConstructorCallExpression cce = new ConstructorCallExpression(StaticCompilationVisitor.ARRAYLIST_CLASSNODE, ArgumentListExpression.EMPTY_ARGUMENTS);
        cce.setNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, StaticCompilationVisitor.ARRAYLIST_CONSTRUCTOR);
        TemporaryVariableExpression result = new TemporaryVariableExpression(cce);
        result.visit(controller.getAcg());
        operandStack.pop();
        // if (receiver != null)
        tmpReceiver.visit(controller.getAcg());
        Label ifnull = compileStack.createLocalLabel("ifnull_" + counter);
        mv.visitJumpInsn(IFNULL, ifnull);
        // receiver consumed by if()
        operandStack.remove(1);
        Label nonull = compileStack.createLocalLabel("nonull_" + counter);
        mv.visitLabel(nonull);
        ClassNode componentType = StaticTypeCheckingVisitor.inferLoopElementType(typeChooser.resolveType(tmpReceiver, classNode));
        Parameter iterator = new Parameter(componentType, "for$it$" + counter);
        VariableExpression iteratorAsVar = new VariableExpression(iterator);
        MethodCallExpression origMCE = (MethodCallExpression) origin;
        MethodCallExpression newMCE = new MethodCallExpression(iteratorAsVar, origMCE.getMethodAsString(), origMCE.getArguments());
        newMCE.setImplicitThis(false);
        newMCE.setMethodTarget(origMCE.getMethodTarget());
        newMCE.setSafe(true);
        MethodCallExpression add = new MethodCallExpression(result, "add", newMCE);
        add.setImplicitThis(false);
        add.setMethodTarget(StaticCompilationVisitor.ARRAYLIST_ADD_METHOD);
        // for (e in receiver) { result.add(e?.method(arguments) }
        ForStatement stmt = new ForStatement(iterator, tmpReceiver, new ExpressionStatement(add));
        stmt.visit(controller.getAcg());
        // else { empty list }
        mv.visitLabel(ifnull);
        // end of if/else
        // return result list
        result.visit(controller.getAcg());
        // cleanup temporary variables
        if (tmpReceiver instanceof TemporaryVariableExpression) {
            ((TemporaryVariableExpression) tmpReceiver).remove(controller);
        }
        result.remove(controller);
    } else if (safe && origin instanceof MethodCallExpression) {
        // wrap call in an IFNULL check
        MethodVisitor mv = controller.getMethodVisitor();
        CompileStack compileStack = controller.getCompileStack();
        OperandStack operandStack = controller.getOperandStack();
        int counter = labelCounter.incrementAndGet();
        // if (receiver != null)
        ExpressionAsVariableSlot slot = new ExpressionAsVariableSlot(controller, receiver);
        slot.visit(controller.getAcg());
        operandStack.box();
        Label ifnull = compileStack.createLocalLabel("ifnull_" + counter);
        mv.visitJumpInsn(IFNULL, ifnull);
        // receiver consumed by if()
        operandStack.remove(1);
        Label nonull = compileStack.createLocalLabel("nonull_" + counter);
        mv.visitLabel(nonull);
        MethodCallExpression origMCE = (MethodCallExpression) origin;
        MethodCallExpression newMCE = new MethodCallExpression(new VariableSlotLoader(slot.getType(), slot.getIndex(), controller.getOperandStack()), origMCE.getMethodAsString(), origMCE.getArguments());
        MethodNode methodTarget = origMCE.getMethodTarget();
        newMCE.setMethodTarget(methodTarget);
        newMCE.setSafe(false);
        newMCE.setImplicitThis(origMCE.isImplicitThis());
        newMCE.setSourcePosition(origMCE);
        newMCE.visit(controller.getAcg());
        compileStack.removeVar(slot.getIndex());
        ClassNode returnType = operandStack.getTopOperand();
        if (ClassHelper.isPrimitiveType(returnType) && !ClassHelper.VOID_TYPE.equals(returnType)) {
            operandStack.box();
        }
        Label endof = compileStack.createLocalLabel("endof_" + counter);
        mv.visitJumpInsn(GOTO, endof);
        mv.visitLabel(ifnull);
        // else { null }
        mv.visitInsn(ACONST_NULL);
        mv.visitLabel(endof);
    } else {
        if ((adapter == AsmClassGenerator.getGroovyObjectField || adapter == AsmClassGenerator.getField) && origin instanceof AttributeExpression) {
            String pname = ((PropertyExpression) origin).getPropertyAsString();
            CallSiteWriter callSiteWriter = controller.getCallSiteWriter();
            if (pname != null && callSiteWriter instanceof StaticTypesCallSiteWriter) {
                StaticTypesCallSiteWriter stcsw = (StaticTypesCallSiteWriter) callSiteWriter;
                TypeChooser typeChooser = controller.getTypeChooser();
                if (stcsw.makeGetField(receiver, typeChooser.resolveType(receiver, controller.getClassNode()), pname, safe, false, true)) {
                    return;
                }
            }
        }
        super.makeCall(origin, receiver, message, arguments, adapter, safe, spreadSafe, implicitThis);
    }
}
Also used : Label(org.objectweb.asm.Label) MethodVisitor(org.objectweb.asm.MethodVisitor) ExtensionMethodNode(org.codehaus.groovy.transform.stc.ExtensionMethodNode) MethodNode(org.codehaus.groovy.ast.MethodNode) ForStatement(org.codehaus.groovy.ast.stmt.ForStatement) ClassNode(org.codehaus.groovy.ast.ClassNode) InnerClassNode(org.codehaus.groovy.ast.InnerClassNode) TemporaryVariableExpression(org.codehaus.groovy.transform.sc.TemporaryVariableExpression) TemporaryVariableExpression(org.codehaus.groovy.transform.sc.TemporaryVariableExpression) TemporaryVariableExpression(org.codehaus.groovy.transform.sc.TemporaryVariableExpression) ExpressionStatement(org.codehaus.groovy.ast.stmt.ExpressionStatement) Parameter(org.codehaus.groovy.ast.Parameter)

Example 2 with ForStatement

use of org.codehaus.groovy.ast.stmt.ForStatement in project groovy by apache.

the class AntlrParserPlugin method forStatement.

protected Statement forStatement(AST forNode) {
    AST inNode = forNode.getFirstChild();
    Expression collectionExpression;
    Parameter forParameter;
    if (isType(CLOSURE_LIST, inNode)) {
        forStatementBeingDef = true;
        ClosureListExpression clist = closureListExpression(inNode);
        forStatementBeingDef = false;
        int size = clist.getExpressions().size();
        if (size != 3) {
            throw new ASTRuntimeException(inNode, "3 expressions are required for the classic for loop, you gave " + size);
        }
        collectionExpression = clist;
        forParameter = ForStatement.FOR_LOOP_DUMMY;
    } else {
        AST variableNode = inNode.getFirstChild();
        AST collectionNode = variableNode.getNextSibling();
        ClassNode type = ClassHelper.OBJECT_TYPE;
        if (isType(VARIABLE_DEF, variableNode)) {
            AST node = variableNode.getFirstChild();
            // skip the final modifier if it's present
            if (isType(MODIFIERS, node)) {
                int modifiersMask = modifiers(node, new ArrayList<AnnotationNode>(), 0);
                // only final modifier allowed
                if ((modifiersMask & ~Opcodes.ACC_FINAL) != 0) {
                    throw new ASTRuntimeException(node, "Only the 'final' modifier is allowed in front of the for loop variable.");
                }
                node = node.getNextSibling();
            }
            type = makeTypeWithArguments(node);
            variableNode = node.getNextSibling();
        }
        String variable = identifier(variableNode);
        collectionExpression = expression(collectionNode);
        forParameter = new Parameter(type, variable);
        configureAST(forParameter, variableNode);
    }
    final AST node = inNode.getNextSibling();
    Statement block;
    if (isType(SEMI, node)) {
        block = EmptyStatement.INSTANCE;
    } else {
        block = statement(node);
    }
    ForStatement forStatement = new ForStatement(forParameter, collectionExpression, block);
    configureAST(forStatement, forNode);
    return forStatement;
}
Also used : EnumConstantClassNode(org.codehaus.groovy.ast.EnumConstantClassNode) InnerClassNode(org.codehaus.groovy.ast.InnerClassNode) ClassNode(org.codehaus.groovy.ast.ClassNode) AST(antlr.collections.AST) AnnotationNode(org.codehaus.groovy.ast.AnnotationNode) CaseStatement(org.codehaus.groovy.ast.stmt.CaseStatement) ForStatement(org.codehaus.groovy.ast.stmt.ForStatement) CatchStatement(org.codehaus.groovy.ast.stmt.CatchStatement) IfStatement(org.codehaus.groovy.ast.stmt.IfStatement) AssertStatement(org.codehaus.groovy.ast.stmt.AssertStatement) BlockStatement(org.codehaus.groovy.ast.stmt.BlockStatement) Statement(org.codehaus.groovy.ast.stmt.Statement) WhileStatement(org.codehaus.groovy.ast.stmt.WhileStatement) ExpressionStatement(org.codehaus.groovy.ast.stmt.ExpressionStatement) ThrowStatement(org.codehaus.groovy.ast.stmt.ThrowStatement) ContinueStatement(org.codehaus.groovy.ast.stmt.ContinueStatement) BreakStatement(org.codehaus.groovy.ast.stmt.BreakStatement) ReturnStatement(org.codehaus.groovy.ast.stmt.ReturnStatement) SynchronizedStatement(org.codehaus.groovy.ast.stmt.SynchronizedStatement) EmptyStatement(org.codehaus.groovy.ast.stmt.EmptyStatement) SwitchStatement(org.codehaus.groovy.ast.stmt.SwitchStatement) TryCatchStatement(org.codehaus.groovy.ast.stmt.TryCatchStatement) Parameter(org.codehaus.groovy.ast.Parameter) ForStatement(org.codehaus.groovy.ast.stmt.ForStatement)

Example 3 with ForStatement

use of org.codehaus.groovy.ast.stmt.ForStatement in project groovy-core by groovy.

the class StaticInvocationWriter method makeCall.

@Override
public void makeCall(final Expression origin, final Expression receiver, final Expression message, final Expression arguments, final MethodCallerMultiAdapter adapter, final boolean safe, final boolean spreadSafe, final boolean implicitThis) {
    ClassNode dynamicCallReturnType = origin.getNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION);
    if (dynamicCallReturnType != null) {
        StaticTypesWriterController staticController = (StaticTypesWriterController) controller;
        if (origin instanceof MethodCallExpression) {
            ((MethodCallExpression) origin).setMethodTarget(null);
        }
        InvocationWriter dynamicInvocationWriter = staticController.getRegularInvocationWriter();
        dynamicInvocationWriter.makeCall(origin, receiver, message, arguments, adapter, safe, spreadSafe, implicitThis);
        return;
    }
    if (tryImplicitReceiver(origin, message, arguments, adapter, safe, spreadSafe, implicitThis)) {
        return;
    }
    // if call is spread safe, replace it with a for in loop
    if (spreadSafe && origin instanceof MethodCallExpression) {
        MethodVisitor mv = controller.getMethodVisitor();
        CompileStack compileStack = controller.getCompileStack();
        TypeChooser typeChooser = controller.getTypeChooser();
        OperandStack operandStack = controller.getOperandStack();
        ClassNode classNode = controller.getClassNode();
        int counter = labelCounter.incrementAndGet();
        // create an empty arraylist
        VariableExpression result = new VariableExpression("spreadresult" + counter, StaticCompilationVisitor.ARRAYLIST_CLASSNODE);
        ConstructorCallExpression cce = new ConstructorCallExpression(StaticCompilationVisitor.ARRAYLIST_CLASSNODE, ArgumentListExpression.EMPTY_ARGUMENTS);
        cce.setNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, StaticCompilationVisitor.ARRAYLIST_CONSTRUCTOR);
        DeclarationExpression declr = new DeclarationExpression(result, Token.newSymbol("=", origin.getLineNumber(), origin.getColumnNumber()), cce);
        declr.visit(controller.getAcg());
        operandStack.pop();
        // if (receiver != null)
        receiver.visit(controller.getAcg());
        Label ifnull = compileStack.createLocalLabel("ifnull_" + counter);
        mv.visitJumpInsn(IFNULL, ifnull);
        // receiver consumed by if()
        operandStack.remove(1);
        Label nonull = compileStack.createLocalLabel("nonull_" + counter);
        mv.visitLabel(nonull);
        ClassNode componentType = StaticTypeCheckingVisitor.inferLoopElementType(typeChooser.resolveType(receiver, classNode));
        Parameter iterator = new Parameter(componentType, "for$it$" + counter);
        VariableExpression iteratorAsVar = new VariableExpression(iterator);
        MethodCallExpression origMCE = (MethodCallExpression) origin;
        MethodCallExpression newMCE = new MethodCallExpression(iteratorAsVar, origMCE.getMethodAsString(), origMCE.getArguments());
        newMCE.setImplicitThis(false);
        newMCE.setMethodTarget(origMCE.getMethodTarget());
        newMCE.setSafe(true);
        MethodCallExpression add = new MethodCallExpression(result, "add", newMCE);
        add.setImplicitThis(false);
        add.setMethodTarget(StaticCompilationVisitor.ARRAYLIST_ADD_METHOD);
        // for (e in receiver) { result.add(e?.method(arguments) }
        ForStatement stmt = new ForStatement(iterator, receiver, new ExpressionStatement(add));
        stmt.visit(controller.getAcg());
        // else { empty list }
        mv.visitLabel(ifnull);
        // end of if/else
        // return result list
        result.visit(controller.getAcg());
    } else if (safe && origin instanceof MethodCallExpression) {
        // wrap call in an IFNULL check
        MethodVisitor mv = controller.getMethodVisitor();
        CompileStack compileStack = controller.getCompileStack();
        OperandStack operandStack = controller.getOperandStack();
        int counter = labelCounter.incrementAndGet();
        // if (receiver != null)
        ExpressionAsVariableSlot slot = new ExpressionAsVariableSlot(controller, receiver);
        slot.visit(controller.getAcg());
        operandStack.box();
        Label ifnull = compileStack.createLocalLabel("ifnull_" + counter);
        mv.visitJumpInsn(IFNULL, ifnull);
        // receiver consumed by if()
        operandStack.remove(1);
        Label nonull = compileStack.createLocalLabel("nonull_" + counter);
        mv.visitLabel(nonull);
        MethodCallExpression origMCE = (MethodCallExpression) origin;
        MethodCallExpression newMCE = new MethodCallExpression(new VariableSlotLoader(slot.getType(), slot.getIndex(), controller.getOperandStack()), origMCE.getMethodAsString(), origMCE.getArguments());
        MethodNode methodTarget = origMCE.getMethodTarget();
        newMCE.setMethodTarget(methodTarget);
        newMCE.setSafe(false);
        newMCE.setImplicitThis(origMCE.isImplicitThis());
        newMCE.setSourcePosition(origMCE);
        newMCE.visit(controller.getAcg());
        compileStack.removeVar(slot.getIndex());
        ClassNode returnType = operandStack.getTopOperand();
        if (ClassHelper.isPrimitiveType(returnType) && !ClassHelper.VOID_TYPE.equals(returnType)) {
            operandStack.box();
        }
        Label endof = compileStack.createLocalLabel("endof_" + counter);
        mv.visitJumpInsn(GOTO, endof);
        mv.visitLabel(ifnull);
        // else { null }
        mv.visitInsn(ACONST_NULL);
        mv.visitLabel(endof);
    } else {
        if ((adapter == AsmClassGenerator.getGroovyObjectField || adapter == AsmClassGenerator.getField) && origin instanceof AttributeExpression) {
            String pname = ((PropertyExpression) origin).getPropertyAsString();
            CallSiteWriter callSiteWriter = controller.getCallSiteWriter();
            if (pname != null && callSiteWriter instanceof StaticTypesCallSiteWriter) {
                StaticTypesCallSiteWriter stcsw = (StaticTypesCallSiteWriter) callSiteWriter;
                TypeChooser typeChooser = controller.getTypeChooser();
                if (stcsw.makeGetField(receiver, typeChooser.resolveType(receiver, controller.getClassNode()), pname, safe, false, true)) {
                    return;
                }
            }
        }
        super.makeCall(origin, receiver, message, arguments, adapter, safe, spreadSafe, implicitThis);
    }
}
Also used : ClassNode(org.codehaus.groovy.ast.ClassNode) InnerClassNode(org.codehaus.groovy.ast.InnerClassNode) Label(org.objectweb.asm.Label) MethodVisitor(org.objectweb.asm.MethodVisitor) ExtensionMethodNode(org.codehaus.groovy.transform.stc.ExtensionMethodNode) MethodNode(org.codehaus.groovy.ast.MethodNode) ExpressionStatement(org.codehaus.groovy.ast.stmt.ExpressionStatement) Parameter(org.codehaus.groovy.ast.Parameter) ForStatement(org.codehaus.groovy.ast.stmt.ForStatement)

Example 4 with ForStatement

use of org.codehaus.groovy.ast.stmt.ForStatement in project groovy-core by groovy.

the class StaticTypesBinaryExpressionMultiTypeDispatcher method transformSpreadOnLHS.

private void transformSpreadOnLHS(BinaryExpression origin) {
    PropertyExpression spreadExpression = (PropertyExpression) origin.getLeftExpression();
    Expression value = origin.getRightExpression();
    WriterController controller = getController();
    MethodVisitor mv = controller.getMethodVisitor();
    CompileStack compileStack = controller.getCompileStack();
    TypeChooser typeChooser = controller.getTypeChooser();
    OperandStack operandStack = controller.getOperandStack();
    ClassNode classNode = controller.getClassNode();
    int counter = labelCounter.incrementAndGet();
    Expression receiver = spreadExpression.getObjectExpression();
    // create an empty arraylist
    VariableExpression result = new VariableExpression(this.getClass().getSimpleName() + "$spreadresult" + counter, ARRAYLIST_CLASSNODE);
    ConstructorCallExpression cce = new ConstructorCallExpression(ARRAYLIST_CLASSNODE, ArgumentListExpression.EMPTY_ARGUMENTS);
    cce.setNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, ARRAYLIST_CONSTRUCTOR);
    DeclarationExpression declr = new DeclarationExpression(result, Token.newSymbol("=", spreadExpression.getLineNumber(), spreadExpression.getColumnNumber()), cce);
    declr.visit(controller.getAcg());
    // if (receiver != null)
    receiver.visit(controller.getAcg());
    Label ifnull = compileStack.createLocalLabel("ifnull_" + counter);
    mv.visitJumpInsn(IFNULL, ifnull);
    // receiver consumed by if()
    operandStack.remove(1);
    Label nonull = compileStack.createLocalLabel("nonull_" + counter);
    mv.visitLabel(nonull);
    ClassNode componentType = StaticTypeCheckingVisitor.inferLoopElementType(typeChooser.resolveType(receiver, classNode));
    Parameter iterator = new Parameter(componentType, "for$it$" + counter);
    VariableExpression iteratorAsVar = new VariableExpression(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 = new BinaryExpression(pexp, origin.getOperation(), value);
    MethodCallExpression add = new MethodCallExpression(result, "add", assignment);
    add.setMethodTarget(ARRAYLIST_ADD_METHOD);
    // for (e in receiver) { result.add(e?.method(arguments) }
    ForStatement stmt = new ForStatement(iterator, receiver, new ExpressionStatement(add));
    stmt.visit(controller.getAcg());
    // else { empty list }
    mv.visitLabel(ifnull);
    // end of if/else
    // return result list
    result.visit(controller.getAcg());
}
Also used : Label(org.objectweb.asm.Label) MethodVisitor(org.objectweb.asm.MethodVisitor) ExpressionStatement(org.codehaus.groovy.ast.stmt.ExpressionStatement) ForStatement(org.codehaus.groovy.ast.stmt.ForStatement)

Example 5 with ForStatement

use of org.codehaus.groovy.ast.stmt.ForStatement in project groovy-core by groovy.

the class CategoryASTTransformation method visit.

/**
     * Property invocations done on 'this' reference are transformed so that the invocations at runtime are
     * done on the additional parameter 'self'
     */
public void visit(ASTNode[] nodes, final SourceUnit source) {
    if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof ClassNode)) {
        source.getErrorCollector().addError(new SyntaxErrorMessage(new SyntaxException("@Category can only be added to a ClassNode but got: " + (nodes.length == 2 ? nodes[1] : "nothing"), nodes[0].getLineNumber(), nodes[0].getColumnNumber()), source));
    }
    AnnotationNode annotation = (AnnotationNode) nodes[0];
    ClassNode parent = (ClassNode) nodes[1];
    ClassNode targetClass = getTargetClass(source, annotation);
    thisExpression.setType(targetClass);
    final LinkedList<Set<String>> varStack = new LinkedList<Set<String>>();
    if (!ensureNoInstanceFieldOrProperty(source, parent))
        return;
    Set<String> names = new HashSet<String>();
    for (FieldNode field : parent.getFields()) {
        names.add(field.getName());
    }
    for (PropertyNode field : parent.getProperties()) {
        names.add(field.getName());
    }
    varStack.add(names);
    final Reference parameter = new Reference();
    final ClassCodeExpressionTransformer expressionTransformer = new ClassCodeExpressionTransformer() {

        protected SourceUnit getSourceUnit() {
            return source;
        }

        private void addVariablesToStack(Parameter[] params) {
            Set<String> names = new HashSet<String>();
            names.addAll(varStack.getLast());
            for (Parameter param : params) {
                names.add(param.getName());
            }
            varStack.add(names);
        }

        @Override
        public void visitCatchStatement(CatchStatement statement) {
            varStack.getLast().add(statement.getVariable().getName());
            super.visitCatchStatement(statement);
            varStack.getLast().remove(statement.getVariable().getName());
        }

        @Override
        public void visitMethod(MethodNode node) {
            addVariablesToStack(node.getParameters());
            super.visitMethod(node);
            varStack.removeLast();
        }

        @Override
        public void visitBlockStatement(BlockStatement block) {
            Set<String> names = new HashSet<String>();
            names.addAll(varStack.getLast());
            varStack.add(names);
            super.visitBlockStatement(block);
            varStack.remove(names);
        }

        @Override
        public void visitClosureExpression(ClosureExpression ce) {
            addVariablesToStack(ce.getParameters());
            super.visitClosureExpression(ce);
            varStack.removeLast();
        }

        @Override
        public void visitDeclarationExpression(DeclarationExpression expression) {
            if (expression.isMultipleAssignmentDeclaration()) {
                TupleExpression te = expression.getTupleExpression();
                List<Expression> list = te.getExpressions();
                for (Expression arg : list) {
                    VariableExpression ve = (VariableExpression) arg;
                    varStack.getLast().add(ve.getName());
                }
            } else {
                VariableExpression ve = expression.getVariableExpression();
                varStack.getLast().add(ve.getName());
            }
            super.visitDeclarationExpression(expression);
        }

        @Override
        public void visitForLoop(ForStatement forLoop) {
            Expression exp = forLoop.getCollectionExpression();
            exp.visit(this);
            Parameter loopParam = forLoop.getVariable();
            if (loopParam != null) {
                varStack.getLast().add(loopParam.getName());
            }
            super.visitForLoop(forLoop);
        }

        @Override
        public void visitExpressionStatement(ExpressionStatement es) {
            // GROOVY-3543: visit the declaration expressions so that declaration variables get added on the varStack
            Expression exp = es.getExpression();
            if (exp instanceof DeclarationExpression) {
                exp.visit(this);
            }
            super.visitExpressionStatement(es);
        }

        @Override
        public Expression transform(Expression exp) {
            if (exp instanceof VariableExpression) {
                VariableExpression ve = (VariableExpression) exp;
                if (ve.getName().equals("this"))
                    return thisExpression;
                else {
                    if (!varStack.getLast().contains(ve.getName())) {
                        return new PropertyExpression(thisExpression, ve.getName());
                    }
                }
            } else if (exp instanceof PropertyExpression) {
                PropertyExpression pe = (PropertyExpression) exp;
                if (pe.getObjectExpression() instanceof VariableExpression) {
                    VariableExpression vex = (VariableExpression) pe.getObjectExpression();
                    if (vex.isThisExpression()) {
                        pe.setObjectExpression(thisExpression);
                        return pe;
                    }
                }
            } else if (exp instanceof ClosureExpression) {
                ClosureExpression ce = (ClosureExpression) exp;
                ce.getVariableScope().putReferencedLocalVariable((Parameter) parameter.get());
                Parameter[] params = ce.getParameters();
                if (params == null) {
                    params = Parameter.EMPTY_ARRAY;
                } else if (params.length == 0) {
                    params = new Parameter[] { new Parameter(ClassHelper.OBJECT_TYPE, "it") };
                }
                addVariablesToStack(params);
                ce.getCode().visit(this);
                varStack.removeLast();
            }
            return super.transform(exp);
        }
    };
    for (MethodNode method : parent.getMethods()) {
        if (!method.isStatic()) {
            method.setModifiers(method.getModifiers() | Opcodes.ACC_STATIC);
            final Parameter[] origParams = method.getParameters();
            final Parameter[] newParams = new Parameter[origParams.length + 1];
            Parameter p = new Parameter(targetClass, "$this");
            p.setClosureSharedVariable(true);
            newParams[0] = p;
            parameter.set(p);
            System.arraycopy(origParams, 0, newParams, 1, origParams.length);
            method.setParameters(newParams);
            expressionTransformer.visitMethod(method);
        }
    }
    new VariableScopeVisitor(source, true).visitClass(parent);
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) TupleExpression(org.codehaus.groovy.ast.expr.TupleExpression) BlockStatement(org.codehaus.groovy.ast.stmt.BlockStatement) MethodNode(org.codehaus.groovy.ast.MethodNode) AnnotationNode(org.codehaus.groovy.ast.AnnotationNode) SyntaxException(org.codehaus.groovy.syntax.SyntaxException) PropertyNode(org.codehaus.groovy.ast.PropertyNode) PropertyExpression(org.codehaus.groovy.ast.expr.PropertyExpression) ClosureExpression(org.codehaus.groovy.ast.expr.ClosureExpression) ForStatement(org.codehaus.groovy.ast.stmt.ForStatement) HashSet(java.util.HashSet) ClassCodeExpressionTransformer(org.codehaus.groovy.ast.ClassCodeExpressionTransformer) ClassNode(org.codehaus.groovy.ast.ClassNode) FieldNode(org.codehaus.groovy.ast.FieldNode) SyntaxErrorMessage(org.codehaus.groovy.control.messages.SyntaxErrorMessage) Reference(groovy.lang.Reference) DeclarationExpression(org.codehaus.groovy.ast.expr.DeclarationExpression) VariableExpression(org.codehaus.groovy.ast.expr.VariableExpression) LinkedList(java.util.LinkedList) CatchStatement(org.codehaus.groovy.ast.stmt.CatchStatement) PropertyExpression(org.codehaus.groovy.ast.expr.PropertyExpression) Expression(org.codehaus.groovy.ast.expr.Expression) VariableExpression(org.codehaus.groovy.ast.expr.VariableExpression) DeclarationExpression(org.codehaus.groovy.ast.expr.DeclarationExpression) ClosureExpression(org.codehaus.groovy.ast.expr.ClosureExpression) ClassExpression(org.codehaus.groovy.ast.expr.ClassExpression) TupleExpression(org.codehaus.groovy.ast.expr.TupleExpression) ExpressionStatement(org.codehaus.groovy.ast.stmt.ExpressionStatement) Parameter(org.codehaus.groovy.ast.Parameter) VariableScopeVisitor(org.codehaus.groovy.classgen.VariableScopeVisitor)

Aggregations

ForStatement (org.codehaus.groovy.ast.stmt.ForStatement)12 ExpressionStatement (org.codehaus.groovy.ast.stmt.ExpressionStatement)10 BlockStatement (org.codehaus.groovy.ast.stmt.BlockStatement)8 Statement (org.codehaus.groovy.ast.stmt.Statement)6 ClassNode (org.codehaus.groovy.ast.ClassNode)5 Parameter (org.codehaus.groovy.ast.Parameter)5 MethodNode (org.codehaus.groovy.ast.MethodNode)4 VariableExpression (org.codehaus.groovy.ast.expr.VariableExpression)4 CatchStatement (org.codehaus.groovy.ast.stmt.CatchStatement)4 InvokerInvocationException (org.codehaus.groovy.runtime.InvokerInvocationException)4 Label (org.objectweb.asm.Label)4 AnnotationNode (org.codehaus.groovy.ast.AnnotationNode)3 InnerClassNode (org.codehaus.groovy.ast.InnerClassNode)3 MethodVisitor (org.objectweb.asm.MethodVisitor)3 Reference (groovy.lang.Reference)2 HashSet (java.util.HashSet)2 LinkedList (java.util.LinkedList)2 Set (java.util.Set)2 ClassCodeExpressionTransformer (org.codehaus.groovy.ast.ClassCodeExpressionTransformer)2 FieldNode (org.codehaus.groovy.ast.FieldNode)2