Search in sources :

Example 26 with ASTNode

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

the class NewMethodCorrectionProposal method getNewName.

/* (non-Javadoc)
	 * @see org.eclipse.jdt.internal.ui.text.correction.proposals.AbstractMethodCorrectionProposal#getNewName(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)
	 */
@Override
protected SimpleName getNewName(ASTRewrite rewrite) {
    ASTNode invocationNode = getInvocationNode();
    String name;
    if (invocationNode instanceof MethodInvocation) {
        name = ((MethodInvocation) invocationNode).getName().getIdentifier();
    } else if (invocationNode instanceof SuperMethodInvocation) {
        name = ((SuperMethodInvocation) invocationNode).getName().getIdentifier();
    } else {
        // name of the class
        name = getSenderBinding().getName();
    }
    AST ast = rewrite.getAST();
    SimpleName newNameNode = ast.newSimpleName(name);
    addLinkedPosition(rewrite.track(newNameNode), false, KEY_NAME);
    ASTNode invocationName = getInvocationNameNode();
    if (invocationName != null && invocationName.getAST() == ast) {
        // in the same CU
        addLinkedPosition(rewrite.track(invocationName), true, KEY_NAME);
    }
    return newNameNode;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ASTNode(org.eclipse.jdt.core.dom.ASTNode) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation)

Example 27 with ASTNode

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

the class NewVariableCorrectionProposal method getDominantNode.

private ASTNode getDominantNode(SimpleName[] names) {
    //ASTResolving.findParentStatement(names[0]);
    ASTNode dominator = names[0];
    for (int i = 1; i < names.length; i++) {
        // ASTResolving.findParentStatement(names[i]);
        ASTNode curr = names[i];
        if (curr != dominator) {
            ASTNode parent = getCommonParent(curr, dominator);
            if (curr.getStartPosition() < dominator.getStartPosition()) {
                dominator = curr;
            }
            while (dominator.getParent() != parent) {
                dominator = dominator.getParent();
            }
        }
    }
    int parentKind = dominator.getParent().getNodeType();
    if (parentKind != ASTNode.BLOCK && parentKind != ASTNode.FOR_STATEMENT) {
        return dominator.getParent();
    }
    return dominator;
}
Also used : ASTNode(org.eclipse.jdt.core.dom.ASTNode)

Example 28 with ASTNode

use of org.eclipse.jdt.core.dom.ASTNode 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 29 with ASTNode

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

the class NewVariableCorrectionProposal method doAddEnumConst.

private ASTRewrite doAddEnumConst(CompilationUnit astRoot) {
    SimpleName node = fOriginalNode;
    ASTNode newTypeDecl = astRoot.findDeclaringNode(fSenderBinding);
    if (newTypeDecl == null) {
        astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
        newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey());
    }
    if (newTypeDecl != null) {
        AST ast = newTypeDecl.getAST();
        ASTRewrite rewrite = ASTRewrite.create(ast);
        EnumConstantDeclaration constDecl = ast.newEnumConstantDeclaration();
        constDecl.setName(ast.newSimpleName(node.getIdentifier()));
        ListRewrite listRewriter = rewrite.getListRewrite(newTypeDecl, EnumDeclaration.ENUM_CONSTANTS_PROPERTY);
        listRewriter.insertLast(constDecl, null);
        addLinkedPosition(rewrite.track(constDecl.getName()), false, KEY_NAME);
        return rewrite;
    }
    return null;
}
Also used : EnumConstantDeclaration(org.eclipse.jdt.core.dom.EnumConstantDeclaration) AST(org.eclipse.jdt.core.dom.AST) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ListRewrite(org.eclipse.jdt.core.dom.rewrite.ListRewrite)

Example 30 with ASTNode

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

the class LinkedNamesAssistProposal method apply.

/* (non-Javadoc)
     * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int)
     */
public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) {
    try {
        Point seletion = viewer.getSelectedRange();
        // get full ast
        CompilationUnit root = SharedASTProvider.getAST(fContext.getCompilationUnit(), SharedASTProvider.WAIT_YES, null);
        ASTNode nameNode = NodeFinder.perform(root, fNode.getStartPosition(), fNode.getLength());
        final int pos = fNode.getStartPosition();
        ASTNode[] sameNodes;
        if (nameNode instanceof SimpleName) {
            sameNodes = LinkedNodeFinder.findByNode(root, (SimpleName) nameNode);
        } else {
            sameNodes = new ASTNode[] { nameNode };
        }
        // sort for iteration order, starting with the node @ offset
        Arrays.sort(sameNodes, new Comparator<ASTNode>() {

            public int compare(ASTNode o1, ASTNode o2) {
                return rank(o1) - rank(o2);
            }

            /**
                 * Returns the absolute rank of an <code>ASTNode</code>. Nodes
                 * preceding <code>offset</code> are ranked last.
                 *
                 * @param node the node to compute the rank for
                 * @return the rank of the node with respect to the invocation offset
                 */
            private int rank(ASTNode node) {
                int relativeRank = node.getStartPosition() + node.getLength() - pos;
                if (relativeRank < 0)
                    return Integer.MAX_VALUE + relativeRank;
                else
                    return relativeRank;
            }
        });
        IDocument document = viewer.getDocument();
        LinkedPositionGroupImpl group = new LinkedPositionGroupImpl();
        for (int i = 0; i < sameNodes.length; i++) {
            ASTNode elem = sameNodes[i];
            RegionImpl region = new RegionImpl();
            region.setOffset(elem.getStartPosition());
            region.setLength(elem.getLength());
            group.addPositions(region);
        //				group.addPosition(new LinkedPosition(document, elem.getStartPosition(), elem.getLength(), i));
        }
        LinkedModeModelImpl model = new LinkedModeModelImpl();
        model.addGroups(group);
        //			model.forceInstall();
        model.setEscapePosition(offset);
        this.linkedModel = model;
        if (fContext instanceof AssistContext) {
        //				IEditorPart editor = ((AssistContext)fContext).getEditor();
        //				if (editor instanceof JavaEditor) {
        //					model.addLinkingListener(new EditorHighlightingSynchronizer((JavaEditor)editor));
        //				}
        }
        if (fValueSuggestion != null) {
            document.replace(nameNode.getStartPosition(), nameNode.getLength(), fValueSuggestion);
        //				IRegion selectedRegion = ui.getSelectedRegion();
        //				seletion = new Point(selectedRegion.getOffset(), fValueSuggestion.length());
        }
    //			viewer.setSelectedRange(seletion.x, seletion.y); // by default full word is selected, restore original selection
    } catch (BadLocationException e) {
        JavaPlugin.log(e);
    }
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) LinkedPositionGroupImpl(org.eclipse.che.plugin.java.server.dto.DtoServerImpls.LinkedPositionGroupImpl) AssistContext(org.eclipse.jdt.internal.ui.text.correction.AssistContext) SimpleName(org.eclipse.jdt.core.dom.SimpleName) LinkedModeModelImpl(org.eclipse.che.plugin.java.server.dto.DtoServerImpls.LinkedModeModelImpl) Point(org.eclipse.swt.graphics.Point) Point(org.eclipse.swt.graphics.Point) ASTNode(org.eclipse.jdt.core.dom.ASTNode) RegionImpl(org.eclipse.che.plugin.java.server.dto.DtoServerImpls.RegionImpl) IDocument(org.eclipse.jface.text.IDocument) BadLocationException(org.eclipse.jface.text.BadLocationException)

Aggregations

ASTNode (org.eclipse.jdt.core.dom.ASTNode)710 SimpleName (org.eclipse.jdt.core.dom.SimpleName)151 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)148 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)147 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)134 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)126 Expression (org.eclipse.jdt.core.dom.Expression)125 ArrayList (java.util.ArrayList)111 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)108 AST (org.eclipse.jdt.core.dom.AST)106 Type (org.eclipse.jdt.core.dom.Type)92 Block (org.eclipse.jdt.core.dom.Block)89 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)77 IMethodBinding (org.eclipse.jdt.core.dom.IMethodBinding)73 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)67 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)66 ListRewrite (org.eclipse.jdt.core.dom.rewrite.ListRewrite)65 CastExpression (org.eclipse.jdt.core.dom.CastExpression)64 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)62 VariableDeclarationStatement (org.eclipse.jdt.core.dom.VariableDeclarationStatement)60