Search in sources :

Example 1 with Initializer

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

the class LocalVariableIndex method internalPerform.

private static int internalPerform(BodyDeclaration methodOrInitializer) {
    // we have to find the outermost method/initializer/field declaration since a local or anonymous
    // type can reference final variables from the outer scope.
    BodyDeclaration target = methodOrInitializer;
    ASTNode parent = target.getParent();
    while (parent != null) {
        if (parent instanceof MethodDeclaration || parent instanceof Initializer || parent instanceof FieldDeclaration) {
            target = (BodyDeclaration) parent;
        }
        parent = parent.getParent();
    }
    return doPerform(target);
}
Also used : Initializer(org.eclipse.jdt.core.dom.Initializer) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration)

Example 2 with Initializer

use of org.eclipse.jdt.core.dom.Initializer in project che 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));
        Expression placeholder = (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
        newDeclFrag.setInitializer(placeholder);
        newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
        rewrite.replace(assignment, newDecl, null);
        addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
        addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME);
        setEndPosition(rewrite.track(assignment.getParent()));
        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));
        rewrite.replace(assignment, expression, null);
        addLinkedPosition(rewrite.track(expression.getType()), false, KEY_TYPE);
        addLinkedPosition(rewrite.track(frag.getName()), true, KEY_NAME);
        setEndPosition(rewrite.track(expression));
        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);
        } else {
            //$NON-NLS-1$
            type = ast.newSimpleType(ast.newSimpleName("Object"));
        }
        rewrite.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, type, null);
        addLinkedPosition(rewrite.track(type), false, KEY_TYPE);
        addLinkedPosition(rewrite.track(newName), true, KEY_NAME);
        setEndPosition(rewrite.track(expression));
        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));
    //		newDeclFrag.setInitializer(ASTNodeFactory.newDefaultExpression(ast, newDecl.getType(), 0));
    addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
    addLinkedPosition(rewrite.track(node), true, KEY_NAME);
    addLinkedPosition(rewrite.track(newDeclFrag.getName()), false, KEY_NAME);
    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 3 with Initializer

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

the class ConvertAnonymousToNestedRefactoring method updateAndMoveBodyDeclarations.

private void updateAndMoveBodyDeclarations(CompilationUnitRewrite rewriter, IVariableBinding[] bindings, String[] fieldNames, List<BodyDeclaration> newBodyDeclarations, MethodDeclaration newConstructorDecl) {
    final ASTRewrite astRewrite = rewriter.getASTRewrite();
    final AST ast = astRewrite.getAST();
    final boolean useThisAccess = useThisForFieldAccess();
    int fieldInsertIndex = newConstructorDecl != null ? newBodyDeclarations.lastIndexOf(newConstructorDecl) : newBodyDeclarations.size();
    for (Iterator<BodyDeclaration> iterator = fAnonymousInnerClassNode.bodyDeclarations().iterator(); iterator.hasNext(); ) {
        BodyDeclaration body = iterator.next();
        for (int i = 0; i < bindings.length; i++) {
            SimpleName[] names = LinkedNodeFinder.findByBinding(body, bindings[i]);
            String fieldName = fieldNames[i];
            for (int k = 0; k < names.length; k++) {
                SimpleName newNode = ast.newSimpleName(fieldName);
                if (useThisAccess) {
                    FieldAccess access = ast.newFieldAccess();
                    access.setExpression(ast.newThisExpression());
                    access.setName(newNode);
                    astRewrite.replace(names[k], access, null);
                } else {
                    astRewrite.replace(names[k], newNode, null);
                }
                addLinkedPosition(KEY_FIELD_NAME_EXT + i, newNode, astRewrite, false);
            }
        }
        if (body instanceof Initializer || body instanceof FieldDeclaration) {
            newBodyDeclarations.add(fieldInsertIndex++, (BodyDeclaration) astRewrite.createMoveTarget(body));
        } else {
            newBodyDeclarations.add((BodyDeclaration) astRewrite.createMoveTarget(body));
        }
    }
    if (newConstructorDecl != null) {
        // move initialization of existing fields to constructor if an outer is referenced
        List<Statement> bodyStatements = newConstructorDecl.getBody().statements();
        List<VariableDeclarationFragment> fieldsToInitializeInConstructor = getFieldsToInitializeInConstructor();
        for (Iterator<VariableDeclarationFragment> iter = fieldsToInitializeInConstructor.iterator(); iter.hasNext(); ) {
            VariableDeclarationFragment fragment = iter.next();
            Expression initializer = fragment.getInitializer();
            Expression replacement = (Expression) astRewrite.get(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY);
            if (replacement == initializer) {
                replacement = (Expression) astRewrite.createMoveTarget(initializer);
            }
            astRewrite.remove(initializer, null);
            SimpleName fieldNameNode = ast.newSimpleName(fragment.getName().getIdentifier());
            bodyStatements.add(newFieldAssignment(ast, fieldNameNode, replacement, useThisAccess));
        }
    }
}
Also used : AST(org.eclipse.jdt.core.dom.AST) Statement(org.eclipse.jdt.core.dom.Statement) SimpleName(org.eclipse.jdt.core.dom.SimpleName) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) ArrayInitializer(org.eclipse.jdt.core.dom.ArrayInitializer) Initializer(org.eclipse.jdt.core.dom.Initializer) Expression(org.eclipse.jdt.core.dom.Expression) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) FieldAccess(org.eclipse.jdt.core.dom.FieldAccess) SuperFieldAccess(org.eclipse.jdt.core.dom.SuperFieldAccess)

Example 4 with Initializer

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

the class SurroundWithAnalyzer method endVisit.

@Override
public void endVisit(CompilationUnit node) {
    postProcessSelectedNodes(internalGetSelectedNodes());
    BodyDeclaration enclosingNode = null;
    superCall: {
        if (getStatus().hasFatalError())
            break superCall;
        if (!hasSelectedNodes()) {
            ASTNode coveringNode = getLastCoveringNode();
            if (coveringNode instanceof Block) {
                Block block = (Block) coveringNode;
                Message[] messages = ASTNodes.getMessages(block, ASTNodes.NODE_ONLY);
                if (messages.length > 0) {
                    invalidSelection(RefactoringCoreMessages.SurroundWithTryCatchAnalyzer_compile_errors, JavaStatusContext.create(getCompilationUnit(), block));
                    break superCall;
                }
            }
            invalidSelection(RefactoringCoreMessages.SurroundWithTryCatchAnalyzer_doesNotCover);
            break superCall;
        }
        enclosingNode = (BodyDeclaration) ASTNodes.getParent(getFirstSelectedNode(), BodyDeclaration.class);
        if (!(enclosingNode instanceof MethodDeclaration) && !(enclosingNode instanceof Initializer)) {
            invalidSelection(RefactoringCoreMessages.SurroundWithTryCatchAnalyzer_doesNotContain);
            break superCall;
        }
        if (!onlyStatements()) {
            invalidSelection(RefactoringCoreMessages.SurroundWithTryCatchAnalyzer_onlyStatements);
        }
        fLocals = LocalDeclarationAnalyzer.perform(enclosingNode, getSelection());
    }
    super.endVisit(node);
}
Also used : Message(org.eclipse.jdt.core.dom.Message) Initializer(org.eclipse.jdt.core.dom.Initializer) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration)

Example 5 with Initializer

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

the class ExtractMethodAnalyzer method computeLastStatementSelected.

private void computeLastStatementSelected() {
    ASTNode[] nodes = getSelectedNodes();
    if (nodes.length == 0) {
        fIsLastStatementSelected = false;
    } else {
        Block body = null;
        LambdaExpression enclosingLambdaExpr = ASTResolving.findEnclosingLambdaExpression(getFirstSelectedNode());
        if (enclosingLambdaExpr != null) {
            ASTNode lambdaBody = enclosingLambdaExpr.getBody();
            if (lambdaBody instanceof Block) {
                body = (Block) lambdaBody;
            } else {
                fIsLastStatementSelected = true;
                return;
            }
        } else {
            if (fEnclosingBodyDeclaration instanceof MethodDeclaration) {
                body = ((MethodDeclaration) fEnclosingBodyDeclaration).getBody();
            } else if (fEnclosingBodyDeclaration instanceof Initializer) {
                body = ((Initializer) fEnclosingBodyDeclaration).getBody();
            }
        }
        if (body != null) {
            List<Statement> statements = body.statements();
            if (statements.size() > 0) {
                fIsLastStatementSelected = nodes[nodes.length - 1] == statements.get(statements.size() - 1);
            } else {
                fIsLastStatementSelected = true;
            }
        }
    }
}
Also used : Initializer(org.eclipse.jdt.core.dom.Initializer) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) DoStatement(org.eclipse.jdt.core.dom.DoStatement) Statement(org.eclipse.jdt.core.dom.Statement) ContinueStatement(org.eclipse.jdt.core.dom.ContinueStatement) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) SwitchStatement(org.eclipse.jdt.core.dom.SwitchStatement) WhileStatement(org.eclipse.jdt.core.dom.WhileStatement) BreakStatement(org.eclipse.jdt.core.dom.BreakStatement) LabeledStatement(org.eclipse.jdt.core.dom.LabeledStatement) ForStatement(org.eclipse.jdt.core.dom.ForStatement) VariableDeclarationStatement(org.eclipse.jdt.core.dom.VariableDeclarationStatement) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Block(org.eclipse.jdt.core.dom.Block) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression)

Aggregations

Initializer (org.eclipse.jdt.core.dom.Initializer)19 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)15 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)15 ASTNode (org.eclipse.jdt.core.dom.ASTNode)13 FieldDeclaration (org.eclipse.jdt.core.dom.FieldDeclaration)10 Block (org.eclipse.jdt.core.dom.Block)7 AST (org.eclipse.jdt.core.dom.AST)6 Statement (org.eclipse.jdt.core.dom.Statement)6 Expression (org.eclipse.jdt.core.dom.Expression)5 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)5 SimpleName (org.eclipse.jdt.core.dom.SimpleName)5 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)5 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)5 Assignment (org.eclipse.jdt.core.dom.Assignment)4 EnhancedForStatement (org.eclipse.jdt.core.dom.EnhancedForStatement)4 ExpressionStatement (org.eclipse.jdt.core.dom.ExpressionStatement)4 ForStatement (org.eclipse.jdt.core.dom.ForStatement)4 VariableDeclarationExpression (org.eclipse.jdt.core.dom.VariableDeclarationExpression)4 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)4 ArrayInitializer (org.eclipse.jdt.core.dom.ArrayInitializer)3