Search in sources :

Example 21 with Initializer

use of org.eclipse.jdt.core.dom.Initializer 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.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) 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 22 with Initializer

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

the class AssignToVariableAssistProposal method doAddField.

private ASTRewrite doAddField(ASTRewrite rewrite, ASTNode nodeToAssign, ITypeBinding typeBinding, int index) {
    boolean isParamToField = nodeToAssign.getNodeType() == ASTNode.SINGLE_VARIABLE_DECLARATION;
    ASTNode newTypeDecl = ASTResolving.findParentType(nodeToAssign);
    if (newTypeDecl == null) {
        return null;
    }
    Expression expression = isParamToField ? ((SingleVariableDeclaration) nodeToAssign).getName() : ((ExpressionStatement) nodeToAssign).getExpression();
    AST ast = newTypeDecl.getAST();
    createImportRewrite((CompilationUnit) nodeToAssign.getRoot());
    BodyDeclaration bodyDecl = ASTResolving.findParentBodyDeclaration(nodeToAssign);
    Block body;
    if (bodyDecl instanceof MethodDeclaration) {
        body = ((MethodDeclaration) bodyDecl).getBody();
    } else if (bodyDecl instanceof Initializer) {
        body = ((Initializer) bodyDecl).getBody();
    } else {
        return null;
    }
    IJavaProject project = getCompilationUnit().getJavaProject();
    boolean isAnonymous = newTypeDecl.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION;
    boolean isStatic = Modifier.isStatic(bodyDecl.getModifiers()) && !isAnonymous;
    int modifiers = Modifier.PRIVATE;
    if (isStatic) {
        modifiers |= Modifier.STATIC;
    }
    VariableDeclarationFragment newDeclFrag = addFieldDeclaration(rewrite, newTypeDecl, modifiers, expression, nodeToAssign, typeBinding, index);
    String varName = newDeclFrag.getName().getIdentifier();
    Assignment assignment = ast.newAssignment();
    assignment.setRightHandSide((Expression) rewrite.createCopyTarget(expression));
    boolean needsThis = StubUtility.useThisForFieldAccess(project);
    if (isParamToField) {
        needsThis |= varName.equals(((SimpleName) expression).getIdentifier());
    }
    SimpleName accessName = ast.newSimpleName(varName);
    if (needsThis) {
        FieldAccess fieldAccess = ast.newFieldAccess();
        fieldAccess.setName(accessName);
        if (isStatic) {
            String typeName = ((AbstractTypeDeclaration) newTypeDecl).getName().getIdentifier();
            fieldAccess.setExpression(ast.newSimpleName(typeName));
        } else {
            fieldAccess.setExpression(ast.newThisExpression());
        }
        assignment.setLeftHandSide(fieldAccess);
    } else {
        assignment.setLeftHandSide(accessName);
    }
    ASTNode selectionNode;
    if (isParamToField) {
        // assign parameter to field
        ExpressionStatement statement = ast.newExpressionStatement(assignment);
        int insertIdx = findAssignmentInsertIndex(body.statements(), nodeToAssign) + index;
        rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY).insertAt(statement, insertIdx, null);
        selectionNode = statement;
    } else {
        if (needsSemicolon(expression)) {
            rewrite.replace(expression, ast.newExpressionStatement(assignment), null);
        } else {
            rewrite.replace(expression, assignment, null);
        }
        selectionNode = nodeToAssign;
    }
    addLinkedPosition(rewrite.track(newDeclFrag.getName()), false, KEY_NAME + index);
    if (!isParamToField) {
        FieldDeclaration fieldDeclaration = (FieldDeclaration) newDeclFrag.getParent();
        addLinkedPosition(rewrite.track(fieldDeclaration.getType()), false, KEY_TYPE);
    }
    addLinkedPosition(rewrite.track(accessName), true, KEY_NAME + index);
    IVariableBinding variableBinding = newDeclFrag.resolveBinding();
    if (variableBinding != null) {
        SimpleName[] linkedNodes = LinkedNodeFinder.findByBinding(nodeToAssign.getRoot(), variableBinding);
        for (int i = 0; i < linkedNodes.length; i++) {
            addLinkedPosition(rewrite.track(linkedNodes[i]), false, KEY_NAME + index);
        }
    }
    setEndPosition(rewrite.track(selectionNode));
    return rewrite;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) Assignment(org.eclipse.jdt.core.dom.Assignment) IJavaProject(org.eclipse.jdt.core.IJavaProject) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationExpression(org.eclipse.jdt.core.dom.VariableDeclarationExpression) Initializer(org.eclipse.jdt.core.dom.Initializer) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess)

Example 23 with Initializer

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

the class QuickAssistProcessor method getCatchClauseToThrowsProposals.

public static boolean getCatchClauseToThrowsProposals(IInvocationContext context, ASTNode node, Collection<ChangeCorrectionProposal> resultingCollections) {
    if (resultingCollections == null) {
        return true;
    }
    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;
    }
    AST ast = bodyDeclaration.getAST();
    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, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_EXCEPTION_WITH_THROWS);
            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, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_CATCH_CLAUSE_WITH_THROWS);
            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, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_EXCEPTION);
            resultingCollections.add(proposal);
        } else {
            removeCatchBlock(rewrite, catchClause);
            String label = CorrectionMessages.QuickAssistProcessor_removecatchclause_description;
            ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_CATCH_CLAUSE);
            resultingCollections.add(proposal);
        }
    }
    return true;
}
Also used : UnionType(org.eclipse.jdt.core.dom.UnionType) AST(org.eclipse.jdt.core.dom.AST) Statement(org.eclipse.jdt.core.dom.Statement) ThrowStatement(org.eclipse.jdt.core.dom.ThrowStatement) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) CatchClause(org.eclipse.jdt.core.dom.CatchClause) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) ASTRewriteCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.ASTRewriteCorrectionProposal) SimpleType(org.eclipse.jdt.core.dom.SimpleType) UnionType(org.eclipse.jdt.core.dom.UnionType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) QualifiedType(org.eclipse.jdt.core.dom.QualifiedType) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) Initializer(org.eclipse.jdt.core.dom.Initializer) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType)

Aggregations

Initializer (org.eclipse.jdt.core.dom.Initializer)23 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)18 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)18 ASTNode (org.eclipse.jdt.core.dom.ASTNode)17 FieldDeclaration (org.eclipse.jdt.core.dom.FieldDeclaration)11 AST (org.eclipse.jdt.core.dom.AST)8 Block (org.eclipse.jdt.core.dom.Block)8 SimpleName (org.eclipse.jdt.core.dom.SimpleName)8 Statement (org.eclipse.jdt.core.dom.Statement)7 Expression (org.eclipse.jdt.core.dom.Expression)6 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)6 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)6 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)6 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)6 Assignment (org.eclipse.jdt.core.dom.Assignment)5 EnhancedForStatement (org.eclipse.jdt.core.dom.EnhancedForStatement)5 ForStatement (org.eclipse.jdt.core.dom.ForStatement)5 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)5 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)5 TryStatement (org.eclipse.jdt.core.dom.TryStatement)4