Search in sources :

Example 6 with VariableDeclarationFragment

use of org.eclipse.jdt.core.dom.VariableDeclarationFragment in project flux by eclipse.

the class AdvancedQuickAssistProcessor method getCastAndAssignIfStatementProposals.

private static boolean getCastAndAssignIfStatementProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
    if (node instanceof IfStatement) {
        node = ((IfStatement) node).getExpression();
    } else if (node instanceof WhileStatement) {
        node = ((WhileStatement) node).getExpression();
    } else if (node instanceof Block) {
        List<Statement> statements = ((Block) node).statements();
        if (statements.size() > 0) {
            if (context.getSelectionOffset() > statements.get(0).getStartPosition()) {
                return false;
            }
        }
        ASTNode parent = node.getParent();
        Expression expression = null;
        if (parent instanceof IfStatement) {
            expression = ((IfStatement) parent).getExpression();
        } else if (parent instanceof WhileStatement) {
            expression = ((WhileStatement) parent).getExpression();
        } else {
            return false;
        }
        if (expression instanceof InstanceofExpression) {
            node = expression;
        } else {
            final ArrayList<InstanceofExpression> nodes = new ArrayList<InstanceofExpression>();
            expression.accept(new ASTVisitor() {

                @Override
                public boolean visit(InstanceofExpression instanceofExpression) {
                    nodes.add(instanceofExpression);
                    return false;
                }
            });
            if (nodes.size() != 1) {
                return false;
            }
            node = nodes.get(0);
        }
    } else {
        while (node != null && !(node instanceof InstanceofExpression) && !(node instanceof Statement)) {
            node = node.getParent();
        }
    }
    if (!(node instanceof InstanceofExpression)) {
        return false;
    }
    InstanceofExpression expression = (InstanceofExpression) node;
    // test that we are the expression of a 'while' or 'if'
    while (node.getParent() instanceof Expression) {
        node = node.getParent();
    }
    StructuralPropertyDescriptor locationInParent = node.getLocationInParent();
    boolean negated = isNegated(expression);
    Statement body = null;
    ASTNode insertionPosition = null;
    if (negated) {
        insertionPosition = node.getParent();
        if (locationInParent == IfStatement.EXPRESSION_PROPERTY) {
            body = ((IfStatement) node.getParent()).getElseStatement();
            if (body != null) {
                negated = false;
            }
        }
        if (body == null && insertionPosition.getParent() instanceof Block) {
            body = (Statement) insertionPosition.getParent();
        }
    } else {
        if (locationInParent == IfStatement.EXPRESSION_PROPERTY) {
            body = ((IfStatement) node.getParent()).getThenStatement();
        } else if (locationInParent == WhileStatement.EXPRESSION_PROPERTY) {
            body = ((WhileStatement) node.getParent()).getBody();
        }
    }
    if (body == null) {
        return false;
    }
    Type originalType = expression.getRightOperand();
    if (originalType.resolveBinding() == null) {
        return false;
    }
    //  we could produce quick assist
    if (resultingCollections == null) {
        return true;
    }
    //$NON-NLS-1$
    final String KEY_NAME = "name";
    //$NON-NLS-1$
    final String KEY_TYPE = "type";
    //
    AST ast = expression.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    ICompilationUnit cu = context.getCompilationUnit();
    // prepare correction proposal
    String label = CorrectionMessages.AdvancedQuickAssistProcessor_castAndAssign;
    //		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
    LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.CAST_AND_ASSIGN);
    // prepare possible variable names
    List<String> excludedNames = Arrays.asList(ASTResolving.getUsedVariableNames(body));
    String[] varNames = suggestLocalVariableNames(cu, originalType.resolveBinding(), excludedNames);
    for (int i = 0; i < varNames.length; i++) {
        proposal.addLinkedPositionProposal(KEY_NAME, varNames[i], null);
    }
    CastExpression castExpression = ast.newCastExpression();
    castExpression.setExpression((Expression) rewrite.createCopyTarget(expression.getLeftOperand()));
    castExpression.setType((Type) ASTNode.copySubtree(ast, originalType));
    // prepare new variable declaration
    VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment();
    vdf.setName(ast.newSimpleName(varNames[0]));
    vdf.setInitializer(castExpression);
    // prepare new variable declaration statement
    VariableDeclarationStatement vds = ast.newVariableDeclarationStatement(vdf);
    vds.setType((Type) ASTNode.copySubtree(ast, originalType));
    // add new variable declaration statement
    if (negated) {
        ListRewrite listRewriter = rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY);
        listRewriter.insertAfter(vds, insertionPosition, null);
    } else {
        if (body instanceof Block) {
            ListRewrite listRewriter = rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY);
            listRewriter.insertAt(vds, 0, null);
        } else {
            Block newBlock = ast.newBlock();
            List<Statement> statements = newBlock.statements();
            statements.add(vds);
            statements.add((Statement) rewrite.createMoveTarget(body));
            rewrite.replace(body, newBlock, null);
        }
    }
    // setup linked positions
    proposal.addLinkedPosition(rewrite.track(vdf.getName()), true, KEY_NAME);
    proposal.addLinkedPosition(rewrite.track(vds.getType()), false, KEY_TYPE);
    proposal.addLinkedPosition(rewrite.track(castExpression.getType()), false, KEY_TYPE);
    // set cursor after expression statement
    proposal.setEndPosition(rewrite.track(vds));
    // add correction proposal
    resultingCollections.add(proposal);
    return true;
}
Also used : ArrayList(java.util.ArrayList) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) IfStatement(org.eclipse.jdt.core.dom.IfStatement) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) InstanceofExpression(org.eclipse.jdt.core.dom.InstanceofExpression) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) DoStatement(org.eclipse.jdt.core.dom.DoStatement) Statement(org.eclipse.jdt.core.dom.Statement) ContinueStatement(org.eclipse.jdt.core.dom.ContinueStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) AssertStatement(org.eclipse.jdt.core.dom.AssertStatement) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) BreakStatement(org.eclipse.jdt.core.dom.BreakStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ASTVisitor(org.eclipse.jdt.core.dom.ASTVisitor) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ConditionalExpression(org.eclipse.jdt.core.dom.ConditionalExpression) InstanceofExpression(org.eclipse.jdt.core.dom.InstanceofExpression) Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) CastExpression(org.eclipse.jdt.core.dom.CastExpression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) PrefixExpression(org.eclipse.jdt.core.dom.PrefixExpression) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) Block(org.eclipse.jdt.core.dom.Block) CastExpression(org.eclipse.jdt.core.dom.CastExpression) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor)

Example 7 with VariableDeclarationFragment

use of org.eclipse.jdt.core.dom.VariableDeclarationFragment in project flux by eclipse.

the class ModifierChangeCorrectionProposal method getRewrite.

@Override
protected ASTRewrite getRewrite() throws CoreException {
    CompilationUnit astRoot = ASTResolving.findParentCompilationUnit(fNode);
    ASTNode boundNode = astRoot.findDeclaringNode(fBinding);
    ASTNode declNode = null;
    if (boundNode != null) {
        // is same CU
        declNode = boundNode;
    } else {
        //setSelectionDescription(selectionDescription);
        CompilationUnit newRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
        declNode = newRoot.findDeclaringNode(fBinding.getKey());
    }
    if (declNode != null) {
        AST ast = declNode.getAST();
        ASTRewrite rewrite = ASTRewrite.create(ast);
        if (declNode.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
            VariableDeclarationFragment fragment = (VariableDeclarationFragment) declNode;
            ASTNode parent = declNode.getParent();
            if (parent instanceof FieldDeclaration) {
                FieldDeclaration fieldDecl = (FieldDeclaration) parent;
                if (fieldDecl.fragments().size() > 1 && (fieldDecl.getParent() instanceof AbstractTypeDeclaration)) {
                    // split
                    VariableDeclarationRewrite.rewriteModifiers(fieldDecl, new VariableDeclarationFragment[] { fragment }, fIncludedModifiers, fExcludedModifiers, rewrite, null);
                    return rewrite;
                }
            } else if (parent instanceof VariableDeclarationStatement) {
                VariableDeclarationStatement varDecl = (VariableDeclarationStatement) parent;
                if (varDecl.fragments().size() > 1 && (varDecl.getParent() instanceof Block)) {
                    // split
                    VariableDeclarationRewrite.rewriteModifiers(varDecl, new VariableDeclarationFragment[] { fragment }, fIncludedModifiers, fExcludedModifiers, rewrite, null);
                    return rewrite;
                }
            } else if (parent instanceof VariableDeclarationExpression) {
            // can't separate
            }
            declNode = parent;
        } else if (declNode.getNodeType() == ASTNode.METHOD_DECLARATION) {
            MethodDeclaration methodDecl = (MethodDeclaration) declNode;
            if (!methodDecl.isConstructor()) {
                IMethodBinding methodBinding = methodDecl.resolveBinding();
                if (methodDecl.getBody() == null && methodBinding != null && Modifier.isAbstract(methodBinding.getModifiers()) && Modifier.isStatic(fIncludedModifiers)) {
                    // add body
                    ICompilationUnit unit = getCompilationUnit();
                    String delimiter = unit.findRecommendedLineSeparator();
                    //$NON-NLS-1$
                    String bodyStatement = "";
                    Block body = ast.newBlock();
                    rewrite.set(methodDecl, MethodDeclaration.BODY_PROPERTY, body, null);
                    Type returnType = methodDecl.getReturnType2();
                    if (returnType != null) {
                        Expression expression = ASTNodeFactory.newDefaultExpression(ast, returnType, methodDecl.getExtraDimensions());
                        if (expression != null) {
                            ReturnStatement returnStatement = ast.newReturnStatement();
                            returnStatement.setExpression(expression);
                            bodyStatement = ASTNodes.asFormattedString(returnStatement, 0, delimiter, unit.getJavaProject().getOptions(true));
                        }
                    }
                    String placeHolder = CodeGeneration.getMethodBodyContent(unit, methodBinding.getDeclaringClass().getName(), methodBinding.getName(), false, bodyStatement, delimiter);
                    if (placeHolder != null) {
                        ReturnStatement todoNode = (ReturnStatement) rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
                        body.statements().add(todoNode);
                    }
                }
            }
        }
        ModifierRewrite listRewrite = ModifierRewrite.create(rewrite, declNode);
        PositionInformation trackedDeclNode = listRewrite.setModifiers(fIncludedModifiers, fExcludedModifiers, null);
        //$NON-NLS-1$
        LinkedProposalPositionGroup positionGroup = new LinkedProposalPositionGroup("group");
        positionGroup.addPosition(trackedDeclNode);
        getLinkedProposalModel().addPositionGroup(positionGroup);
        if (boundNode != null) {
            // only set end position if in same CU
            setEndPosition(rewrite.track(fNode));
        }
        return rewrite;
    }
    return null;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ModifierRewrite(org.eclipse.jdt.internal.corext.dom.ModifierRewrite) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) PositionInformation(org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroup.PositionInformation) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) Type(org.eclipse.jdt.core.dom.Type) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) Block(org.eclipse.jdt.core.dom.Block) LinkedProposalPositionGroup(org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroup) AbstractTypeDeclaration(org.eclipse.jdt.core.dom.AbstractTypeDeclaration)

Example 8 with VariableDeclarationFragment

use of org.eclipse.jdt.core.dom.VariableDeclarationFragment in project che by eclipse.

the class RenameFieldProcessor method addDelegates.

private RefactoringStatus addDelegates() throws JavaModelException, CoreException {
    RefactoringStatus status = new RefactoringStatus();
    CompilationUnitRewrite rewrite = new CompilationUnitRewrite(fField.getCompilationUnit());
    rewrite.setResolveBindings(true);
    // add delegate for the field
    if (RefactoringAvailabilityTester.isDelegateCreationAvailable(fField)) {
        FieldDeclaration fieldDeclaration = ASTNodeSearchUtil.getFieldDeclarationNode(fField, rewrite.getRoot());
        if (fieldDeclaration.fragments().size() > 1) {
            status.addWarning(Messages.format(RefactoringCoreMessages.DelegateCreator_cannot_create_field_delegate_more_than_one_fragment, BasicElementLabels.getJavaElementName(fField.getElementName())), JavaStatusContext.create(fField));
        } else if (((VariableDeclarationFragment) fieldDeclaration.fragments().get(0)).getInitializer() == null) {
            status.addWarning(Messages.format(RefactoringCoreMessages.DelegateCreator_cannot_create_field_delegate_no_initializer, BasicElementLabels.getJavaElementName(fField.getElementName())), JavaStatusContext.create(fField));
        } else {
            DelegateFieldCreator creator = new DelegateFieldCreator();
            creator.setDeclareDeprecated(fDelegateDeprecation);
            creator.setDeclaration(fieldDeclaration);
            creator.setNewElementName(getNewElementName());
            creator.setSourceRewrite(rewrite);
            creator.prepareDelegate();
            creator.createEdit();
        }
    }
    // there may be getters even if the field is static final
    if (getGetter() != null && fRenameGetter)
        addMethodDelegate(getGetter(), getNewGetterName(), rewrite);
    if (getSetter() != null && fRenameSetter)
        addMethodDelegate(getSetter(), getNewSetterName(), rewrite);
    final CompilationUnitChange change = rewrite.createChange(true);
    if (change != null) {
        change.setKeepPreviewEdits(true);
        fChangeManager.manage(fField.getCompilationUnit(), change);
    }
    return status;
}
Also used : CompilationUnitRewrite(org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) DelegateFieldCreator(org.eclipse.jdt.internal.corext.refactoring.delegates.DelegateFieldCreator) RefactoringStatus(org.eclipse.ltk.core.refactoring.RefactoringStatus) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) CompilationUnitChange(org.eclipse.jdt.core.refactoring.CompilationUnitChange)

Example 9 with VariableDeclarationFragment

use of org.eclipse.jdt.core.dom.VariableDeclarationFragment in project che by eclipse.

the class ExtractToNullCheckedLocalProposal method getRewrite.

@Override
protected ASTRewrite getRewrite() throws CoreException {
    // infrastructure:
    AST ast = this.compilationUnit.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    ImportRewrite imports = ImportRewrite.create(this.compilationUnit, true);
    TextEditGroup group = new TextEditGroup(FixMessages.ExtractToNullCheckedLocalProposal_extractCheckedLocal_editName);
    LinkedProposalPositionGroup localNameGroup = new LinkedProposalPositionGroup(LOCAL_NAME_POSITION_GROUP);
    getLinkedProposalModel().addPositionGroup(localNameGroup);
    // AST context:
    Statement origStmt = (Statement) ASTNodes.getParent(this.fieldReference, Statement.class);
    // determine suitable strategy for rearranging elements towards a new code structure:
    RearrangeStrategy rearrangeStrategy = RearrangeStrategy.create(origStmt, rewrite, group);
    Expression toReplace;
    ASTNode directParent = this.fieldReference.getParent();
    if (directParent instanceof FieldAccess) {
        toReplace = (Expression) directParent;
    } else if (directParent instanceof QualifiedName && this.fieldReference.getLocationInParent() == QualifiedName.NAME_PROPERTY) {
        toReplace = (Expression) directParent;
    } else {
        toReplace = this.fieldReference;
    }
    // new local declaration initialized from the field reference
    VariableDeclarationFragment localFrag = ast.newVariableDeclarationFragment();
    VariableDeclarationStatement localDecl = ast.newVariableDeclarationStatement(localFrag);
    // ... type
    localDecl.setType(newType(toReplace.resolveTypeBinding(), ast, imports));
    localDecl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD));
    // ... name
    String localName = proposeLocalName(this.fieldReference, this.compilationUnit, getCompilationUnit().getJavaProject());
    localFrag.setName(ast.newSimpleName(localName));
    // ... initialization
    localFrag.setInitializer((Expression) ASTNode.copySubtree(ast, toReplace));
    rearrangeStrategy.insertLocalDecl(localDecl);
    // if statement:
    IfStatement ifStmt = ast.newIfStatement();
    // condition:
    InfixExpression nullCheck = ast.newInfixExpression();
    nullCheck.setLeftOperand(ast.newSimpleName(localName));
    nullCheck.setRightOperand(ast.newNullLiteral());
    nullCheck.setOperator(InfixExpression.Operator.NOT_EQUALS);
    ifStmt.setExpression(nullCheck);
    // then block: the original statement
    Block thenBlock = ast.newBlock();
    thenBlock.statements().add(rearrangeStrategy.createMoveTargetForOrigStmt());
    ifStmt.setThenStatement(thenBlock);
    // ... but with the field reference replaced by the new local:
    SimpleName dereferencedName = ast.newSimpleName(localName);
    rewrite.replace(toReplace, dereferencedName, group);
    // else block: a Todo comment
    Block elseBlock = ast.newBlock();
    //$NON-NLS-1$
    String elseStatement = "// TODO " + FixMessages.ExtractToNullCheckedLocalProposal_todoHandleNullDescription;
    if (origStmt instanceof ReturnStatement) {
        Type returnType = newType(((ReturnStatement) origStmt).getExpression().resolveTypeBinding(), ast, imports);
        ReturnStatement returnStatement = ast.newReturnStatement();
        returnStatement.setExpression(ASTNodeFactory.newDefaultExpression(ast, returnType, 0));
        elseStatement += '\n' + ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true));
    }
    EmptyStatement todoNode = (EmptyStatement) rewrite.createStringPlaceholder(elseStatement, ASTNode.EMPTY_STATEMENT);
    elseBlock.statements().add(todoNode);
    ifStmt.setElseStatement(elseBlock);
    // link all three occurrences of the new local variable:
    addLinkedPosition(rewrite.track(localFrag.getName()), true, /*first*/
    LOCAL_NAME_POSITION_GROUP);
    addLinkedPosition(rewrite.track(nullCheck.getLeftOperand()), false, LOCAL_NAME_POSITION_GROUP);
    addLinkedPosition(rewrite.track(dereferencedName), false, LOCAL_NAME_POSITION_GROUP);
    rearrangeStrategy.insertIfStatement(ifStmt, thenBlock);
    return rewrite;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) Statement(org.eclipse.jdt.core.dom.Statement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) EmptyStatement(org.eclipse.jdt.core.dom.EmptyStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) SimpleName(org.eclipse.jdt.core.dom.SimpleName) EmptyStatement(org.eclipse.jdt.core.dom.EmptyStatement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) Expression(org.eclipse.jdt.core.dom.Expression) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ASTNode(org.eclipse.jdt.core.dom.ASTNode) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) Block(org.eclipse.jdt.core.dom.Block) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) TextEditGroup(org.eclipse.text.edits.TextEditGroup) LinkedProposalPositionGroup(org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroup)

Example 10 with VariableDeclarationFragment

use of org.eclipse.jdt.core.dom.VariableDeclarationFragment in project che by eclipse.

the class GenerateForLoopAssistProposal method getIndexBasedForBodyAssignment.

/**
	 * Creates an {@link Assignment} as first expression appearing in an index based
	 * <code>for</code> loop's body. This Assignment declares a local variable and initializes it
	 * using the {@link List}'s current element identified by the loop index.
	 * 
	 * @param rewrite the current {@link ASTRewrite} instance
	 * @param loopVariableName the name of the index variable in String representation
	 * @return a completed {@link Assignment} containing the mentioned declaration and
	 *         initialization
	 */
private Expression getIndexBasedForBodyAssignment(ASTRewrite rewrite, SimpleName loopVariableName) {
    AST ast = rewrite.getAST();
    ITypeBinding loopOverType = extractElementType(ast);
    Assignment assignResolvedVariable = ast.newAssignment();
    // left hand side
    SimpleName resolvedVariableName = resolveLinkedVariableNameWithProposals(rewrite, loopOverType.getName(), loopVariableName.getIdentifier(), false);
    VariableDeclarationFragment resolvedVariableDeclarationFragment = ast.newVariableDeclarationFragment();
    resolvedVariableDeclarationFragment.setName(resolvedVariableName);
    VariableDeclarationExpression resolvedVariableDeclaration = ast.newVariableDeclarationExpression(resolvedVariableDeclarationFragment);
    resolvedVariableDeclaration.setType(getImportRewrite().addImport(loopOverType, ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite())));
    assignResolvedVariable.setLeftHandSide(resolvedVariableDeclaration);
    // right hand side
    MethodInvocation invokeGetExpression = ast.newMethodInvocation();
    //$NON-NLS-1$
    invokeGetExpression.setName(ast.newSimpleName("get"));
    SimpleName indexVariableName = ast.newSimpleName(loopVariableName.getIdentifier());
    addLinkedPosition(rewrite.track(indexVariableName), LinkedPositionGroup.NO_STOP, indexVariableName.getIdentifier());
    invokeGetExpression.arguments().add(indexVariableName);
    invokeGetExpression.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression));
    assignResolvedVariable.setRightHandSide(invokeGetExpression);
    assignResolvedVariable.setOperator(Assignment.Operator.ASSIGN);
    return assignResolvedVariable;
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) AST(org.eclipse.jdt.core.dom.AST) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation)

Aggregations

VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)101 ASTNode (org.eclipse.jdt.core.dom.ASTNode)44 AST (org.eclipse.jdt.core.dom.AST)38 Expression (org.eclipse.jdt.core.dom.Expression)33 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)33 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)30 FieldDeclaration (org.eclipse.jdt.core.dom.FieldDeclaration)28 Assignment (org.eclipse.jdt.core.dom.Assignment)25 SimpleName (org.eclipse.jdt.core.dom.SimpleName)25 Type (org.eclipse.jdt.core.dom.Type)25 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)22 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)21 Block (org.eclipse.jdt.core.dom.Block)17 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)16 ArrayList (java.util.ArrayList)15 CastExpression (org.eclipse.jdt.core.dom.CastExpression)15 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)15 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)15 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)15 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)14