Search in sources :

Example 6 with ASTRewriteCorrectionProposal

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

the class SuppressWarningsSubProcessor method addUnknownSuppressWarningProposals.

/**
	 * Adds a proposal to correct the name of the SuppressWarning annotation
	 * @param context the context
	 * @param problem the problem
	 * @param proposals the resulting proposals
	 */
public static void addUnknownSuppressWarningProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    ASTNode coveringNode = context.getCoveringNode();
    if (!(coveringNode instanceof StringLiteral))
        return;
    AST ast = coveringNode.getAST();
    StringLiteral literal = (StringLiteral) coveringNode;
    String literalValue = literal.getLiteralValue();
    String[] allWarningTokens = CorrectionEngine.getAllWarningTokens();
    for (int i = 0; i < allWarningTokens.length; i++) {
        String curr = allWarningTokens[i];
        if (NameMatcher.isSimilarName(literalValue, curr)) {
            StringLiteral newLiteral = ast.newStringLiteral();
            newLiteral.setLiteralValue(curr);
            ASTRewrite rewrite = ASTRewrite.create(ast);
            rewrite.replace(literal, newLiteral, null);
            String label = Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_fix_suppress_token_label, new String[] { curr });
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.FIX_SUPPRESS_TOKEN, image);
            proposals.add(proposal);
        }
    }
    addRemoveUnusedSuppressWarningProposals(context, problem, proposals);
}
Also used : ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) AST(org.eclipse.jdt.core.dom.AST) StringLiteral(org.eclipse.jdt.core.dom.StringLiteral) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Image(org.eclipse.swt.graphics.Image)

Example 7 with ASTRewriteCorrectionProposal

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

the class SuppressWarningsSubProcessor method addSuppressWarningsProposalIfPossible.

/**
	 * Adds a SuppressWarnings proposal if possible and returns whether parent nodes should be processed or not (and with what relevance).
	 *
	 * @param cu the compilation unit
	 * @param node the node on which to add a SuppressWarning token
	 * @param warningToken the warning token to add
	 * @param relevance the proposal's relevance
	 * @param proposals collector to which the proposal should be added
	 * @return <code>0</code> if no further proposals should be added to parent nodes, or the relevance of the next proposal
	 *
	 * @since 3.6
	 */
private static int addSuppressWarningsProposalIfPossible(ICompilationUnit cu, ASTNode node, String warningToken, int relevance, Collection<ICommandAccess> proposals) {
    ChildListPropertyDescriptor property;
    String name;
    boolean isLocalVariable = false;
    switch(node.getNodeType()) {
        case ASTNode.SINGLE_VARIABLE_DECLARATION:
            property = SingleVariableDeclaration.MODIFIERS2_PROPERTY;
            name = ((SingleVariableDeclaration) node).getName().getIdentifier();
            isLocalVariable = true;
            break;
        case ASTNode.VARIABLE_DECLARATION_STATEMENT:
            property = VariableDeclarationStatement.MODIFIERS2_PROPERTY;
            name = getFirstFragmentName(((VariableDeclarationStatement) node).fragments());
            isLocalVariable = true;
            break;
        case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
            property = VariableDeclarationExpression.MODIFIERS2_PROPERTY;
            name = getFirstFragmentName(((VariableDeclarationExpression) node).fragments());
            isLocalVariable = true;
            break;
        case ASTNode.TYPE_DECLARATION:
            property = TypeDeclaration.MODIFIERS2_PROPERTY;
            name = ((TypeDeclaration) node).getName().getIdentifier();
            break;
        case ASTNode.ANNOTATION_TYPE_DECLARATION:
            property = AnnotationTypeDeclaration.MODIFIERS2_PROPERTY;
            name = ((AnnotationTypeDeclaration) node).getName().getIdentifier();
            break;
        case ASTNode.ENUM_DECLARATION:
            property = EnumDeclaration.MODIFIERS2_PROPERTY;
            name = ((EnumDeclaration) node).getName().getIdentifier();
            break;
        case ASTNode.FIELD_DECLARATION:
            property = FieldDeclaration.MODIFIERS2_PROPERTY;
            name = getFirstFragmentName(((FieldDeclaration) node).fragments());
            break;
        // case ASTNode.INITIALIZER: not used, because Initializer cannot have annotations
        case ASTNode.METHOD_DECLARATION:
            property = MethodDeclaration.MODIFIERS2_PROPERTY;
            //$NON-NLS-1$
            name = ((MethodDeclaration) node).getName().getIdentifier() + "()";
            break;
        case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION:
            property = AnnotationTypeMemberDeclaration.MODIFIERS2_PROPERTY;
            //$NON-NLS-1$
            name = ((AnnotationTypeMemberDeclaration) node).getName().getIdentifier() + "()";
            break;
        case ASTNode.ENUM_CONSTANT_DECLARATION:
            property = EnumConstantDeclaration.MODIFIERS2_PROPERTY;
            name = ((EnumConstantDeclaration) node).getName().getIdentifier();
            break;
        default:
            return relevance;
    }
    String label = Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_suppress_warnings_label, new String[] { warningToken, BasicElementLabels.getJavaElementName(name) });
    ASTRewriteCorrectionProposal proposal = new SuppressWarningsProposal(warningToken, label, cu, node, property, relevance);
    proposals.add(proposal);
    return isLocalVariable ? relevance - 1 : 0;
}
Also used : SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) EnumDeclaration(org.eclipse.jdt.core.dom.EnumDeclaration) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) EnumConstantDeclaration(org.eclipse.jdt.core.dom.EnumConstantDeclaration) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) AnnotationTypeDeclaration(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration)

Example 8 with ASTRewriteCorrectionProposal

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

the class VarargsWarningsSubProcessor method addRemoveSafeVarargsProposals.

public static void addRemoveSafeVarargsProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    ASTNode coveringNode = problem.getCoveringNode(context.getASTRoot());
    if (!(coveringNode instanceof MethodDeclaration))
        return;
    MethodDeclaration methodDeclaration = (MethodDeclaration) coveringNode;
    MarkerAnnotation annotation = null;
    List<? extends ASTNode> modifiers = methodDeclaration.modifiers();
    for (Iterator<? extends ASTNode> iterator = modifiers.iterator(); iterator.hasNext(); ) {
        ASTNode node = iterator.next();
        if (node instanceof MarkerAnnotation) {
            annotation = (MarkerAnnotation) node;
            if ("SafeVarargs".equals(annotation.resolveAnnotationBinding().getName())) {
                //$NON-NLS-1$
                break;
            }
        }
    }
    if (annotation == null)
        return;
    ASTRewrite rewrite = ASTRewrite.create(coveringNode.getAST());
    rewrite.remove(annotation, null);
    String label = CorrectionMessages.VarargsWarningsSubProcessor_remove_safevarargs_label;
    //JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
    Image image = JavaPluginImages.get(JavaPluginImages.IMG_TOOL_DELETE);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_SAFEVARARGS, image);
    proposals.add(proposal);
}
Also used : ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) MarkerAnnotation(org.eclipse.jdt.core.dom.MarkerAnnotation) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Image(org.eclipse.swt.graphics.Image)

Example 9 with ASTRewriteCorrectionProposal

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

the class QuickAssistProcessor method getCatchClauseToThrowsProposals.

public static boolean getCatchClauseToThrowsProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
    CatchClause catchClause = (CatchClause) ASTResolving.findAncestor(node, ASTNode.CATCH_CLAUSE);
    if (catchClause == null) {
        return false;
    }
    Statement statement = ASTResolving.findParentStatement(node);
    if (statement != catchClause.getParent() && statement != catchClause.getBody()) {
        // selection is in a statement inside the body
        return false;
    }
    Type type = catchClause.getException().getType();
    if (!type.isSimpleType() && !type.isUnionType() && !type.isNameQualifiedType()) {
        return false;
    }
    BodyDeclaration bodyDeclaration = ASTResolving.findParentBodyDeclaration(catchClause);
    if (!(bodyDeclaration instanceof MethodDeclaration) && !(bodyDeclaration instanceof Initializer)) {
        return false;
    }
    if (resultingCollections == null) {
        return true;
    }
    AST ast = bodyDeclaration.getAST();
    Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
    Type selectedMultiCatchType = null;
    if (type.isUnionType() && node instanceof Name) {
        Name topMostName = ASTNodes.getTopMostName((Name) node);
        ASTNode parent = topMostName.getParent();
        if (parent instanceof SimpleType) {
            selectedMultiCatchType = (SimpleType) parent;
        } else if (parent instanceof NameQualifiedType) {
            selectedMultiCatchType = (NameQualifiedType) parent;
        }
    }
    if (bodyDeclaration instanceof MethodDeclaration) {
        MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration;
        ASTRewrite rewrite = ASTRewrite.create(ast);
        if (selectedMultiCatchType != null) {
            removeException(rewrite, (UnionType) type, selectedMultiCatchType);
            addExceptionToThrows(ast, methodDeclaration, rewrite, selectedMultiCatchType);
            String label = CorrectionMessages.QuickAssistProcessor_exceptiontothrows_description;
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_EXCEPTION_WITH_THROWS, image);
            resultingCollections.add(proposal);
        } else {
            removeCatchBlock(rewrite, catchClause);
            if (type.isUnionType()) {
                UnionType unionType = (UnionType) type;
                List<Type> types = unionType.types();
                for (Type elementType : types) {
                    if (!(elementType instanceof SimpleType || elementType instanceof NameQualifiedType))
                        return false;
                    addExceptionToThrows(ast, methodDeclaration, rewrite, elementType);
                }
            } else {
                addExceptionToThrows(ast, methodDeclaration, rewrite, type);
            }
            String label = CorrectionMessages.QuickAssistProcessor_catchclausetothrows_description;
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_CATCH_CLAUSE_WITH_THROWS, image);
            resultingCollections.add(proposal);
        }
    }
    {
        // for initializers or method declarations
        ASTRewrite rewrite = ASTRewrite.create(ast);
        if (selectedMultiCatchType != null) {
            removeException(rewrite, (UnionType) type, selectedMultiCatchType);
            String label = CorrectionMessages.QuickAssistProcessor_removeexception_description;
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_EXCEPTION, image);
            resultingCollections.add(proposal);
        } else {
            removeCatchBlock(rewrite, catchClause);
            String label = CorrectionMessages.QuickAssistProcessor_removecatchclause_description;
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_CATCH_CLAUSE, image);
            resultingCollections.add(proposal);
        }
    }
    return true;
}
Also used : Image(org.eclipse.swt.graphics.Image) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) IType(org.eclipse.jdt.core.IType) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 10 with ASTRewriteCorrectionProposal

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

the class QuickAssistProcessor method getAddBlockProposals.

private static boolean getAddBlockProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
    if (!(node instanceof Statement)) {
        return false;
    }
    /*
		 * only show the quick assist when the selection is of the control statement keywords (if, else, while,...)
		 * but not inside the statement or the if expression.
		 */
    if (!isControlStatementWithBlock(node) && isControlStatementWithBlock(node.getParent())) {
        int statementStart = node.getStartPosition();
        int statementEnd = statementStart + node.getLength();
        int offset = context.getSelectionOffset();
        int length = context.getSelectionLength();
        if (length == 0) {
            if (offset != statementEnd) {
                // cursor at end
                return false;
            }
        } else {
            if (offset > statementStart || offset + length < statementEnd) {
                // statement selected
                return false;
            }
        }
        node = node.getParent();
    }
    StructuralPropertyDescriptor childProperty = null;
    ASTNode child = null;
    switch(node.getNodeType()) {
        case ASTNode.IF_STATEMENT:
            ASTNode then = ((IfStatement) node).getThenStatement();
            ASTNode elseStatement = ((IfStatement) node).getElseStatement();
            if ((then instanceof Block) && (elseStatement instanceof Block || elseStatement == null)) {
                break;
            }
            int thenEnd = then.getStartPosition() + then.getLength();
            int selectionEnd = context.getSelectionOffset() + context.getSelectionLength();
            if (!(then instanceof Block)) {
                if (selectionEnd <= thenEnd) {
                    childProperty = IfStatement.THEN_STATEMENT_PROPERTY;
                    child = then;
                    break;
                } else if (elseStatement != null && selectionEnd < elseStatement.getStartPosition()) {
                    // find out if we are before or after the 'else' keyword
                    try {
                        TokenScanner scanner = new TokenScanner(context.getCompilationUnit());
                        int elseTokenStart = scanner.getNextStartOffset(thenEnd, true);
                        if (selectionEnd < elseTokenStart) {
                            childProperty = IfStatement.THEN_STATEMENT_PROPERTY;
                            child = then;
                            break;
                        }
                    } catch (CoreException e) {
                    // ignore
                    }
                }
            }
            if (elseStatement != null && !(elseStatement instanceof Block) && context.getSelectionOffset() >= thenEnd) {
                childProperty = IfStatement.ELSE_STATEMENT_PROPERTY;
                child = elseStatement;
            }
            break;
        case ASTNode.WHILE_STATEMENT:
            ASTNode whileBody = ((WhileStatement) node).getBody();
            if (!(whileBody instanceof Block)) {
                childProperty = WhileStatement.BODY_PROPERTY;
                child = whileBody;
            }
            break;
        case ASTNode.FOR_STATEMENT:
            ASTNode forBody = ((ForStatement) node).getBody();
            if (!(forBody instanceof Block)) {
                childProperty = ForStatement.BODY_PROPERTY;
                child = forBody;
            }
            break;
        case ASTNode.ENHANCED_FOR_STATEMENT:
            ASTNode enhancedForBody = ((EnhancedForStatement) node).getBody();
            if (!(enhancedForBody instanceof Block)) {
                childProperty = EnhancedForStatement.BODY_PROPERTY;
                child = enhancedForBody;
            }
            break;
        case ASTNode.DO_STATEMENT:
            ASTNode doBody = ((DoStatement) node).getBody();
            if (!(doBody instanceof Block)) {
                childProperty = DoStatement.BODY_PROPERTY;
                child = doBody;
            }
            break;
        default:
    }
    if (child == null) {
        return false;
    }
    if (resultingCollections == null) {
        return true;
    }
    AST ast = node.getAST();
    {
        ASTRewrite rewrite = ASTRewrite.create(ast);
        ASTNode childPlaceholder = rewrite.createMoveTarget(child);
        Block replacingBody = ast.newBlock();
        replacingBody.statements().add(childPlaceholder);
        rewrite.set(node, childProperty, replacingBody, null);
        String label;
        if (childProperty == IfStatement.THEN_STATEMENT_PROPERTY) {
            label = CorrectionMessages.QuickAssistProcessor_replacethenwithblock_description;
        } else if (childProperty == IfStatement.ELSE_STATEMENT_PROPERTY) {
            label = CorrectionMessages.QuickAssistProcessor_replaceelsewithblock_description;
        } else {
            label = CorrectionMessages.QuickAssistProcessor_replacebodywithblock_description;
        }
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
        LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_BLOCK, image);
        proposal.setCommandId(ADD_BLOCK_ID);
        proposal.setEndPosition(rewrite.track(child));
        resultingCollections.add(proposal);
    }
    if (node.getNodeType() == ASTNode.IF_STATEMENT) {
        ASTRewrite rewrite = ASTRewrite.create(ast);
        while (node.getLocationInParent() == IfStatement.ELSE_STATEMENT_PROPERTY) {
            node = node.getParent();
        }
        boolean missingBlockFound = false;
        boolean foundElse = false;
        IfStatement ifStatement;
        Statement thenStatment;
        Statement elseStatment;
        do {
            ifStatement = (IfStatement) node;
            thenStatment = ifStatement.getThenStatement();
            elseStatment = ifStatement.getElseStatement();
            if (!(thenStatment instanceof Block)) {
                ASTNode childPlaceholder1 = rewrite.createMoveTarget(thenStatment);
                Block replacingBody1 = ast.newBlock();
                replacingBody1.statements().add(childPlaceholder1);
                rewrite.set(ifStatement, IfStatement.THEN_STATEMENT_PROPERTY, replacingBody1, null);
                if (thenStatment != child) {
                    missingBlockFound = true;
                }
            }
            if (elseStatment != null) {
                foundElse = true;
            }
            node = elseStatment;
        } while (elseStatment instanceof IfStatement);
        if (elseStatment != null && !(elseStatment instanceof Block)) {
            ASTNode childPlaceholder2 = rewrite.createMoveTarget(elseStatment);
            Block replacingBody2 = ast.newBlock();
            replacingBody2.statements().add(childPlaceholder2);
            rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, replacingBody2, null);
            if (elseStatment != child) {
                missingBlockFound = true;
            }
        }
        if (missingBlockFound && foundElse) {
            String label = CorrectionMessages.QuickAssistProcessor_replacethenelsewithblock_description;
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CHANGE_IF_ELSE_TO_BLOCK, image);
            resultingCollections.add(proposal);
        }
    }
    return true;
}
Also used : TokenScanner(org.eclipse.jdt.internal.corext.dom.TokenScanner) Image(org.eclipse.swt.graphics.Image) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) CoreException(org.eclipse.core.runtime.CoreException) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

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