Search in sources :

Example 81 with BodyDeclaration

use of org.eclipse.jdt.core.dom.BodyDeclaration in project eclipse.jdt.ls by eclipse.

the class UnresolvedElementsSubProcessor method addNewVariableProposals.

private static void addNewVariableProposals(ICompilationUnit cu, Name node, SimpleName simpleName, Collection<CUCorrectionProposal> proposals) {
    String name = simpleName.getIdentifier();
    BodyDeclaration bodyDeclaration = ASTResolving.findParentBodyDeclaration(node, true);
    int type = bodyDeclaration.getNodeType();
    if (type == ASTNode.METHOD_DECLARATION) {
        int relevance = StubUtility.hasParameterName(cu.getJavaProject(), name) ? IProposalRelevance.CREATE_PARAMETER_PREFIX_OR_SUFFIX_MATCH : IProposalRelevance.CREATE_PARAMETER;
        String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createparameter_description, BasicElementLabels.getJavaElementName(name));
        proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.PARAM, simpleName, null, relevance));
    }
    if (type == ASTNode.INITIALIZER || type == ASTNode.METHOD_DECLARATION && !ASTResolving.isInsideConstructorInvocation((MethodDeclaration) bodyDeclaration, node)) {
        int relevance = StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? IProposalRelevance.CREATE_LOCAL_PREFIX_OR_SUFFIX_MATCH : IProposalRelevance.CREATE_LOCAL;
        String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createlocal_description, BasicElementLabels.getJavaElementName(name));
        proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL, simpleName, null, relevance));
    }
    if (node.getParent().getNodeType() == ASTNode.ASSIGNMENT) {
        Assignment assignment = (Assignment) node.getParent();
        if (assignment.getLeftHandSide() == node && assignment.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
            ASTNode statement = assignment.getParent();
            ASTRewrite rewrite = ASTRewrite.create(statement.getAST());
            if (ASTNodes.isControlStatementBody(assignment.getParent().getLocationInParent())) {
                rewrite.replace(statement, rewrite.getAST().newBlock(), null);
            } else {
                rewrite.remove(statement, null);
            }
            String label = CorrectionMessages.UnresolvedElementsSubProcessor_removestatement_description;
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.REMOVE_ASSIGNMENT);
            proposals.add(proposal);
        }
    }
}
Also used : Assignment(org.eclipse.jdt.core.dom.Assignment) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration)

Example 82 with BodyDeclaration

use of org.eclipse.jdt.core.dom.BodyDeclaration in project eclipse.jdt.ls by eclipse.

the class LocalCorrectionsSubProcessor method addUncaughtExceptionProposals.

public static void addUncaughtExceptionProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) throws CoreException {
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    if (selectedNode == null) {
        return;
    }
    while (selectedNode != null && !(selectedNode instanceof Statement) && !(selectedNode instanceof VariableDeclarationExpression) && !(selectedNode.getLocationInParent() == LambdaExpression.BODY_PROPERTY) && !(selectedNode instanceof MethodReference)) {
        selectedNode = selectedNode.getParent();
    }
    if (selectedNode == null) {
        return;
    }
    int offset = selectedNode.getStartPosition();
    int length = selectedNode.getLength();
    int selectionEnd = context.getSelectionOffset() + context.getSelectionLength();
    if (selectionEnd > offset + length) {
        // extend the selection if more than one statement is selected (bug 72149)
        length = selectionEnd - offset;
    }
    // Surround with proposals
    SurroundWithTryCatchRefactoring refactoring = SurroundWithTryCatchRefactoring.create(cu, offset, length);
    if (refactoring == null) {
        return;
    }
    refactoring.setLeaveDirty(true);
    if (refactoring.checkActivationBasics(astRoot).isOK()) {
        String label = CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_trycatch_description;
        RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, cu, refactoring, IProposalRelevance.SURROUND_WITH_TRY_CATCH);
        proposal.setLinkedProposalModel(refactoring.getLinkedProposalModel());
        proposals.add(proposal);
    }
    if (JavaModelUtil.is17OrHigher(cu.getJavaProject())) {
        refactoring = SurroundWithTryCatchRefactoring.create(cu, offset, length, true);
        if (refactoring == null) {
            return;
        }
        refactoring.setLeaveDirty(true);
        if (refactoring.checkActivationBasics(astRoot).isOK()) {
            String label = CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_trymulticatch_description;
            RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, cu, refactoring, IProposalRelevance.SURROUND_WITH_TRY_MULTICATCH);
            proposal.setLinkedProposalModel(refactoring.getLinkedProposalModel());
            proposals.add(proposal);
        }
    }
    // Catch exception
    BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
    if (decl == null) {
        return;
    }
    ASTNode enclosingNode = SurroundWithAnalyzer.getEnclosingNode(selectedNode);
    if (enclosingNode == null) {
        return;
    }
    ITypeBinding[] uncaughtExceptions = ExceptionAnalyzer.perform(enclosingNode, Selection.createFromStartLength(offset, length));
    if (uncaughtExceptions.length == 0) {
        return;
    }
    TryStatement surroundingTry = ASTResolving.findParentTryStatement(selectedNode);
    AST ast = astRoot.getAST();
    if (surroundingTry != null && (ASTNodes.isParent(selectedNode, surroundingTry.getBody()) || selectedNode.getLocationInParent() == TryStatement.RESOURCES_PROPERTY)) {
        {
            ASTRewrite rewrite = ASTRewrite.create(surroundingTry.getAST());
            String label = CorrectionMessages.LocalCorrectionsSubProcessor_addadditionalcatch_description;
            LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_ADDITIONAL_CATCH);
            ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
            ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
            CodeScopeBuilder.Scope scope = CodeScopeBuilder.perform(decl, Selection.createFromStartLength(offset, length)).findScope(offset, length);
            scope.setCursor(offset);
            ListRewrite clausesRewrite = rewrite.getListRewrite(surroundingTry, TryStatement.CATCH_CLAUSES_PROPERTY);
            for (int i = 0; i < uncaughtExceptions.length; i++) {
                ITypeBinding excBinding = uncaughtExceptions[i];
                String varName = StubUtility.getExceptionVariableName(cu.getJavaProject());
                String name = scope.createName(varName, false);
                SingleVariableDeclaration var = ast.newSingleVariableDeclaration();
                var.setName(ast.newSimpleName(name));
                var.setType(imports.addImport(excBinding, ast, importRewriteContext, TypeLocation.EXCEPTION));
                CatchClause newClause = ast.newCatchClause();
                newClause.setException(var);
                String catchBody = StubUtility.getCatchBodyContent(cu, excBinding.getName(), name, selectedNode, String.valueOf('\n'));
                if (catchBody != null) {
                    ASTNode node = rewrite.createStringPlaceholder(catchBody, ASTNode.RETURN_STATEMENT);
                    newClause.getBody().statements().add(node);
                }
                clausesRewrite.insertLast(newClause, null);
                // $NON-NLS-1$
                String typeKey = "type" + i;
                // $NON-NLS-1$
                String nameKey = "name" + i;
                proposal.addLinkedPosition(rewrite.track(var.getType()), false, typeKey);
                proposal.addLinkedPosition(rewrite.track(var.getName()), false, nameKey);
                addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
            }
            proposals.add(proposal);
        }
        if (JavaModelUtil.is17OrHigher(cu.getJavaProject())) {
            List<CatchClause> catchClauses = surroundingTry.catchClauses();
            if (catchClauses != null && catchClauses.size() == 1) {
                List<ITypeBinding> filteredExceptions = SurroundWithTryCatchRefactoring.filterSubtypeExceptions(uncaughtExceptions);
                String label = filteredExceptions.size() > 1 ? CorrectionMessages.LocalCorrectionsSubProcessor_addexceptionstoexistingcatch_description : CorrectionMessages.LocalCorrectionsSubProcessor_addexceptiontoexistingcatch_description;
                ASTRewrite rewrite = ASTRewrite.create(ast);
                LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_EXCEPTIONS_TO_EXISTING_CATCH);
                ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
                ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
                CatchClause catchClause = catchClauses.get(0);
                Type type = catchClause.getException().getType();
                if (type instanceof UnionType) {
                    UnionType unionType = (UnionType) type;
                    ListRewrite listRewrite = rewrite.getListRewrite(unionType, UnionType.TYPES_PROPERTY);
                    for (int i = 0; i < filteredExceptions.size(); i++) {
                        ITypeBinding excBinding = filteredExceptions.get(i);
                        Type type2 = imports.addImport(excBinding, ast, importRewriteContext, TypeLocation.EXCEPTION);
                        listRewrite.insertLast(type2, null);
                        // $NON-NLS-1$
                        String typeKey = "type" + i;
                        proposal.addLinkedPosition(rewrite.track(type2), false, typeKey);
                        addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
                    }
                } else {
                    UnionType newUnionType = ast.newUnionType();
                    List<Type> types = newUnionType.types();
                    types.add((Type) rewrite.createCopyTarget(type));
                    for (int i = 0; i < filteredExceptions.size(); i++) {
                        ITypeBinding excBinding = filteredExceptions.get(i);
                        Type type2 = imports.addImport(excBinding, ast, importRewriteContext, TypeLocation.EXCEPTION);
                        types.add(type2);
                        // $NON-NLS-1$
                        String typeKey = "type" + i;
                        proposal.addLinkedPosition(rewrite.track(type2), false, typeKey);
                        addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
                    }
                    rewrite.replace(type, newUnionType, null);
                }
                proposals.add(proposal);
            } else if (catchClauses != null && catchClauses.size() == 0) {
                List<ITypeBinding> filteredExceptions = SurroundWithTryCatchRefactoring.filterSubtypeExceptions(uncaughtExceptions);
                if (filteredExceptions.size() > 1) {
                    String label = CorrectionMessages.LocalCorrectionsSubProcessor_addadditionalmulticatch_description;
                    ASTRewrite rewrite = ASTRewrite.create(ast);
                    LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_ADDITIONAL_MULTI_CATCH);
                    ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
                    ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
                    CodeScopeBuilder.Scope scope = CodeScopeBuilder.perform(decl, Selection.createFromStartLength(offset, length)).findScope(offset, length);
                    scope.setCursor(offset);
                    CatchClause newCatchClause = ast.newCatchClause();
                    String varName = StubUtility.getExceptionVariableName(cu.getJavaProject());
                    String name = scope.createName(varName, false);
                    SingleVariableDeclaration var = ast.newSingleVariableDeclaration();
                    var.setName(ast.newSimpleName(name));
                    UnionType newUnionType = ast.newUnionType();
                    List<Type> types = newUnionType.types();
                    for (int i = 0; i < filteredExceptions.size(); i++) {
                        ITypeBinding excBinding = filteredExceptions.get(i);
                        Type type2 = imports.addImport(excBinding, ast, importRewriteContext, TypeLocation.EXCEPTION);
                        types.add(type2);
                        // $NON-NLS-1$
                        String typeKey = "type" + i;
                        proposal.addLinkedPosition(rewrite.track(type2), false, typeKey);
                        addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
                    }
                    // $NON-NLS-1$
                    String nameKey = "name";
                    proposal.addLinkedPosition(rewrite.track(var.getName()), false, nameKey);
                    var.setType(newUnionType);
                    newCatchClause.setException(var);
                    // $NON-NLS-1$
                    String catchBody = StubUtility.getCatchBodyContent(cu, "Exception", name, selectedNode, String.valueOf('\n'));
                    if (catchBody != null) {
                        ASTNode node = rewrite.createStringPlaceholder(catchBody, ASTNode.RETURN_STATEMENT);
                        newCatchClause.getBody().statements().add(node);
                    }
                    ListRewrite listRewrite = rewrite.getListRewrite(surroundingTry, TryStatement.CATCH_CLAUSES_PROPERTY);
                    listRewrite.insertFirst(newCatchClause, null);
                    proposals.add(proposal);
                }
            }
        }
    }
    // Add throws declaration
    if (enclosingNode instanceof MethodDeclaration) {
        MethodDeclaration methodDecl = (MethodDeclaration) enclosingNode;
        IMethodBinding binding = methodDecl.resolveBinding();
        boolean isApplicable = (binding != null);
        if (isApplicable) {
            IMethodBinding overriddenMethod = Bindings.findOverriddenMethod(binding, true);
            if (overriddenMethod != null) {
                isApplicable = overriddenMethod.getDeclaringClass().isFromSource();
                if (!isApplicable) {
                    // bug 349051
                    ITypeBinding[] exceptionTypes = overriddenMethod.getExceptionTypes();
                    ArrayList<ITypeBinding> unhandledExceptions = new ArrayList<>(uncaughtExceptions.length);
                    for (int i = 0; i < uncaughtExceptions.length; i++) {
                        ITypeBinding curr = uncaughtExceptions[i];
                        if (isSubtype(curr, exceptionTypes)) {
                            unhandledExceptions.add(curr);
                        }
                    }
                    uncaughtExceptions = unhandledExceptions.toArray(new ITypeBinding[unhandledExceptions.size()]);
                    isApplicable |= uncaughtExceptions.length > 0;
                }
            }
        }
        if (isApplicable) {
            ITypeBinding[] methodExceptions = binding.getExceptionTypes();
            ArrayList<ITypeBinding> unhandledExceptions = new ArrayList<>(uncaughtExceptions.length);
            for (int i = 0; i < uncaughtExceptions.length; i++) {
                ITypeBinding curr = uncaughtExceptions[i];
                if (!isSubtype(curr, methodExceptions)) {
                    unhandledExceptions.add(curr);
                }
            }
            uncaughtExceptions = unhandledExceptions.toArray(new ITypeBinding[unhandledExceptions.size()]);
            List<Type> exceptions = methodDecl.thrownExceptionTypes();
            int nExistingExceptions = exceptions.size();
            ChangeDescription[] desc = new ChangeDescription[nExistingExceptions + uncaughtExceptions.length];
            for (int i = 0; i < exceptions.size(); i++) {
                Type elem = exceptions.get(i);
                if (isSubtype(elem.resolveBinding(), uncaughtExceptions)) {
                    desc[i] = new RemoveDescription();
                }
            }
            for (int i = 0; i < uncaughtExceptions.length; i++) {
                // $NON-NLS-1$
                desc[i + nExistingExceptions] = new InsertDescription(uncaughtExceptions[i], "");
            }
            String label = CorrectionMessages.LocalCorrectionsSubProcessor_addthrows_description;
            ChangeMethodSignatureProposal proposal = new ChangeMethodSignatureProposal(label, cu, astRoot, binding, null, desc, IProposalRelevance.ADD_THROWS_DECLARATION);
            for (int i = 0; i < uncaughtExceptions.length; i++) {
                addExceptionTypeLinkProposals(proposal, uncaughtExceptions[i], proposal.getExceptionTypeGroupId(i + nExistingExceptions));
            }
            proposals.add(proposal);
        }
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) UnionType(org.eclipse.jdt.core.dom.UnionType) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) InsertDescription(org.eclipse.jdt.ls.core.internal.corrections.proposals.ChangeMethodSignatureProposal.InsertDescription) ArrayList(java.util.ArrayList) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) SurroundWithTryCatchRefactoring(org.eclipse.jdt.ls.core.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring) TryStatement(org.eclipse.jdt.core.dom.TryStatement) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ChangeDescription(org.eclipse.jdt.ls.core.internal.corrections.proposals.ChangeMethodSignatureProposal.ChangeDescription) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) List(java.util.List) ArrayList(java.util.ArrayList) RemoveDescription(org.eclipse.jdt.ls.core.internal.corrections.proposals.ChangeMethodSignatureProposal.RemoveDescription) 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) Statement(org.eclipse.jdt.core.dom.Statement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) EmptyStatement(org.eclipse.jdt.core.dom.EmptyStatement) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) CatchClause(org.eclipse.jdt.core.dom.CatchClause) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) UnionType(org.eclipse.jdt.core.dom.UnionType) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) MethodReference(org.eclipse.jdt.core.dom.MethodReference) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration)

Example 83 with BodyDeclaration

use of org.eclipse.jdt.core.dom.BodyDeclaration in project eclipse.jdt.ls by eclipse.

the class NewMethodCorrectionProposal method getInterfaceMethodModifiers.

private int getInterfaceMethodModifiers(ASTNode targetTypeDecl, boolean createAbstractMethod) {
    // for interface and annotation members copy the modifiers from an existing member
    if (targetTypeDecl instanceof TypeDeclaration) {
        TypeDeclaration type = (TypeDeclaration) targetTypeDecl;
        MethodDeclaration[] methodDecls = type.getMethods();
        if (methodDecls.length > 0) {
            if (createAbstractMethod) {
                for (MethodDeclaration methodDeclaration : methodDecls) {
                    IMethodBinding methodBinding = methodDeclaration.resolveBinding();
                    if (methodBinding != null && JdtFlags.isAbstract(methodBinding)) {
                        return methodDeclaration.getModifiers();
                    }
                }
            }
            return methodDecls[0].getModifiers() & Modifier.PUBLIC;
        }
        List<BodyDeclaration> bodyDecls = type.bodyDeclarations();
        if (bodyDecls.size() > 0) {
            return bodyDecls.get(0).getModifiers() & Modifier.PUBLIC;
        }
    }
    return 0;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration)

Example 84 with BodyDeclaration

use of org.eclipse.jdt.core.dom.BodyDeclaration in project eclipse.jdt.ls 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, TypeLocation.LOCAL_VARIABLE));
        Expression placeholder = (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
        newDeclFrag.setInitializer(placeholder);
        newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
        rewrite.replace(assignment, newDecl, null);
        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, TypeLocation.LOCAL_VARIABLE));
        rewrite.replace(assignment, expression, null);
        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, TypeLocation.LOCAL_VARIABLE);
        } else {
            // $NON-NLS-1$
            type = ast.newSimpleType(ast.newSimpleName("Object"));
        }
        rewrite.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, type, null);
        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, TypeLocation.LOCAL_VARIABLE));
    // newDeclFrag.setInitializer(ASTNodeFactory.newDefaultExpression(ast, newDecl.getType(), 0));
    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.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.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 85 with BodyDeclaration

use of org.eclipse.jdt.core.dom.BodyDeclaration in project eclipse.jdt.ls by eclipse.

the class NewVariableCorrectionProposal method doAddField.

private ASTRewrite doAddField(CompilationUnit astRoot) {
    SimpleName node = fOriginalNode;
    boolean isInDifferentCU = false;
    ASTNode newTypeDecl = astRoot.findDeclaringNode(fSenderBinding);
    if (newTypeDecl == null) {
        astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
        newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey());
        isInDifferentCU = true;
    }
    ImportRewrite imports = createImportRewrite(astRoot);
    ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(node), imports);
    if (newTypeDecl != null) {
        AST ast = newTypeDecl.getAST();
        ASTRewrite rewrite = ASTRewrite.create(ast);
        VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment();
        fragment.setName(ast.newSimpleName(node.getIdentifier()));
        Type type = evaluateVariableType(ast, imports, importRewriteContext, fSenderBinding, TypeLocation.FIELD);
        FieldDeclaration newDecl = ast.newFieldDeclaration(fragment);
        newDecl.setType(type);
        newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, evaluateFieldModifiers(newTypeDecl)));
        if (fSenderBinding.isInterface() || fVariableKind == CONST_FIELD) {
            fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0));
        }
        ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
        List<BodyDeclaration> decls = ASTNodes.<BodyDeclaration>getChildListProperty(newTypeDecl, property);
        int maxOffset = isInDifferentCU ? -1 : node.getStartPosition();
        int insertIndex = findFieldInsertIndex(decls, newDecl, maxOffset);
        ListRewrite listRewriter = rewrite.getListRewrite(newTypeDecl, property);
        listRewriter.insertAt(newDecl, insertIndex, null);
        return rewrite;
    }
    return null;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) ChildListPropertyDescriptor(org.eclipse.jdt.core.dom.ChildListPropertyDescriptor) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration)

Aggregations

BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)98 ASTNode (org.eclipse.jdt.core.dom.ASTNode)61 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)53 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)28 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)27 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)26 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)26 Type (org.eclipse.jdt.core.dom.Type)25 AST (org.eclipse.jdt.core.dom.AST)23 FieldDeclaration (org.eclipse.jdt.core.dom.FieldDeclaration)18 ImportRewrite (org.eclipse.jdt.core.dom.rewrite.ImportRewrite)17 Expression (org.eclipse.jdt.core.dom.Expression)16 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)15 Initializer (org.eclipse.jdt.core.dom.Initializer)15 SimpleName (org.eclipse.jdt.core.dom.SimpleName)15 TypeDeclaration (org.eclipse.jdt.core.dom.TypeDeclaration)15 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)14 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)14 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)13 ArrayList (java.util.ArrayList)12