Search in sources :

Example 56 with ImportRewrite

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

the class ChangeMethodSignatureProposal method modifyParameters.

private void modifyParameters(ASTRewrite rewrite, MethodDeclaration methodDecl) {
    AST ast = methodDecl.getAST();
    ArrayList<String> usedNames = new ArrayList<String>();
    boolean hasCreatedVariables = false;
    IVariableBinding[] declaredFields = fSenderBinding.getDeclaringClass().getDeclaredFields();
    for (int i = 0; i < declaredFields.length; i++) {
        // avoid to take parameter names that are equal to field names
        usedNames.add(declaredFields[i].getName());
    }
    ImportRewrite imports = getImportRewrite();
    ImportRewriteContext context = new ContextSensitiveImportRewriteContext(methodDecl, imports);
    ListRewrite listRewrite = rewrite.getListRewrite(methodDecl, MethodDeclaration.PARAMETERS_PROPERTY);
    // old parameters
    List<SingleVariableDeclaration> parameters = methodDecl.parameters();
    // index over the oldParameters
    int k = 0;
    for (int i = 0; i < fParameterChanges.length; i++) {
        ChangeDescription curr = fParameterChanges[i];
        if (curr == null) {
            SingleVariableDeclaration oldParam = parameters.get(k);
            usedNames.add(oldParam.getName().getIdentifier());
            k++;
        } else if (curr instanceof InsertDescription) {
            InsertDescription desc = (InsertDescription) curr;
            SingleVariableDeclaration newNode = ast.newSingleVariableDeclaration();
            newNode.setType(imports.addImport(desc.type, ast, context));
            //$NON-NLS-1$
            newNode.setName(ast.newSimpleName("x"));
            // remember to set name later
            desc.resultingParamName = new SimpleName[] { newNode.getName() };
            desc.resultingParamType = newNode.getType();
            hasCreatedVariables = true;
            listRewrite.insertAt(newNode, i, null);
            Javadoc javadoc = methodDecl.getJavadoc();
            if (javadoc != null) {
                TagElement newTagElement = ast.newTagElement();
                newTagElement.setTagName(TagElement.TAG_PARAM);
                //$NON-NLS-1$
                SimpleName arg = ast.newSimpleName("x");
                newTagElement.fragments().add(arg);
                //$NON-NLS-1$
                insertTabStop(rewrite, newTagElement.fragments(), "param_tagcomment" + i);
                insertParamTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), parameters, k, newTagElement);
                // set the name later
                desc.resultingTagArg = arg;
            } else {
                desc.resultingTagArg = null;
            }
        } else if (curr instanceof RemoveDescription) {
            SingleVariableDeclaration decl = parameters.get(k);
            listRewrite.remove(decl, null);
            k++;
            TagElement tagNode = findParamTag(methodDecl, decl);
            if (tagNode != null) {
                rewrite.remove(tagNode, null);
            }
        } else if (curr instanceof EditDescription) {
            EditDescription desc = (EditDescription) curr;
            ITypeBinding newTypeBinding = desc.type;
            SingleVariableDeclaration decl = parameters.get(k);
            if (k == parameters.size() - 1 && i == fParameterChanges.length - 1 && decl.isVarargs() && newTypeBinding.isArray()) {
                // stick with varargs if it was before
                newTypeBinding = newTypeBinding.getElementType();
            } else {
                rewrite.set(decl, SingleVariableDeclaration.VARARGS_PROPERTY, Boolean.FALSE, null);
            }
            Type newType = imports.addImport(newTypeBinding, ast, context);
            rewrite.replace(decl.getType(), newType, null);
            DimensionRewrite.removeAllChildren(decl, SingleVariableDeclaration.EXTRA_DIMENSIONS2_PROPERTY, rewrite, null);
            IBinding binding = decl.getName().resolveBinding();
            if (binding != null) {
                SimpleName[] names = LinkedNodeFinder.findByBinding(decl.getRoot(), binding);
                SimpleName[] newNames = new SimpleName[names.length];
                for (int j = 0; j < names.length; j++) {
                    //$NON-NLS-1$  // name will be set later
                    SimpleName newName = ast.newSimpleName("x");
                    newNames[j] = newName;
                    rewrite.replace(names[j], newName, null);
                }
                desc.resultingParamName = newNames;
            } else {
                //$NON-NLS-1$  // name will be set later
                SimpleName newName = ast.newSimpleName("x");
                rewrite.replace(decl.getName(), newName, null);
                // remember to set name later
                desc.resultingParamName = new SimpleName[] { newName };
            }
            desc.resultingParamType = newType;
            desc.orginalName = decl.getName().getIdentifier();
            hasCreatedVariables = true;
            k++;
            TagElement tagNode = findParamTag(methodDecl, decl);
            if (tagNode != null) {
                List<? extends ASTNode> fragments = tagNode.fragments();
                if (!fragments.isEmpty()) {
                    //$NON-NLS-1$
                    SimpleName arg = ast.newSimpleName("x");
                    rewrite.replace(fragments.get(0), arg, null);
                    desc.resultingTagArg = arg;
                }
            }
        } else if (curr instanceof SwapDescription) {
            SingleVariableDeclaration decl1 = parameters.get(k);
            SingleVariableDeclaration decl2 = parameters.get(((SwapDescription) curr).index);
            rewrite.replace(decl1, rewrite.createCopyTarget(decl2), null);
            rewrite.replace(decl2, rewrite.createCopyTarget(decl1), null);
            usedNames.add(decl1.getName().getIdentifier());
            k++;
            TagElement tagNode1 = findParamTag(methodDecl, decl1);
            TagElement tagNode2 = findParamTag(methodDecl, decl2);
            if (tagNode1 != null && tagNode2 != null) {
                rewrite.replace(tagNode1, rewrite.createCopyTarget(tagNode2), null);
                rewrite.replace(tagNode2, rewrite.createCopyTarget(tagNode1), null);
            }
        }
    }
    if (!hasCreatedVariables) {
        return;
    }
    if (methodDecl.getBody() != null) {
        // avoid take a name of a local variable inside
        CompilationUnit root = (CompilationUnit) methodDecl.getRoot();
        IBinding[] bindings = (new ScopeAnalyzer(root)).getDeclarationsAfter(methodDecl.getBody().getStartPosition(), ScopeAnalyzer.VARIABLES);
        for (int i = 0; i < bindings.length; i++) {
            usedNames.add(bindings[i].getName());
        }
    }
    fixupNames(rewrite, usedNames);
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IBinding(org.eclipse.jdt.core.dom.IBinding) ArrayList(java.util.ArrayList) Javadoc(org.eclipse.jdt.core.dom.Javadoc) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) TagElement(org.eclipse.jdt.core.dom.TagElement) ArrayList(java.util.ArrayList) List(java.util.List) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) AST(org.eclipse.jdt.core.dom.AST) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) 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) ScopeAnalyzer(org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer)

Example 57 with ImportRewrite

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

the class UnresolvedElementsSubProcessor method addStaticImportFavoriteProposals.

private static void addStaticImportFavoriteProposals(IInvocationContext context, SimpleName node, boolean isMethod, Collection<ICommandAccess> proposals) throws JavaModelException {
    IJavaProject project = context.getCompilationUnit().getJavaProject();
    if (JavaModelUtil.is50OrHigher(project)) {
        String pref = PreferenceConstants.getPreference(PreferenceConstants.CODEASSIST_FAVORITE_STATIC_MEMBERS, project);
        //$NON-NLS-1$
        String[] favourites = pref.split(";");
        if (favourites.length == 0) {
            return;
        }
        CompilationUnit root = context.getASTRoot();
        AST ast = root.getAST();
        String name = node.getIdentifier();
        String[] staticImports = SimilarElementsRequestor.getStaticImportFavorites(context.getCompilationUnit(), name, isMethod, favourites);
        for (int i = 0; i < staticImports.length; i++) {
            String curr = staticImports[i];
            ImportRewrite importRewrite = StubUtility.createImportRewrite(root, true);
            ASTRewrite astRewrite = ASTRewrite.create(ast);
            String label;
            String qualifiedTypeName = Signature.getQualifier(curr);
            String elementLabel = BasicElementLabels.getJavaElementName(JavaModelUtil.concatenateName(Signature.getSimpleName(qualifiedTypeName), name));
            String res = importRewrite.addStaticImport(qualifiedTypeName, name, isMethod, new ContextSensitiveImportRewriteContext(root, node.getStartPosition(), importRewrite));
            int dot = res.lastIndexOf('.');
            if (dot != -1) {
                String usedTypeName = importRewrite.addImport(qualifiedTypeName);
                Name newName = ast.newQualifiedName(ast.newName(usedTypeName), ast.newSimpleName(name));
                astRewrite.replace(node, newName, null);
                label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_change_to_static_import_description, elementLabel);
            } else {
                label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_add_static_import_description, elementLabel);
            }
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL);
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_STATIC_IMPORT, image);
            proposal.setImportRewrite(importRewrite);
            proposals.add(proposal);
        }
    }
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) AST(org.eclipse.jdt.core.dom.AST) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) IJavaProject(org.eclipse.jdt.core.IJavaProject) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Image(org.eclipse.swt.graphics.Image) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) Name(org.eclipse.jdt.core.dom.Name)

Example 58 with ImportRewrite

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

the class QuickAssistProcessor method getConvertToMessageFormatProposal.

private static ASTRewriteCorrectionProposal getConvertToMessageFormatProposal(IInvocationContext context, AST ast, InfixExpression oldInfixExpression) {
    ICompilationUnit cu = context.getCompilationUnit();
    boolean is50OrHigher = JavaModelUtil.is50OrHigher(cu.getJavaProject());
    ASTRewrite rewrite = ASTRewrite.create(ast);
    CompilationUnit root = context.getASTRoot();
    ImportRewrite importRewrite = StubUtility.createImportRewrite(root, true);
    ContextSensitiveImportRewriteContext importContext = new ContextSensitiveImportRewriteContext(root, oldInfixExpression.getStartPosition(), importRewrite);
    // collect operands
    List<Expression> operands = new ArrayList<Expression>();
    collectInfixPlusOperands(oldInfixExpression, operands);
    List<Expression> formatArguments = new ArrayList<Expression>();
    //$NON-NLS-1$
    String formatString = "";
    int i = 0;
    for (Iterator<Expression> iterator = operands.iterator(); iterator.hasNext(); ) {
        Expression operand = iterator.next();
        if (operand instanceof StringLiteral) {
            String value = ((StringLiteral) operand).getEscapedValue();
            value = value.substring(1, value.length() - 1);
            //$NON-NLS-1$ //$NON-NLS-2$
            value = value.replaceAll("'", "''");
            formatString += value;
        } else {
            //$NON-NLS-1$ //$NON-NLS-2$
            formatString += "{" + i + "}";
            Expression argument;
            if (is50OrHigher) {
                argument = (Expression) rewrite.createCopyTarget(operand);
            } else {
                ITypeBinding binding = operand.resolveTypeBinding();
                if (binding == null)
                    return null;
                argument = (Expression) rewrite.createCopyTarget(operand);
                if (binding.isPrimitive()) {
                    ITypeBinding boxedBinding = Bindings.getBoxedTypeBinding(binding, ast);
                    if (boxedBinding != binding) {
                        Type boxedType = importRewrite.addImport(boxedBinding, ast, importContext);
                        ClassInstanceCreation cic = ast.newClassInstanceCreation();
                        cic.setType(boxedType);
                        cic.arguments().add(argument);
                        argument = cic;
                    }
                }
            }
            formatArguments.add(argument);
            i++;
        }
    }
    if (formatArguments.size() == 0)
        return null;
    String label = CorrectionMessages.QuickAssistProcessor_convert_to_message_format;
    Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.CONVERT_TO_MESSAGE_FORMAT, image);
    proposal.setCommandId(CONVERT_TO_MESSAGE_FORMAT_ID);
    proposal.setImportRewrite(importRewrite);
    //$NON-NLS-1$
    String messageType = importRewrite.addImport("java.text.MessageFormat", importContext);
    MethodInvocation formatInvocation = ast.newMethodInvocation();
    formatInvocation.setExpression(ast.newName(messageType));
    //$NON-NLS-1$
    formatInvocation.setName(ast.newSimpleName("format"));
    List<Expression> arguments = formatInvocation.arguments();
    StringLiteral formatStringArgument = ast.newStringLiteral();
    //$NON-NLS-1$ //$NON-NLS-2$
    formatStringArgument.setEscapedValue("\"" + formatString + "\"");
    arguments.add(formatStringArgument);
    if (is50OrHigher) {
        for (Iterator<Expression> iterator = formatArguments.iterator(); iterator.hasNext(); ) {
            arguments.add(iterator.next());
        }
    } else {
        ArrayCreation objectArrayCreation = ast.newArrayCreation();
        //$NON-NLS-1$
        Type objectType = ast.newSimpleType(ast.newSimpleName("Object"));
        ArrayType arrayType = ast.newArrayType(objectType);
        objectArrayCreation.setType(arrayType);
        ArrayInitializer arrayInitializer = ast.newArrayInitializer();
        List<Expression> initializerExpressions = arrayInitializer.expressions();
        for (Iterator<Expression> iterator = formatArguments.iterator(); iterator.hasNext(); ) {
            initializerExpressions.add(iterator.next());
        }
        objectArrayCreation.setInitializer(arrayInitializer);
        arguments.add(objectArrayCreation);
    }
    rewrite.replace(oldInfixExpression, formatInvocation, null);
    return proposal;
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) ArrayList(java.util.ArrayList) Image(org.eclipse.swt.graphics.Image) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) IType(org.eclipse.jdt.core.IType) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 59 with ImportRewrite

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

the class ReturnTypeSubProcessor method addVoidMethodReturnsProposals.

public static void addVoidMethodReturnsProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    if (selectedNode == null) {
        return;
    }
    BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
    if (decl instanceof MethodDeclaration && selectedNode.getNodeType() == ASTNode.RETURN_STATEMENT) {
        ReturnStatement returnStatement = (ReturnStatement) selectedNode;
        Expression expr = returnStatement.getExpression();
        if (expr != null) {
            AST ast = astRoot.getAST();
            ITypeBinding binding = Bindings.normalizeTypeBinding(expr.resolveTypeBinding());
            if (binding == null) {
                //$NON-NLS-1$
                binding = ast.resolveWellKnownType("java.lang.Object");
            }
            if (binding.isWildcardType()) {
                binding = ASTResolving.normalizeWildcardType(binding, true, ast);
            }
            MethodDeclaration methodDeclaration = (MethodDeclaration) decl;
            ASTRewrite rewrite = ASTRewrite.create(ast);
            String label = Messages.format(CorrectionMessages.ReturnTypeSubProcessor_voidmethodreturns_description, BindingLabelProvider.getBindingLabel(binding, BindingLabelProvider.DEFAULT_TEXTFLAGS));
            Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
            LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.VOID_METHOD_RETURNS, image);
            ImportRewrite imports = proposal.createImportRewrite(astRoot);
            ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(methodDeclaration, imports);
            Type newReturnType = imports.addImport(binding, ast, importRewriteContext);
            if (methodDeclaration.isConstructor()) {
                rewrite.set(methodDeclaration, MethodDeclaration.CONSTRUCTOR_PROPERTY, Boolean.FALSE, null);
                rewrite.set(methodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, newReturnType, null);
            } else {
                rewrite.replace(methodDeclaration.getReturnType2(), newReturnType, null);
            }
            //$NON-NLS-1$
            String key = "return_type";
            proposal.addLinkedPosition(rewrite.track(newReturnType), true, key);
            ITypeBinding[] bindings = ASTResolving.getRelaxingTypes(ast, binding);
            for (int i = 0; i < bindings.length; i++) {
                proposal.addLinkedPositionProposal(key, bindings[i]);
            }
            Javadoc javadoc = methodDeclaration.getJavadoc();
            if (javadoc != null) {
                TagElement newTag = ast.newTagElement();
                newTag.setTagName(TagElement.TAG_RETURN);
                TextElement commentStart = ast.newTextElement();
                newTag.fragments().add(commentStart);
                JavadocTagsSubProcessor.insertTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), newTag, null);
                //$NON-NLS-1$
                proposal.addLinkedPosition(rewrite.track(commentStart), false, "comment_start");
            }
            proposals.add(proposal);
        }
        ASTRewrite rewrite = ASTRewrite.create(decl.getAST());
        rewrite.remove(returnStatement.getExpression(), null);
        String label = CorrectionMessages.ReturnTypeSubProcessor_removereturn_description;
        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
        ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_TO_RETURN, image);
        proposals.add(proposal);
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Javadoc(org.eclipse.jdt.core.dom.Javadoc) Image(org.eclipse.swt.graphics.Image) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) TextElement(org.eclipse.jdt.core.dom.TextElement) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Expression(org.eclipse.jdt.core.dom.Expression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TagElement(org.eclipse.jdt.core.dom.TagElement) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration)

Example 60 with ImportRewrite

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

the class LocalCorrectionsSubProcessor method addRemoveIncludingConditionProposal.

private static void addRemoveIncludingConditionProposal(IInvocationContext context, ASTNode toRemove, ASTNode replacement, Collection<ICommandAccess> proposals) {
    //JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
    Image image = JavaPluginImages.get(JavaPluginImages.IMG_TOOL_DELETE);
    String label = CorrectionMessages.LocalCorrectionsSubProcessor_removeunreachablecode_including_condition_description;
    AST ast = toRemove.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_UNREACHABLE_CODE_INCLUDING_CONDITION, image);
    if (replacement == null || replacement instanceof EmptyStatement || replacement instanceof Block && ((Block) replacement).statements().size() == 0) {
        if (ASTNodes.isControlStatementBody(toRemove.getLocationInParent())) {
            rewrite.replace(toRemove, toRemove.getAST().newBlock(), null);
        } else {
            rewrite.remove(toRemove, null);
        }
    } else if (toRemove instanceof Expression && replacement instanceof Expression) {
        Expression moved = (Expression) rewrite.createMoveTarget(replacement);
        Expression toRemoveExpression = (Expression) toRemove;
        Expression replacementExpression = (Expression) replacement;
        ITypeBinding explicitCast = ASTNodes.getExplicitCast(replacementExpression, toRemoveExpression);
        if (explicitCast != null) {
            CastExpression cast = ast.newCastExpression();
            if (NecessaryParenthesesChecker.needsParentheses(replacementExpression, cast, CastExpression.EXPRESSION_PROPERTY)) {
                ParenthesizedExpression parenthesized = ast.newParenthesizedExpression();
                parenthesized.setExpression(moved);
                moved = parenthesized;
            }
            cast.setExpression(moved);
            ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
            ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(toRemove, imports);
            cast.setType(imports.addImport(explicitCast, ast, importRewriteContext));
            moved = cast;
        }
        rewrite.replace(toRemove, moved, null);
    } else {
        ASTNode parent = toRemove.getParent();
        ASTNode moveTarget;
        if ((parent instanceof Block || parent instanceof SwitchStatement) && replacement instanceof Block) {
            ListRewrite listRewrite = rewrite.getListRewrite(replacement, Block.STATEMENTS_PROPERTY);
            List<Statement> list = ((Block) replacement).statements();
            int lastIndex = list.size() - 1;
            moveTarget = listRewrite.createMoveTarget(list.get(0), list.get(lastIndex));
        } else {
            moveTarget = rewrite.createMoveTarget(replacement);
        }
        rewrite.replace(toRemove, moveTarget, null);
    }
    proposals.add(proposal);
}
Also used : ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) Image(org.eclipse.swt.graphics.Image) ASTRewriteCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal) 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) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) List(java.util.List) ArrayList(java.util.ArrayList)

Aggregations

ImportRewrite (org.eclipse.jdt.core.dom.rewrite.ImportRewrite)62 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)34 ContextSensitiveImportRewriteContext (org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext)32 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)28 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)27 AST (org.eclipse.jdt.core.dom.AST)25 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)20 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)18 SimpleName (org.eclipse.jdt.core.dom.SimpleName)18 Image (org.eclipse.swt.graphics.Image)17 ASTNode (org.eclipse.jdt.core.dom.ASTNode)16 Type (org.eclipse.jdt.core.dom.Type)15 ASTRewriteCorrectionProposal (org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal)14 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)12 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)10 ArrayList (java.util.ArrayList)9 IType (org.eclipse.jdt.core.IType)9 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)9 Expression (org.eclipse.jdt.core.dom.Expression)9 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)9