Search in sources :

Example 81 with ASTRewriteCorrectionProposal

use of org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal in project che by eclipse.

the class ReturnTypeQuickFixTest method testMissingReturnStatement.

@Test
public void testMissingReturnStatement() throws Exception {
    IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
    StringBuffer buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("public class E {\n");
    buf.append("    public int[][] getArray() {\n");
    buf.append("    }\n");
    buf.append("}\n");
    ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
    CompilationUnit astRoot = getASTRoot(cu);
    ArrayList proposals = collectCorrections(cu, astRoot);
    assertNumberOfProposals(proposals, 2);
    assertCorrectLabels(proposals);
    ASTRewriteCorrectionProposal proposal = (ASTRewriteCorrectionProposal) proposals.get(0);
    String preview1 = getPreviewContent(proposal);
    buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("public class E {\n");
    buf.append("    public int[][] getArray() {\n");
    buf.append("        return null;\n");
    buf.append("    }\n");
    buf.append("}\n");
    String expected1 = buf.toString();
    proposal = (ASTRewriteCorrectionProposal) proposals.get(1);
    String preview2 = getPreviewContent(proposal);
    buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("public class E {\n");
    buf.append("    public void getArray() {\n");
    buf.append("    }\n");
    buf.append("}\n");
    String expected2 = buf.toString();
    assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 82 with ASTRewriteCorrectionProposal

use of org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal in project che by eclipse.

the class TypeMismatchQuickFixTests method testMismatchingReturnTypeOnWildcardExtends.

@Test
public void testMismatchingReturnTypeOnWildcardExtends() throws Exception {
    IPackageFragment pack1 = fSourceFolder.createPackageFragment("test1", false, null);
    StringBuffer buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("import java.util.ArrayList;\n");
    buf.append("public class E {\n");
    buf.append("    public Integer getIt(ArrayList<? extends Number> b) {\n");
    buf.append("        return b.get(0);\n");
    buf.append("    }\n");
    buf.append("}\n");
    ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
    CompilationUnit astRoot = getASTRoot(cu);
    ArrayList proposals = collectCorrections(cu, astRoot);
    assertNumberOfProposals(proposals, 2);
    assertCorrectLabels(proposals);
    ASTRewriteCorrectionProposal proposal = (ASTRewriteCorrectionProposal) proposals.get(0);
    String preview1 = getPreviewContent(proposal);
    buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("import java.util.ArrayList;\n");
    buf.append("public class E {\n");
    buf.append("    public Number getIt(ArrayList<? extends Number> b) {\n");
    buf.append("        return b.get(0);\n");
    buf.append("    }\n");
    buf.append("}\n");
    String expected1 = buf.toString();
    proposal = (ASTRewriteCorrectionProposal) proposals.get(1);
    String preview2 = getPreviewContent(proposal);
    buf = new StringBuffer();
    buf.append("package test1;\n");
    buf.append("import java.util.ArrayList;\n");
    buf.append("public class E {\n");
    buf.append("    public Integer getIt(ArrayList<? extends Number> b) {\n");
    buf.append("        return (Integer) b.get(0);\n");
    buf.append("    }\n");
    buf.append("}\n");
    String expected2 = buf.toString();
    assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 83 with ASTRewriteCorrectionProposal

use of org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal in project che by eclipse.

the class AdvancedQuickAssistProcessor method getJoinIfListInIfElseIfProposals.

private static boolean getJoinIfListInIfElseIfProposals(IInvocationContext context, ASTNode covering, ArrayList<ASTNode> coveredNodes, Collection<ICommandAccess> resultingCollections) {
    if (coveredNodes.isEmpty()) {
        return false;
    }
    // check that we have more than one covered statement
    if (coveredNodes.size() < 2) {
        return false;
    }
    // check that all selected nodes are 'if' statements with only 'then' statement
    for (Iterator<ASTNode> iter = coveredNodes.iterator(); iter.hasNext(); ) {
        ASTNode node = iter.next();
        if (!(node instanceof IfStatement)) {
            return false;
        }
        IfStatement ifStatement = (IfStatement) node;
        if (ifStatement.getElseStatement() != null) {
            return false;
        }
    }
    //  we could produce quick assist
    if (resultingCollections == null) {
        return true;
    }
    //
    final AST ast = covering.getAST();
    final ASTRewrite rewrite = ASTRewrite.create(ast);
    //
    IfStatement firstIfStatement = (IfStatement) coveredNodes.get(0);
    IfStatement firstNewIfStatement = null;
    //
    IfStatement prevIfStatement = null;
    for (Iterator<ASTNode> iter = coveredNodes.iterator(); iter.hasNext(); ) {
        IfStatement ifStatement = (IfStatement) iter.next();
        // prepare new 'if' statement
        IfStatement newIfStatement = ast.newIfStatement();
        newIfStatement.setExpression((Expression) rewrite.createMoveTarget(ifStatement.getExpression()));
        // prepare 'then' statement and convert into block if needed
        Statement thenStatement = (Statement) rewrite.createMoveTarget(ifStatement.getThenStatement());
        if (ifStatement.getThenStatement() instanceof IfStatement) {
            IfStatement ifBodyStatement = (IfStatement) ifStatement.getThenStatement();
            if (ifBodyStatement.getElseStatement() == null) {
                Block thenBlock = ast.newBlock();
                thenBlock.statements().add(thenStatement);
                thenStatement = thenBlock;
            }
        }
        newIfStatement.setThenStatement(thenStatement);
        //
        if (prevIfStatement != null) {
            prevIfStatement.setElseStatement(newIfStatement);
            rewrite.remove(ifStatement, null);
        } else {
            firstNewIfStatement = newIfStatement;
        }
        prevIfStatement = newIfStatement;
    }
    rewrite.replace(firstIfStatement, firstNewIfStatement, null);
    // add correction proposal
    String label = CorrectionMessages.AdvancedQuickAssistProcessor_joinIfSequence;
    Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.JOIN_IF_SEQUENCE, image);
    resultingCollections.add(proposal);
    return true;
}
Also used : ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Image(org.eclipse.swt.graphics.Image)

Example 84 with ASTRewriteCorrectionProposal

use of org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal in project che by eclipse.

the class AdvancedQuickAssistProcessor method getInverseIfProposals.

private static boolean getInverseIfProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
    if (!(covering instanceof IfStatement)) {
        return false;
    }
    IfStatement ifStatement = (IfStatement) covering;
    if (ifStatement.getElseStatement() == null) {
        return false;
    }
    //  we could produce quick assist
    if (resultingCollections == null) {
        return true;
    }
    //
    AST ast = covering.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    Statement thenStatement = ifStatement.getThenStatement();
    Statement elseStatement = ifStatement.getElseStatement();
    // prepare original nodes
    Expression inversedExpression = getInversedExpression(rewrite, ifStatement.getExpression());
    Statement newElseStatement = (Statement) rewrite.createMoveTarget(thenStatement);
    Statement newThenStatement = (Statement) rewrite.createMoveTarget(elseStatement);
    // set new nodes
    rewrite.set(ifStatement, IfStatement.EXPRESSION_PROPERTY, inversedExpression, null);
    if (elseStatement instanceof IfStatement) {
        // bug 79507 && bug 74580
        Block elseBlock = ast.newBlock();
        elseBlock.statements().add(newThenStatement);
        newThenStatement = elseBlock;
    }
    rewrite.set(ifStatement, IfStatement.THEN_STATEMENT_PROPERTY, newThenStatement, null);
    rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, newElseStatement, null);
    // add correction proposal
    String label = CorrectionMessages.AdvancedQuickAssistProcessor_inverseIf_description;
    Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERSE_IF_STATEMENT, image);
    resultingCollections.add(proposal);
    return true;
}
Also used : ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Image(org.eclipse.swt.graphics.Image)

Example 85 with ASTRewriteCorrectionProposal

use of org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal in project che by eclipse.

the class AdvancedQuickAssistProcessor method getConvertSwitchToIfProposals.

private static boolean getConvertSwitchToIfProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections, boolean preserveNPE) {
    final AST ast = covering.getAST();
    final ASTRewrite rewrite = ASTRewrite.create(ast);
    final ImportRewrite importRewrite = StubUtility.createImportRewrite(context.getASTRoot(), true);
    //
    SwitchStatement switchStatement = (SwitchStatement) covering;
    ITypeBinding expressionType = switchStatement.getExpression().resolveTypeBinding();
    //$NON-NLS-1$
    boolean isStringsInSwitch = expressionType != null && "java.lang.String".equals(expressionType.getQualifiedName());
    if (!isStringsInSwitch && preserveNPE)
        return false;
    IfStatement firstIfStatement = null;
    IfStatement currentIfStatement = null;
    Block currentBlock = null;
    boolean hasStopAsLastExecutableStatement = false;
    Block defaultBlock = null;
    Expression currentCondition = null;
    boolean defaultFound = false;
    ArrayList<Block> allBlocks = new ArrayList<Block>();
    ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(covering), importRewrite);
    Expression switchExpression = switchStatement.getExpression();
    Name varName;
    VariableDeclarationStatement variableDeclarationStatement = null;
    if (switchExpression instanceof Name) {
        varName = (Name) switchExpression;
    } else {
        // Switch expression could have side effects, see bug 252040
        VariableDeclarationFragment variableDeclarationFragment = ast.newVariableDeclarationFragment();
        String[] varNames = StubUtility.getVariableNameSuggestions(NamingConventions.VK_LOCAL, context.getCompilationUnit().getJavaProject(), expressionType, switchExpression, null);
        varName = ast.newSimpleName(varNames[0]);
        variableDeclarationFragment.setName((SimpleName) varName);
        variableDeclarationFragment.setStructuralProperty(VariableDeclarationFragment.INITIALIZER_PROPERTY, rewrite.createCopyTarget(switchExpression));
        variableDeclarationStatement = ast.newVariableDeclarationStatement(variableDeclarationFragment);
        Type type = importRewrite.addImport(expressionType, ast, importRewriteContext);
        variableDeclarationStatement.setType(type);
    }
    for (Iterator<Statement> iter = switchStatement.statements().iterator(); iter.hasNext(); ) {
        Statement statement = iter.next();
        if (statement instanceof SwitchCase) {
            SwitchCase switchCase = (SwitchCase) statement;
            // special case: pass through
            if (currentBlock != null) {
                if (!hasStopAsLastExecutableStatement) {
                    return false;
                }
                currentBlock = null;
            }
            if (defaultFound) {
                // This gets too complicated. We only support 'default' as last SwitchCase.
                return false;
            }
            if (switchCase.isDefault()) {
                defaultFound = true;
            }
            // prepare condition (is null for 'default')
            Expression switchCaseCondition = createSwitchCaseCondition(ast, rewrite, importRewrite, importRewriteContext, varName, switchCase, isStringsInSwitch, preserveNPE);
            if (currentCondition == null) {
                currentCondition = switchCaseCondition;
            } else {
                InfixExpression condition = ast.newInfixExpression();
                condition.setOperator(InfixExpression.Operator.CONDITIONAL_OR);
                condition.setLeftOperand(currentCondition);
                if (switchCaseCondition == null)
                    switchCaseCondition = ast.newBooleanLiteral(true);
                condition.setRightOperand(switchCaseCondition);
                currentCondition = condition;
            }
        } else {
            // ensure that current block exists as 'then' statement of 'if'
            if (currentBlock == null) {
                if (currentCondition != null) {
                    IfStatement ifStatement;
                    if (firstIfStatement == null) {
                        firstIfStatement = ast.newIfStatement();
                        ifStatement = firstIfStatement;
                    } else {
                        ifStatement = ast.newIfStatement();
                        currentIfStatement.setElseStatement(ifStatement);
                    }
                    currentIfStatement = ifStatement;
                    ifStatement.setExpression(currentCondition);
                    currentCondition = null;
                    currentBlock = ast.newBlock();
                    ifStatement.setThenStatement(currentBlock);
                    allBlocks.add(currentBlock);
                } else {
                    // case for default:
                    defaultBlock = ast.newBlock();
                    currentBlock = defaultBlock;
                    allBlocks.add(currentBlock);
                // delay adding of default block
                }
            }
            if (statement instanceof BreakStatement) {
                currentBlock = null;
            } else {
                // add current statement in current block
                hasStopAsLastExecutableStatement = hasStopAsLastExecutableStatement(statement);
                Statement copyStatement = copyStatementExceptBreak(ast, rewrite, statement);
                currentBlock.statements().add(copyStatement);
            }
        }
    }
    // check, may be we have delayed default block
    if (defaultBlock != null) {
        currentIfStatement.setElseStatement(defaultBlock);
    }
    // remove unnecessary blocks in blocks
    for (int i = 0; i < allBlocks.size(); i++) {
        Block block = allBlocks.get(i);
        List<Statement> statements = block.statements();
        if (statements.size() == 1 && statements.get(0) instanceof Block) {
            Block innerBlock = (Block) statements.remove(0);
            block.getParent().setStructuralProperty(block.getLocationInParent(), innerBlock);
        }
    }
    if (variableDeclarationStatement == null) {
        // replace 'switch' with single if-else-if statement
        rewrite.replace(switchStatement, firstIfStatement, null);
    } else {
        new StatementRewrite(rewrite, new ASTNode[] { switchStatement }).replace(new ASTNode[] { variableDeclarationStatement, firstIfStatement }, null);
    }
    // add correction proposal
    //$NON-NLS-1$ //$NON-NLS-2$
    String source = ASTNodes.asString(switchExpression).replaceAll("\r\n?|\n", " ");
    String label = preserveNPE ? Messages.format(CorrectionMessages.AdvancedQuickAssistProcessor_convertSwitchToIf_preserveNPE, source) : CorrectionMessages.AdvancedQuickAssistProcessor_convertSwitchToIf;
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_SWITCH_TO_IF_ELSE);
    proposal.setImportRewrite(importRewrite);
    resultingCollections.add(proposal);
    return true;
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) ArrayList(java.util.ArrayList) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) StatementRewrite(org.eclipse.jdt.internal.corext.dom.StatementRewrite) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)

Aggregations

ASTRewriteCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal)125 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)93 Image (org.eclipse.swt.graphics.Image)70 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)49 AST (org.eclipse.jdt.core.dom.AST)38 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)35 ASTNode (org.eclipse.jdt.core.dom.ASTNode)33 Expression (org.eclipse.jdt.core.dom.Expression)32 ArrayList (java.util.ArrayList)29 CastExpression (org.eclipse.jdt.core.dom.CastExpression)24 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)23 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)23 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)23 Test (org.junit.Test)23 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)21 LambdaExpression (org.eclipse.jdt.core.dom.LambdaExpression)21 Block (org.eclipse.jdt.core.dom.Block)19 ConditionalExpression (org.eclipse.jdt.core.dom.ConditionalExpression)19 PrefixExpression (org.eclipse.jdt.core.dom.PrefixExpression)19 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)19