org.codehaus.groovy.ast.stmt.ForStatement Java Examples

The following examples show how to use org.codehaus.groovy.ast.stmt.ForStatement. 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: StaticCompilationVisitor.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void visitForLoop(final ForStatement statement) {
    super.visitForLoop(statement);
    Expression collectionExpression = statement.getCollectionExpression();
    if (!(collectionExpression instanceof ClosureListExpression)) {
        ClassNode forLoopVariableType = statement.getVariableType();
        ClassNode collectionType = getType(collectionExpression);
        ClassNode componentType;
        if (Character_TYPE.equals(ClassHelper.getWrapper(forLoopVariableType)) && STRING_TYPE.equals(collectionType)) {
            // we allow auto-coercion here
            componentType = forLoopVariableType;
        } else {
            componentType = inferLoopElementType(collectionType);
        }
        statement.getVariable().setType(componentType);
    }
}
 
Example #2
Source File: OptimizingStatementWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
protected void writeForInLoop(final ForStatement statement) {
    if (controller.isFastPath()) {
        super.writeForInLoop(statement);
    } else {
        StatementMeta meta = statement.getNodeMetaData(StatementMeta.class);
        FastPathData fastPathData = writeGuards(meta, statement);

        boolean oldFastPathBlock = fastPathBlocked;
        fastPathBlocked = true;
        super.writeForInLoop(statement);
        fastPathBlocked = oldFastPathBlock;

        if (fastPathData == null) return;
        writeFastPathPrelude(fastPathData);
        super.writeForInLoop(statement);
        writeFastPathEpilogue(fastPathData);
    }
}
 
Example #3
Source File: OptimizingStatementWriter.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
protected void writeForLoopWithClosureList(final ForStatement statement) {
    if (controller.isFastPath()) {
        super.writeForLoopWithClosureList(statement);
    } else {
        StatementMeta meta = statement.getNodeMetaData(StatementMeta.class);
        FastPathData fastPathData = writeGuards(meta, statement);

        boolean oldFastPathBlock = fastPathBlocked;
        fastPathBlocked = true;
        super.writeForLoopWithClosureList(statement);
        fastPathBlocked = oldFastPathBlock;

        if (fastPathData == null) return;
        writeFastPathPrelude(fastPathData);
        super.writeForLoopWithClosureList(statement);
        writeFastPathEpilogue(fastPathData);
    }
}
 
Example #4
Source File: VariableScopeVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void visitForLoop(ForStatement forLoop) {
    if (FindTypeUtils.isCaretOnClassNode(path, doc, cursorOffset)) {
        addOccurrences(forLoop.getVariableType(), (ClassNode) FindTypeUtils.findCurrentNode(path, doc, cursorOffset));
    } else {
        final Parameter forLoopVar = forLoop.getVariable();
        final String varName = forLoopVar.getName();
        
        if (leaf instanceof Variable) {
            if (varName.equals(((Variable) leaf).getName())) {
                occurrences.add(forLoopVar);
            }
        } else if (leaf instanceof ForStatement) {
            if (varName.equals(((ForStatement) leaf).getVariable().getName())) {
                occurrences.add(forLoopVar);
            }
        }
    }
    super.visitForLoop(forLoop);
}
 
Example #5
Source File: TupleListTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void assertIterate(String methodName, Expression listExpression) throws Exception {
    ClassNode classNode = new ClassNode("Foo", ACC_PUBLIC, ClassHelper.OBJECT_TYPE);
    classNode.addConstructor(new ConstructorNode(ACC_PUBLIC, null));
    classNode.addProperty(new PropertyNode("bar", ACC_PUBLIC, ClassHelper.STRING_TYPE, classNode, null, null, null));

    Statement loopStatement = createPrintlnStatement(new VariableExpression("i"));

    BlockStatement block = new BlockStatement();
    block.addStatement(new ExpressionStatement(new DeclarationExpression(new VariableExpression("list"), Token.newSymbol("=", 0, 0), listExpression)));
    block.addStatement(new ForStatement(new Parameter(ClassHelper.DYNAMIC_TYPE, "i"), new VariableExpression("list"), loopStatement));
    classNode.addMethod(new MethodNode(methodName, ACC_PUBLIC, ClassHelper.VOID_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, block));

    Class fooClass = loadClass(classNode);
    assertTrue("Loaded a new class", fooClass != null);

    Object bean = fooClass.getDeclaredConstructor().newInstance();
    assertTrue("Managed to create bean", bean != null);

    System.out.println("################ Now about to invoke method");

    try {
        InvokerHelper.invokeMethod(bean, methodName, null);
    }
    catch (InvokerInvocationException e) {
        System.out.println("Caught: " + e.getCause());
        e.getCause().printStackTrace();
        fail("Should not have thrown an exception");
    }
    System.out.println("################ Done");
}
 
Example #6
Source File: ASTNodeVisitor.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
public void visitForLoop(ForStatement node) {
	pushASTNode(node);
	try {
		super.visitForLoop(node);
	} finally {
		popASTNode();
	}
}
 
Example #7
Source File: VariableScopeVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitForLoop(final ForStatement statement) {
    pushState();
    statement.setVariableScope(currentScope);
    Parameter parameter = statement.getVariable();
    parameter.setInStaticContext(currentScope.isInStaticContext());
    if (parameter != ForStatement.FOR_LOOP_DUMMY) declare(parameter, statement);
    super.visitForLoop(statement);
    popState();
}
 
Example #8
Source File: OptimizingStatementWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void visitForLoop(final ForStatement statement) {
    opt.push();
    super.visitForLoop(statement);
    if (opt.shouldOptimize()) {
        addMeta(statement, opt);
    }
    opt.pop(opt.shouldOptimize());
}
 
Example #9
Source File: StaticTypesStatementWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
protected void writeForInLoop(final ForStatement loop) {
    controller.getAcg().onLineNumber(loop,"visitForLoop");
    writeStatementLabel(loop);

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

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

    // Identify type of collection
    TypeChooser typeChooser = controller.getTypeChooser();
    Expression collectionExpression = loop.getCollectionExpression();
    ClassNode collectionType = typeChooser.resolveType(collectionExpression, controller.getClassNode());
    Parameter loopVariable = loop.getVariable();
    int size = operandStack.getStackLength();
    if (collectionType.isArray() && loopVariable.getOriginType().equals(collectionType.getComponentType())) {
        writeOptimizedForEachLoop(compileStack, operandStack, mv, loop, collectionExpression, collectionType, loopVariable);
    } else if (ENUMERATION_CLASSNODE.equals(collectionType)) {
        writeEnumerationBasedForEachLoop(compileStack, operandStack, mv, loop, collectionExpression, collectionType, loopVariable);
    } else {
        writeIteratorBasedForEachLoop(compileStack, operandStack, mv, loop, collectionExpression, collectionType, loopVariable);
    }
    operandStack.popDownTo(size);
    compileStack.pop();
}
 
Example #10
Source File: VariableFinderVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void visitForLoop(ForStatement forLoop) {
    if (!blocks.remove(forLoop)) {
        return;
    }

    Parameter param = forLoop.getVariable();
    if (param != ForStatement.FOR_LOOP_DUMMY) {
        variables.put(param.getName(), param);
    }
    super.visitForLoop(forLoop);
}
 
Example #11
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 #12
Source File: StatementWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void writeForStatement(final ForStatement statement) {
    if (statement.getVariable() == ForStatement.FOR_LOOP_DUMMY) {
        writeForLoopWithClosureList(statement);
    } else {
        writeForInLoop(statement);
    }
}
 
Example #13
Source File: ForTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void testLoop() throws Exception {
    ClassNode classNode = new ClassNode("Foo", ACC_PUBLIC, ClassHelper.OBJECT_TYPE);
    classNode.addConstructor(new ConstructorNode(ACC_PUBLIC, null));

    Parameter[] parameters = {new Parameter(ClassHelper.OBJECT_TYPE.makeArray(), "coll")};

    Statement loopStatement = createPrintlnStatement(new VariableExpression("i"));

    ForStatement statement = new ForStatement(new Parameter(ClassHelper.OBJECT_TYPE, "i"), new VariableExpression("coll"), loopStatement);
    classNode.addMethod(new MethodNode("iterateDemo", ACC_PUBLIC, ClassHelper.VOID_TYPE, parameters, ClassNode.EMPTY_ARRAY, statement));

    Class fooClass = loadClass(classNode);
    assertTrue("Loaded a new class", fooClass != null);

    Object bean = fooClass.getDeclaredConstructor().newInstance();
    assertTrue("Managed to create bean", bean != null);

    System.out.println("################ Now about to invoke a method with looping");
    Object[] array = {Integer.valueOf(1234), "abc", "def"};

    try {
        InvokerHelper.invokeMethod(bean, "iterateDemo", new Object[]{array});
    } catch (InvokerInvocationException e) {
        System.out.println("Caught: " + e.getCause());
        e.getCause().printStackTrace();
        fail("Should not have thrown an exception");
    }
    System.out.println("################ Done");
}
 
Example #14
Source File: StaticTypesStatementWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
private void writeOptimizedForEachLoop(
        CompileStack compileStack,
        OperandStack operandStack,
        MethodVisitor mv,
        ForStatement loop,
        Expression collectionExpression,
        ClassNode collectionType,
        Parameter loopVariable) {
    BytecodeVariable variable = compileStack.defineVariable(loopVariable, false);

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

    AsmClassGenerator acg = controller.getAcg();

    // load array on stack
    collectionExpression.visit(acg);
    mv.visitInsn(DUP);
    int array = compileStack.defineTemporaryVariable("$arr", collectionType, true);
    mv.visitJumpInsn(IFNULL, breakLabel);

    // $len = array.length
    mv.visitVarInsn(ALOAD, array);
    mv.visitInsn(ARRAYLENGTH);
    operandStack.push(ClassHelper.int_TYPE);
    int arrayLen = compileStack.defineTemporaryVariable("$len", ClassHelper.int_TYPE, true);

    // $idx = 0
    mv.visitInsn(ICONST_0);
    operandStack.push(ClassHelper.int_TYPE);
    int loopIdx = compileStack.defineTemporaryVariable("$idx", ClassHelper.int_TYPE, true);

    mv.visitLabel(continueLabel);
    // $idx<$len?
    mv.visitVarInsn(ILOAD, loopIdx);
    mv.visitVarInsn(ILOAD, arrayLen);
    mv.visitJumpInsn(IF_ICMPGE, breakLabel);

    // get array element
    loadFromArray(mv, variable, array, loopIdx);

    // $idx++
    mv.visitIincInsn(loopIdx, 1);

    // loop body
    loop.getLoopBlock().visit(acg);

    mv.visitJumpInsn(GOTO, continueLabel);

    mv.visitLabel(breakLabel);

    compileStack.removeVar(loopIdx);
    compileStack.removeVar(arrayLen);
    compileStack.removeVar(array);
}
 
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);
}
 
Example #16
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 #17
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();
}
 
Example #18
Source File: StatementWriter.java    From groovy with Apache License 2.0 4 votes vote down vote up
protected void writeForLoopWithClosureList(final ForStatement statement) {
    controller.getAcg().onLineNumber(statement, "visitForLoop");
    writeStatementLabel(statement);

    MethodVisitor mv = controller.getMethodVisitor();
    controller.getCompileStack().pushLoop(statement.getVariableScope(), statement.getStatementLabels());

    ClosureListExpression clExpr = (ClosureListExpression) statement.getCollectionExpression();
    controller.getCompileStack().pushVariableScope(clExpr.getVariableScope());

    List<Expression> expressions = clExpr.getExpressions();
    int size = expressions.size();

    // middle element is condition, lower half is init, higher half is increment
    int condIndex = (size - 1) / 2;

    // visit init
    for (int i = 0; i < condIndex; i += 1) {
        visitExpressionOfLoopStatement(expressions.get(i));
    }

    Label continueLabel = controller.getCompileStack().getContinueLabel();
    Label breakLabel = controller.getCompileStack().getBreakLabel();

    Label cond = new Label();
    mv.visitLabel(cond);
    // visit condition leave boolean on stack
    {
        int mark = controller.getOperandStack().getStackLength();
        Expression condExpr = expressions.get(condIndex);
        condExpr.visit(controller.getAcg());
        controller.getOperandStack().castToBool(mark, true);
    }
    // jump if we don't want to continue
    // note: ifeq tests for ==0, a boolean is 0 if it is false
    controller.getOperandStack().jump(IFEQ, breakLabel);

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

    // visit increment
    mv.visitLabel(continueLabel);
    // fix for being on the wrong line when debugging for loop
    controller.getAcg().onLineNumber(statement, "increment condition");
    for (int i = condIndex + 1; i < size; i += 1) {
        visitExpressionOfLoopStatement(expressions.get(i));
    }

    // jump to test the condition again
    mv.visitJumpInsn(GOTO, cond);

    // loop end
    mv.visitLabel(breakLabel);

    controller.getCompileStack().pop();
    controller.getCompileStack().pop();
}
 
Example #19
Source File: AsmClassGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitForLoop(final ForStatement statement) {
    controller.getStatementWriter().writeForStatement(statement);
}
 
Example #20
Source File: VerifierCodeVisitor.java    From groovy with Apache License 2.0 4 votes vote down vote up
public void visitForLoop(ForStatement expression) {
    assertValidIdentifier(expression.getVariable().getName(), "for loop variable name", expression);
    super.visitForLoop(expression);
}
 
Example #21
Source File: ClassCodeExpressionTransformer.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitForLoop(ForStatement stmt) {
    stmt.setCollectionExpression(transform(stmt.getCollectionExpression()));
    super.visitForLoop(stmt);
}
 
Example #22
Source File: ClassCodeVisitorSupport.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitForLoop(ForStatement statement) {
    visitStatement(statement);
    super.visitForLoop(statement);
}
 
Example #23
Source File: ASTFinder.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitForLoop(final ForStatement forLoop) {
    super.visitForLoop(forLoop);
    tryFind(ForStatement.class, forLoop);
}
 
Example #24
Source File: PathFinderVisitor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void visitForLoop(ForStatement node) {
    if (isInside(node, line, column)) {
        super.visitForLoop(node);
    }
}
 
Example #25
Source File: FindTypeUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static boolean isCaretOnForStatementType(ForStatement forLoop, BaseDocument doc, int cursorOffset) {
    if (getForLoopRange(forLoop, doc, cursorOffset) != OffsetRange.NONE) {
        return true;
    }
    return false;
}
 
Example #26
Source File: FindTypeUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static OffsetRange getForLoopRange(ForStatement forLoop, BaseDocument doc, int cursorOffset) {
    return getRange(forLoop.getVariableType(), doc, cursorOffset);
}
 
Example #27
Source File: ElementUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Returns type for the given ASTNode. For example if FieldNode is passed
 * as a parameter, it returns type of the given field etc. If the Method call
 * is passed as a parameter, the method tried to interfere proper type and return it
 *
 * @param node where we want to know declared type
 * @return type of the given node
 * @throws IllegalStateException if an implementation is missing for the given ASTNode type
 */
public static ClassNode getType(ASTNode node) {
    if (node instanceof FakeASTNode) {
        node = ((FakeASTNode) node).getOriginalNode();
    }

    if (node instanceof ClassNode) {
        ClassNode clazz = ((ClassNode) node);
        if (clazz.getComponentType() != null) {
            return clazz.getComponentType();
        } else {
            return clazz;
        }
    } else if (node instanceof AnnotationNode) {
        return ((AnnotationNode) node).getClassNode();
    } else if (node instanceof FieldNode) {
        return ((FieldNode) node).getType();
    } else if (node instanceof PropertyNode) {
        return ((PropertyNode) node).getType();
    } else if (node instanceof MethodNode) {
        return ((MethodNode) node).getReturnType();
    } else if (node instanceof Parameter) {
       return ((Parameter) node).getType();
    } else if (node instanceof ForStatement) {
        return ((ForStatement) node).getVariableType();
    } else if (node instanceof CatchStatement) {
        return ((CatchStatement) node).getVariable().getOriginType();
    } else if (node instanceof ImportNode) {
        return ((ImportNode) node).getType();
    } else if (node instanceof ClassExpression) {
        return ((ClassExpression) node).getType();
    } else if (node instanceof VariableExpression) {
        return ((VariableExpression) node).getType();
    } else if (node instanceof DeclarationExpression) {
        DeclarationExpression declaration = ((DeclarationExpression) node);
        if (declaration.isMultipleAssignmentDeclaration()) {
            return declaration.getTupleExpression().getType();
        } else {
            return declaration.getVariableExpression().getType();
        }
    } else if (node instanceof ConstructorCallExpression) {
        return ((ConstructorCallExpression) node).getType();
    } else if (node instanceof ArrayExpression) {
        return ((ArrayExpression) node).getElementType();
    }
    throw new IllegalStateException("Not implemented yet - GroovyRefactoringElement.getType() needs to be improve!"); // NOI18N
}
 
Example #28
Source File: ElementUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static String getNameWithoutPackage(ASTNode node) {
    if (node instanceof FakeASTNode) {
        node = ((FakeASTNode) node).getOriginalNode();
    }

    String name = null;
    if (node instanceof ClassNode) {
        name = ((ClassNode) node).getNameWithoutPackage();
    } else if (node instanceof AnnotationNode) {
        return ((AnnotationNode) node).getText();
    } else if (node instanceof MethodNode) {
        name = ((MethodNode) node).getName();
        if ("<init>".equals(name)) { // NOI18N
            name = getDeclaringClassNameWithoutPackage(node);
        }
    } else if (node instanceof FieldNode) {
        name = ((FieldNode) node).getName();
    } else if (node instanceof PropertyNode) {
        name = ((PropertyNode) node).getName();
    } else if (node instanceof Parameter) {
        name = ((Parameter) node).getName();
    } else if (node instanceof ForStatement) {
        name = ((ForStatement) node).getVariableType().getNameWithoutPackage();
    } else if (node instanceof CatchStatement) {
        name = ((CatchStatement) node).getVariable().getName();
    } else if (node instanceof ImportNode) {
        name = ((ImportNode) node).getType().getNameWithoutPackage();
    } else if (node instanceof ClassExpression) {
        name = ((ClassExpression) node).getType().getNameWithoutPackage();
    } else if (node instanceof VariableExpression) {
        name = ((VariableExpression) node).getName();
    } else if (node instanceof DeclarationExpression) {
        DeclarationExpression declaration = ((DeclarationExpression) node);
        if (declaration.isMultipleAssignmentDeclaration()) {
            name = declaration.getTupleExpression().getType().getNameWithoutPackage();
        } else {
            name = declaration.getVariableExpression().getType().getNameWithoutPackage();
        }
    } else if (node instanceof ConstantExpression) {
        name = ((ConstantExpression) node).getText();
    } else if (node instanceof MethodCallExpression) {
        name = ((MethodCallExpression) node).getMethodAsString();
    } else if (node instanceof ConstructorCallExpression) {
        name = ((ConstructorCallExpression) node).getType().getNameWithoutPackage();
    } else if (node instanceof ArrayExpression) {
        name = ((ArrayExpression) node).getElementType().getNameWithoutPackage();
    }


    if (name != null) {
        return normalizeTypeName(name, null);
    }
    throw new IllegalStateException("Not implemented yet - GroovyRefactoringElement.getName() needs to be improve for type: " + node.getClass().getSimpleName()); // NOI18N
}
 
Example #29
Source File: ElementUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static ClassNode getDeclaringClass(ASTNode node) {
    if (node instanceof ClassNode) {
        return (ClassNode) node;
    } else if (node instanceof AnnotationNode) {
        return ((AnnotationNode) node).getClassNode();
    } else if (node instanceof MethodNode) {
        return ((MethodNode) node).getDeclaringClass();
    } else if (node instanceof FieldNode) {
        return ((FieldNode) node).getDeclaringClass();
    } else if (node instanceof PropertyNode) {
        return ((PropertyNode) node).getDeclaringClass();
    } else if (node instanceof Parameter) {
        return ((Parameter) node).getDeclaringClass();
    } else if (node instanceof ForStatement) {
        return ((ForStatement) node).getVariableType().getDeclaringClass();
    } else if (node instanceof CatchStatement) {
        return ((CatchStatement) node).getVariable().getDeclaringClass();
    } else if (node instanceof ImportNode) {
        return ((ImportNode) node).getDeclaringClass();
    } else if (node instanceof ClassExpression) {
        return ((ClassExpression) node).getType().getDeclaringClass();
    } else if (node instanceof VariableExpression) {
        return ((VariableExpression) node).getDeclaringClass();
    } else if (node instanceof DeclarationExpression) {
        DeclarationExpression declaration = ((DeclarationExpression) node);
        if (declaration.isMultipleAssignmentDeclaration()) {
            return declaration.getTupleExpression().getDeclaringClass();
        } else {
            return declaration.getVariableExpression().getDeclaringClass();
        }
    } else if (node instanceof ConstantExpression) {
        return ((ConstantExpression) node).getDeclaringClass();
    } else if (node instanceof MethodCallExpression) {
        return ((MethodCallExpression) node).getType();
    } else if (node instanceof ConstructorCallExpression) {
        return ((ConstructorCallExpression) node).getType();
    } else if (node instanceof ArrayExpression) {
        return ((ArrayExpression) node).getDeclaringClass();
    }

    throw new IllegalStateException("Not implemented yet - GroovyRefactoringElement.getDeclaringClass() ..looks like the type: " + node.getClass().getName() + " isn't handled at the moment!"); // NOI18N
}
 
Example #30
Source File: VariableFinderVisitor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void collect() {
    TokenSequence<GroovyTokenId> ts = LexUtilities.getPositionedSequence(doc, cursorOffset);
    if (ts == null) {
        return;
    }
    Token<GroovyTokenId> token = ts.token();
    if (token == null) {
        return;
    }

    ASTNode last = null;

    blocks.clear();
    variables.clear();

    // We are going through the path up marking all the declaration
    // blocks and the top (last) one.
    for (Iterator<ASTNode> it = path.iterator(); it.hasNext();) {
        ASTNode scope = it.next();
        if ((scope instanceof ClosureExpression) || (scope instanceof MethodNode)
                || (scope instanceof ConstructorNode) || (scope instanceof ForStatement)
                || (scope instanceof BlockStatement) || (scope instanceof ClosureListExpression)
                || (scope instanceof CatchStatement)) {

            last = scope;
            blocks.add(scope);

            // In for loop we have to allow visitor to visit ClosureListExpression
            if ((scope instanceof ForStatement)
                    && (((ForStatement) scope).getCollectionExpression() instanceof ClosureListExpression)) {
                blocks.add(((ForStatement) scope).getCollectionExpression());
            }
        }
    }

    // Lets visit the code from top. We visit only allowed blocks
    // to avoid visiting subtrees declared before offset, but not usable.
    // ie
    // def clos = {
    //     def x = {
    //         String str
    //     }
    //     ^ // we are here and we dont want to get str as possibility
    // }
    if (last instanceof ClosureExpression) {
        visitClosureExpression((ClosureExpression) last);
    } else if (last instanceof MethodNode) {
        visitMethod((MethodNode) last);
    } else if (last instanceof ConstructorNode) {
        visitConstructor((ConstructorNode) last);
    } else if (last instanceof ForStatement) {
        visitForLoop((ForStatement) last);
    } else if (last instanceof BlockStatement) {
        visitBlockStatement((BlockStatement) last);
    } else if (last instanceof ClosureListExpression) {
        visitClosureListExpression((ClosureListExpression) last);
    } else if (last instanceof CatchStatement) {
        visitCatchStatement((CatchStatement) last);
    }

}