Search in sources :

Example 1 with Statement

use of org.eclipse.jdt.core.dom.Statement 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 2 with Statement

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

the class MissingReturnTypeCorrectionProposal method getRewrite.

/*(non-Javadoc)
	 * @see org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal#getRewrite()
	 */
@Override
protected ASTRewrite getRewrite() {
    AST ast = getAST();
    ITypeBinding returnBinding = getReturnTypeBinding();
    if (fExistingReturn != null) {
        ASTRewrite rewrite = ASTRewrite.create(ast);
        Expression expression = evaluateReturnExpressions(ast, returnBinding, fExistingReturn.getStartPosition());
        if (expression != null) {
            rewrite.set(fExistingReturn, ReturnStatement.EXPRESSION_PROPERTY, expression, null);
            addLinkedPosition(rewrite.track(expression), true, RETURN_EXPRESSION_KEY);
        }
        return rewrite;
    } else {
        ASTRewrite rewrite = ASTRewrite.create(ast);
        ASTNode body = getBody();
        // For lambda the body can be a block or an expression.
        if (body instanceof Block) {
            Block block = (Block) body;
            List<Statement> statements = block.statements();
            int nStatements = statements.size();
            ASTNode lastStatement = null;
            if (nStatements > 0) {
                lastStatement = statements.get(nStatements - 1);
            }
            if (returnBinding != null && lastStatement instanceof ExpressionStatement && lastStatement.getNodeType() != ASTNode.ASSIGNMENT) {
                Expression expression = ((ExpressionStatement) lastStatement).getExpression();
                ITypeBinding binding = expression.resolveTypeBinding();
                if (binding != null && binding.isAssignmentCompatible(returnBinding)) {
                    Expression placeHolder = (Expression) rewrite.createMoveTarget(expression);
                    ReturnStatement returnStatement = ast.newReturnStatement();
                    returnStatement.setExpression(placeHolder);
                    rewrite.replace(lastStatement, returnStatement, null);
                    return rewrite;
                }
            }
            int offset;
            if (lastStatement == null) {
                offset = block.getStartPosition() + 1;
            } else {
                offset = lastStatement.getStartPosition() + lastStatement.getLength();
            }
            ReturnStatement returnStatement = ast.newReturnStatement();
            Expression expression = evaluateReturnExpressions(ast, returnBinding, offset);
            returnStatement.setExpression(expression);
            rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY).insertLast(returnStatement, null);
            addLinkedPosition(rewrite.track(returnStatement.getExpression()), true, RETURN_EXPRESSION_KEY);
        }
        return rewrite;
    }
}
Also used : AST(org.eclipse.jdt.core.dom.AST) Expression(org.eclipse.jdt.core.dom.Expression) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) Statement(org.eclipse.jdt.core.dom.Statement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Block(org.eclipse.jdt.core.dom.Block)

Example 3 with Statement

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

the class NewVariableCorrectionProposal method doAddLocal.

private ASTRewrite doAddLocal(CompilationUnit cu) {
    AST ast = cu.getAST();
    Block body;
    BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(fOriginalNode);
    IBinding targetContext = null;
    if (decl instanceof MethodDeclaration) {
        body = (((MethodDeclaration) decl).getBody());
        targetContext = ((MethodDeclaration) decl).resolveBinding();
    } else if (decl instanceof Initializer) {
        body = (((Initializer) decl).getBody());
        targetContext = Bindings.getBindingOfParentType(decl);
    } else {
        return null;
    }
    ASTRewrite rewrite = ASTRewrite.create(ast);
    ImportRewrite imports = createImportRewrite((CompilationUnit) decl.getRoot());
    SimpleName[] names = getAllReferences(body);
    ASTNode dominant = getDominantNode(names);
    Statement dominantStatement = ASTResolving.findParentStatement(dominant);
    if (ASTNodes.isControlStatementBody(dominantStatement.getLocationInParent())) {
        dominantStatement = (Statement) dominantStatement.getParent();
    }
    SimpleName node = names[0];
    ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, imports);
    if (isAssigned(dominantStatement, node)) {
        // x = 1; -> int x = 1;
        Assignment assignment = (Assignment) node.getParent();
        // trick to avoid comment removal around the statement: keep the expression statement
        // and replace the assignment with an VariableDeclarationExpression
        VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
        VariableDeclarationExpression newDecl = ast.newVariableDeclarationExpression(newDeclFrag);
        newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext));
        Expression placeholder = (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
        newDeclFrag.setInitializer(placeholder);
        newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
        rewrite.replace(assignment, newDecl, null);
        addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
        addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME);
        setEndPosition(rewrite.track(assignment.getParent()));
        return rewrite;
    } else if ((dominant != dominantStatement) && isForStatementInit(dominantStatement, node)) {
        //	for (x = 1;;) ->for (int x = 1;;)
        Assignment assignment = (Assignment) node.getParent();
        VariableDeclarationFragment frag = ast.newVariableDeclarationFragment();
        VariableDeclarationExpression expression = ast.newVariableDeclarationExpression(frag);
        frag.setName(ast.newSimpleName(node.getIdentifier()));
        Expression placeholder = (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
        frag.setInitializer(placeholder);
        expression.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext));
        rewrite.replace(assignment, expression, null);
        addLinkedPosition(rewrite.track(expression.getType()), false, KEY_TYPE);
        addLinkedPosition(rewrite.track(frag.getName()), true, KEY_NAME);
        setEndPosition(rewrite.track(expression));
        return rewrite;
    } else if ((dominant != dominantStatement) && isEnhancedForStatementVariable(dominantStatement, node)) {
        //	for (x: collectionOfT) -> for (T x: collectionOfT)
        EnhancedForStatement enhancedForStatement = (EnhancedForStatement) dominantStatement;
        SingleVariableDeclaration parameter = enhancedForStatement.getParameter();
        Expression expression = enhancedForStatement.getExpression();
        SimpleName newName = (SimpleName) rewrite.createMoveTarget(node);
        rewrite.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, newName, null);
        ITypeBinding elementBinding = null;
        ITypeBinding typeBinding = expression.resolveTypeBinding();
        if (typeBinding != null) {
            if (typeBinding.isArray()) {
                elementBinding = typeBinding.getElementType();
            } else {
                //$NON-NLS-1$
                ITypeBinding iterable = Bindings.findTypeInHierarchy(typeBinding, "java.lang.Iterable");
                if (iterable != null) {
                    ITypeBinding[] typeArguments = iterable.getTypeArguments();
                    if (typeArguments.length == 1) {
                        elementBinding = typeArguments[0];
                        elementBinding = Bindings.normalizeForDeclarationUse(elementBinding, ast);
                    }
                }
            }
        }
        Type type;
        if (elementBinding != null) {
            type = imports.addImport(elementBinding, ast, importRewriteContext);
        } else {
            //$NON-NLS-1$
            type = ast.newSimpleType(ast.newSimpleName("Object"));
        }
        rewrite.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, type, null);
        addLinkedPosition(rewrite.track(type), false, KEY_TYPE);
        addLinkedPosition(rewrite.track(newName), true, KEY_NAME);
        setEndPosition(rewrite.track(expression));
        return rewrite;
    }
    //	foo(x) -> int x; foo(x)
    VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
    VariableDeclarationStatement newDecl = ast.newVariableDeclarationStatement(newDeclFrag);
    newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
    newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext));
    //		newDeclFrag.setInitializer(ASTNodeFactory.newDefaultExpression(ast, newDecl.getType(), 0));
    addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
    addLinkedPosition(rewrite.track(node), true, KEY_NAME);
    addLinkedPosition(rewrite.track(newDeclFrag.getName()), false, KEY_NAME);
    Statement statement = dominantStatement;
    List<? extends ASTNode> list = ASTNodes.getContainingList(statement);
    while (list == null && statement.getParent() instanceof Statement) {
        // parent must be if, for or while
        statement = (Statement) statement.getParent();
        list = ASTNodes.getContainingList(statement);
    }
    if (list != null) {
        ASTNode parent = statement.getParent();
        StructuralPropertyDescriptor childProperty = statement.getLocationInParent();
        if (childProperty.isChildListProperty()) {
            rewrite.getListRewrite(parent, (ChildListPropertyDescriptor) childProperty).insertBefore(newDecl, statement, null);
            return rewrite;
        } else {
            return null;
        }
    }
    return rewrite;
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) IBinding(org.eclipse.jdt.core.dom.IBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Assignment(org.eclipse.jdt.core.dom.Assignment) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Statement(org.eclipse.jdt.core.dom.Statement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Initializer(org.eclipse.jdt.core.dom.Initializer) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) Block(org.eclipse.jdt.core.dom.Block) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) StructuralPropertyDescriptor(org.eclipse.jdt.core.dom.StructuralPropertyDescriptor)

Example 4 with Statement

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

the class GenerateForLoopAssistProposal method createBlankLineStatementWithCursorPosition.

/**
	 * Generates an empty statement, which is shown as blank line and is set as end position for the
	 * cursor.
	 * 
	 * @param rewrite the current {@link ASTRewrite} instance
	 * @return an empty statement, shown as blank line
	 */
private Statement createBlankLineStatementWithCursorPosition(ASTRewrite rewrite) {
    //$NON-NLS-1$
    Statement blankLineStatement = (Statement) rewrite.createStringPlaceholder("", ASTNode.EMPTY_STATEMENT);
    setEndPosition(rewrite.track(blankLineStatement));
    return blankLineStatement;
}
Also used : Statement(org.eclipse.jdt.core.dom.Statement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement)

Example 5 with Statement

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

the class SourceProvider method isDangligIf.

public boolean isDangligIf() {
    List<Statement> statements = fDeclaration.getBody().statements();
    if (statements.size() != 1)
        return false;
    ASTNode p = statements.get(0);
    while (true) {
        if (p instanceof IfStatement) {
            return ((IfStatement) p).getElseStatement() == null;
        } else {
            ChildPropertyDescriptor childD;
            if (p instanceof WhileStatement) {
                childD = WhileStatement.BODY_PROPERTY;
            } else if (p instanceof ForStatement) {
                childD = ForStatement.BODY_PROPERTY;
            } else if (p instanceof EnhancedForStatement) {
                childD = EnhancedForStatement.BODY_PROPERTY;
            } else if (p instanceof DoStatement) {
                childD = DoStatement.BODY_PROPERTY;
            } else if (p instanceof LabeledStatement) {
                childD = LabeledStatement.BODY_PROPERTY;
            } else {
                return false;
            }
            Statement body = (Statement) p.getStructuralProperty(childD);
            if (body instanceof Block) {
                return false;
            } else {
                p = body;
            }
        }
    }
}
Also used : IfStatement(org.eclipse.jdt.core.dom.IfStatement) ChildPropertyDescriptor(org.eclipse.jdt.core.dom.ChildPropertyDescriptor) LabeledStatement(org.eclipse.jdt.core.dom.LabeledStatement) DoStatement(org.eclipse.jdt.core.dom.DoStatement) DoStatement(org.eclipse.jdt.core.dom.DoStatement) Statement(org.eclipse.jdt.core.dom.Statement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) LabeledStatement(org.eclipse.jdt.core.dom.LabeledStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement)

Aggregations

Statement (org.eclipse.jdt.core.dom.Statement)178 IfStatement (org.eclipse.jdt.core.dom.IfStatement)107 ForStatement (org.eclipse.jdt.core.dom.ForStatement)89 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)85 EnhancedForStatement (org.eclipse.jdt.core.dom.EnhancedForStatement)83 WhileStatement (org.eclipse.jdt.core.dom.WhileStatement)77 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)76 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)75 Block (org.eclipse.jdt.core.dom.Block)70 DoStatement (org.eclipse.jdt.core.dom.DoStatement)70 Expression (org.eclipse.jdt.core.dom.Expression)61 SwitchStatement (org.eclipse.jdt.core.dom.SwitchStatement)61 ASTNode (org.eclipse.jdt.core.dom.ASTNode)54 TryStatement (org.eclipse.jdt.core.dom.TryStatement)48 BreakStatement (org.eclipse.jdt.core.dom.BreakStatement)43 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)39 ArrayList (java.util.ArrayList)37 AST (org.eclipse.jdt.core.dom.AST)37 ContinueStatement (org.eclipse.jdt.core.dom.ContinueStatement)34 SimpleName (org.eclipse.jdt.core.dom.SimpleName)34