Search in sources :

Example 61 with ASTRewrite

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

the class AdvancedQuickAssistProcessor method getInverseIfIntoContinueInLoopsProposals.

private static boolean getInverseIfIntoContinueInLoopsProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
    if (!(covering instanceof IfStatement)) {
        return false;
    }
    IfStatement ifStatement = (IfStatement) covering;
    if (ifStatement.getElseStatement() != null) {
        return false;
    }
    // prepare outer control structure and block that contains 'if' statement
    ASTNode ifParent = ifStatement.getParent();
    Block ifParentBlock = null;
    ASTNode ifParentStructure = ifParent;
    if (ifParentStructure instanceof Block) {
        ifParentBlock = (Block) ifParent;
        ifParentStructure = ifParentStructure.getParent();
    }
    // check that control structure is loop and 'if' statement if last statement
    if (!(ifParentStructure instanceof ForStatement) && !(ifParentStructure instanceof WhileStatement)) {
        return false;
    }
    if (ifParentBlock != null && ifParentBlock.statements().indexOf(ifStatement) != ifParentBlock.statements().size() - 1) {
        return false;
    }
    //  we could produce quick assist
    if (resultingCollections == null) {
        return true;
    }
    //
    AST ast = covering.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    // create inverted 'if' statement
    Expression inversedExpression = getInversedExpression(rewrite, ifStatement.getExpression());
    IfStatement newIf = ast.newIfStatement();
    newIf.setExpression(inversedExpression);
    newIf.setThenStatement(ast.newContinueStatement());
    //
    if (ifParentBlock == null) {
        // if there is no block, create it
        ifParentBlock = ast.newBlock();
        ifParentBlock.statements().add(newIf);
        for (Iterator<Statement> iter = getUnwrappedStatements(ifStatement.getThenStatement()).iterator(); iter.hasNext(); ) {
            Statement statement = iter.next();
            ifParentBlock.statements().add(rewrite.createMoveTarget(statement));
        }
        // replace 'if' statement as body with new block
        if (ifParentStructure instanceof ForStatement) {
            rewrite.set(ifParentStructure, ForStatement.BODY_PROPERTY, ifParentBlock, null);
        } else if (ifParentStructure instanceof WhileStatement) {
            rewrite.set(ifParentStructure, WhileStatement.BODY_PROPERTY, ifParentBlock, null);
        }
    } else {
        // if there was block, replace
        ListRewrite listRewriter = rewrite.getListRewrite(ifParentBlock, (ChildListPropertyDescriptor) ifStatement.getLocationInParent());
        listRewriter.replace(ifStatement, newIf, null);
        // add statements from 'then' to the end of block
        for (Iterator<Statement> iter = getUnwrappedStatements(ifStatement.getThenStatement()).iterator(); iter.hasNext(); ) {
            Statement statement = iter.next();
            listRewriter.insertLast(rewrite.createMoveTarget(statement), null);
        }
    }
    // add correction proposal
    String label = CorrectionMessages.AdvancedQuickAssistProcessor_inverseIfToContinue_description;
    Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERT_IF_TO_CONTINUE, image);
    resultingCollections.add(proposal);
    return true;
}
Also used : ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Image(org.eclipse.swt.graphics.Image) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 62 with ASTRewrite

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

the class AdvancedQuickAssistProcessor method getAddParenthesesForExpressionProposals.

private static boolean getAddParenthesesForExpressionProposals(IInvocationContext context, ASTNode coveringNode, Collection<ICommandAccess> resultingCollections) {
    ASTNode node;
    if (context.getSelectionLength() == 0) {
        node = coveringNode;
        while (node != null && !(node instanceof CastExpression) && !(node instanceof InfixExpression) && !(node instanceof InstanceofExpression) && !(node instanceof ConditionalExpression)) {
            node = node.getParent();
        }
    } else {
        node = context.getCoveredNode();
    }
    String label = null;
    if (node instanceof CastExpression) {
        label = CorrectionMessages.UnresolvedElementsSubProcessor_missingcastbrackets_description;
    } else if (node instanceof InstanceofExpression) {
        label = CorrectionMessages.LocalCorrectionsSubProcessor_setparenteses_instanceof_description;
    } else if (node instanceof InfixExpression) {
        InfixExpression infixExpression = (InfixExpression) node;
        label = Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_setparenteses_description, infixExpression.getOperator().toString());
    } else if (node instanceof ConditionalExpression) {
        label = CorrectionMessages.AdvancedQuickAssistProcessor_putConditionalExpressionInParentheses;
    } else {
        return false;
    }
    if (node.getParent() instanceof ParenthesizedExpression)
        return false;
    if (resultingCollections == null)
        return true;
    AST ast = node.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    ParenthesizedExpression parenthesizedExpression = ast.newParenthesizedExpression();
    parenthesizedExpression.setExpression((Expression) rewrite.createCopyTarget(node));
    rewrite.replace(node, parenthesizedExpression, null);
    Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CAST);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_PARENTHESES_FOR_EXPRESSION, 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 63 with ASTRewrite

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

the class AdvancedQuickAssistProcessor method getSplitAndConditionProposals.

public static boolean getSplitAndConditionProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
    Operator andOperator = InfixExpression.Operator.CONDITIONAL_AND;
    // check that user invokes quick assist on infix expression
    if (!(node instanceof InfixExpression)) {
        return false;
    }
    InfixExpression infixExpression = (InfixExpression) node;
    if (infixExpression.getOperator() != andOperator) {
        return false;
    }
    int offset = isOperatorSelected(infixExpression, context.getSelectionOffset(), context.getSelectionLength());
    if (offset == -1) {
        return false;
    }
    // check that infix expression belongs to IfStatement
    Statement statement = ASTResolving.findParentStatement(node);
    if (!(statement instanceof IfStatement)) {
        return false;
    }
    IfStatement ifStatement = (IfStatement) statement;
    // check that infix expression is part of first level && condition of IfStatement
    InfixExpression topInfixExpression = infixExpression;
    while (topInfixExpression.getParent() instanceof InfixExpression && ((InfixExpression) topInfixExpression.getParent()).getOperator() == andOperator) {
        topInfixExpression = (InfixExpression) topInfixExpression.getParent();
    }
    if (ifStatement.getExpression() != topInfixExpression) {
        return false;
    }
    //
    if (resultingCollections == null) {
        return true;
    }
    AST ast = ifStatement.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    // prepare left and right conditions
    Expression[] newOperands = { null, null };
    breakInfixOperationAtOperation(rewrite, topInfixExpression, andOperator, offset, true, newOperands);
    Expression leftCondition = newOperands[0];
    Expression rightCondition = newOperands[1];
    // replace conditions in outer IfStatement
    rewrite.set(ifStatement, IfStatement.EXPRESSION_PROPERTY, leftCondition, null);
    // prepare inner IfStatement
    IfStatement innerIf = ast.newIfStatement();
    innerIf.setExpression(rightCondition);
    innerIf.setThenStatement((Statement) rewrite.createMoveTarget(ifStatement.getThenStatement()));
    Block innerBlock = ast.newBlock();
    innerBlock.statements().add(innerIf);
    Statement elseStatement = ifStatement.getElseStatement();
    if (elseStatement != null) {
        innerIf.setElseStatement((Statement) rewrite.createCopyTarget(elseStatement));
    }
    // replace outer thenStatement
    rewrite.replace(ifStatement.getThenStatement(), innerBlock, null);
    // add correction proposal
    String label = CorrectionMessages.AdvancedQuickAssistProcessor_splitAndCondition_description;
    Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.SPLIT_AND_CONDITION, image);
    resultingCollections.add(proposal);
    return true;
}
Also used : Operator(org.eclipse.jdt.core.dom.InfixExpression.Operator) Image(org.eclipse.swt.graphics.Image) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 64 with ASTRewrite

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

the class AdvancedQuickAssistProcessor method getPickOutStringProposals.

private static boolean getPickOutStringProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
    // we work with String's
    if (!(node instanceof StringLiteral)) {
        return false;
    }
    // user should select part of String
    int selectionPos = context.getSelectionOffset();
    int selectionLen = context.getSelectionLength();
    if (selectionLen == 0) {
        return false;
    }
    int valueStart = node.getStartPosition() + 1;
    int valueEnd = node.getStartPosition() + node.getLength() - 1;
    // selection must be inside node and the quotes and not contain the full value
    if (selectionPos < valueStart || selectionPos + selectionLen > valueEnd || valueEnd - valueStart == selectionLen) {
        return false;
    }
    // prepare string parts positions
    StringLiteral stringLiteral = (StringLiteral) node;
    String stringValue = stringLiteral.getEscapedValue();
    int firstPos = selectionPos - node.getStartPosition();
    int secondPos = firstPos + selectionLen;
    // prepare new string literals
    AST ast = node.getAST();
    StringLiteral leftLiteral = ast.newStringLiteral();
    StringLiteral centerLiteral = ast.newStringLiteral();
    StringLiteral rightLiteral = ast.newStringLiteral();
    try {
        leftLiteral.setEscapedValue('"' + stringValue.substring(1, firstPos) + '"');
        centerLiteral.setEscapedValue('"' + stringValue.substring(firstPos, secondPos) + '"');
        rightLiteral.setEscapedValue('"' + stringValue.substring(secondPos, stringValue.length() - 1) + '"');
    } catch (IllegalArgumentException e) {
        return false;
    }
    if (resultingCollections == null) {
        return true;
    }
    ASTRewrite rewrite = ASTRewrite.create(ast);
    // prepare new expression instead of StringLiteral
    InfixExpression expression = ast.newInfixExpression();
    expression.setOperator(InfixExpression.Operator.PLUS);
    if (firstPos != 1) {
        expression.setLeftOperand(leftLiteral);
    }
    if (firstPos == 1) {
        expression.setLeftOperand(centerLiteral);
    } else {
        expression.setRightOperand(centerLiteral);
    }
    if (secondPos < stringValue.length() - 1) {
        if (firstPos == 1) {
            expression.setRightOperand(rightLiteral);
        } else {
            expression.extendedOperands().add(rightLiteral);
        }
    }
    // use new expression instead of old StirngLiteral
    rewrite.replace(stringLiteral, expression, null);
    // add correction proposal
    String label = CorrectionMessages.AdvancedQuickAssistProcessor_pickSelectedString;
    Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
    LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.PICK_SELECTED_STRING, image);
    //$NON-NLS-1$
    proposal.addLinkedPosition(rewrite.track(centerLiteral), true, "CENTER_STRING");
    resultingCollections.add(proposal);
    return true;
}
Also used : LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Image(org.eclipse.swt.graphics.Image)

Example 65 with ASTRewrite

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

the class QuickAssistProcessor method getSplitVariableProposals.

private static boolean getSplitVariableProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
    VariableDeclarationFragment fragment;
    if (node instanceof VariableDeclarationFragment) {
        fragment = (VariableDeclarationFragment) node;
    } else if (node.getLocationInParent() == VariableDeclarationFragment.NAME_PROPERTY) {
        fragment = (VariableDeclarationFragment) node.getParent();
    } else {
        return false;
    }
    if (fragment.getInitializer() == null) {
        return false;
    }
    Statement statement;
    ASTNode fragParent = fragment.getParent();
    if (fragParent instanceof VariableDeclarationStatement) {
        statement = (VariableDeclarationStatement) fragParent;
    } else if (fragParent instanceof VariableDeclarationExpression) {
        if (fragParent.getLocationInParent() == TryStatement.RESOURCES_PROPERTY) {
            return false;
        }
        statement = (Statement) fragParent.getParent();
    } else {
        return false;
    }
    // statement is ForStatement or VariableDeclarationStatement
    ASTNode statementParent = statement.getParent();
    StructuralPropertyDescriptor property = statement.getLocationInParent();
    if (!property.isChildListProperty()) {
        return false;
    }
    List<? extends ASTNode> list = ASTNodes.getChildListProperty(statementParent, (ChildListPropertyDescriptor) property);
    if (resultingCollections == null) {
        return true;
    }
    AST ast = statement.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    String label = CorrectionMessages.QuickAssistProcessor_splitdeclaration_description;
    Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.SPLIT_VARIABLE_DECLARATION, image);
    boolean commandConflict = false;
    for (Iterator<ICommandAccess> iterator = resultingCollections.iterator(); iterator.hasNext(); ) {
        Object completionProposal = iterator.next();
        if (completionProposal instanceof ChangeCorrectionProposal) {
            if (SPLIT_JOIN_VARIABLE_DECLARATION_ID.equals(((ChangeCorrectionProposal) completionProposal).getCommandId())) {
                commandConflict = true;
            }
        }
    }
    if (!commandConflict) {
        proposal.setCommandId(SPLIT_JOIN_VARIABLE_DECLARATION_ID);
    }
    Statement newStatement;
    int insertIndex = list.indexOf(statement);
    Expression placeholder = (Expression) rewrite.createMoveTarget(fragment.getInitializer());
    ITypeBinding binding = fragment.getInitializer().resolveTypeBinding();
    if (placeholder instanceof ArrayInitializer && binding != null && binding.isArray()) {
        ArrayCreation creation = ast.newArrayCreation();
        creation.setInitializer((ArrayInitializer) placeholder);
        final ITypeBinding componentType = binding.getElementType();
        Type type = null;
        if (componentType.isPrimitive())
            type = ast.newPrimitiveType(PrimitiveType.toCode(componentType.getName()));
        else
            type = ast.newSimpleType(ast.newSimpleName(componentType.getName()));
        creation.setType(ast.newArrayType(type, binding.getDimensions()));
        placeholder = creation;
    }
    Assignment assignment = ast.newAssignment();
    assignment.setRightHandSide(placeholder);
    assignment.setLeftHandSide(ast.newSimpleName(fragment.getName().getIdentifier()));
    if (statement instanceof VariableDeclarationStatement) {
        newStatement = ast.newExpressionStatement(assignment);
        // add after declaration
        insertIndex += 1;
    } else {
        rewrite.replace(fragment.getParent(), assignment, null);
        VariableDeclarationFragment newFrag = ast.newVariableDeclarationFragment();
        newFrag.setName(ast.newSimpleName(fragment.getName().getIdentifier()));
        newFrag.extraDimensions().addAll(DimensionRewrite.copyDimensions(fragment.extraDimensions(), rewrite));
        VariableDeclarationExpression oldVarDecl = (VariableDeclarationExpression) fragParent;
        VariableDeclarationStatement newVarDec = ast.newVariableDeclarationStatement(newFrag);
        newVarDec.setType((Type) rewrite.createCopyTarget(oldVarDecl.getType()));
        newVarDec.modifiers().addAll(ASTNodeFactory.newModifiers(ast, oldVarDecl.getModifiers()));
        newStatement = newVarDec;
    }
    ListRewrite listRewriter = rewrite.getListRewrite(statementParent, (ChildListPropertyDescriptor) property);
    listRewriter.insertAt(newStatement, insertIndex, null);
    resultingCollections.add(proposal);
    return true;
}
Also used : ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Image(org.eclipse.swt.graphics.Image) ChangeCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ICommandAccess(org.eclipse.jdt.ui.text.java.correction.ICommandAccess) IType(org.eclipse.jdt.core.IType)

Aggregations

ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)180 ASTRewriteCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal)93 Image (org.eclipse.swt.graphics.Image)80 AST (org.eclipse.jdt.core.dom.AST)78 ASTNode (org.eclipse.jdt.core.dom.ASTNode)69 Expression (org.eclipse.jdt.core.dom.Expression)54 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)49 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)44 Block (org.eclipse.jdt.core.dom.Block)38 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)35 SimpleName (org.eclipse.jdt.core.dom.SimpleName)34 ImportRewrite (org.eclipse.jdt.core.dom.rewrite.ImportRewrite)34 CastExpression (org.eclipse.jdt.core.dom.CastExpression)33 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)32 Type (org.eclipse.jdt.core.dom.Type)30 ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)30 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)29 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)29 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)29 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)29