Search in sources :

Example 21 with SimpleName

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

the class GenerateForLoopAssistProposal method resolveLinkedVariableNameWithProposals.

/**
	 * Resolves name proposals by the given basename and adds a {@link LinkedPosition} to the
	 * returned {@link SimpleName} expression.
	 * 
	 * @param rewrite the current instance of an {@link ASTRewrite}
	 * @param basename the base string to use for proposal calculation
	 * @param excludedName a name that cannot be used for the variable; <code>null</code> if none
	 * @param firstLinkedProposal true if the generated name is the first {@link LinkedPosition} to
	 *            edit in the current {@link CompilationUnit}, false otherwise
	 * @return the linked {@link SimpleName} instance based on the name proposals
	 */
private SimpleName resolveLinkedVariableNameWithProposals(ASTRewrite rewrite, String basename, String excludedName, boolean firstLinkedProposal) {
    AST ast = rewrite.getAST();
    String[] nameProposals = getVariableNameProposals(basename, excludedName);
    SimpleName forDeclarationName = ast.newSimpleName(nameProposals.length > 0 ? nameProposals[0] : basename);
    for (int i = 0; i < nameProposals.length; i++) {
        addLinkedPositionProposal(forDeclarationName.getIdentifier(), nameProposals[i], null);
    }
    // mark declaration name as editable
    addLinkedPosition(rewrite.track(forDeclarationName), firstLinkedProposal, forDeclarationName.getIdentifier());
    return forDeclarationName;
}
Also used : AST(org.eclipse.jdt.core.dom.AST) SimpleName(org.eclipse.jdt.core.dom.SimpleName)

Example 22 with SimpleName

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

the class GenerateForLoopAssistProposal method generateForEachRewrite.

/**
	 * Helper to generate a <code>foreach</code> loop to iterate over an {@link Iterable}.
	 *
	 * @param ast the {@link AST} instance to rewrite the loop to
	 * @return the complete {@link ASTRewrite} object
	 */
private ASTRewrite generateForEachRewrite(AST ast) {
    EnhancedForStatement loopStatement = ast.newEnhancedForStatement();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    ITypeBinding loopOverType = extractElementType(ast);
    // generate name proposals and add them to the variable declaration
    SimpleName forDeclarationName = resolveLinkedVariableNameWithProposals(rewrite, loopOverType.getName(), null, true);
    SingleVariableDeclaration forLoopInitializer = ast.newSingleVariableDeclaration();
    forLoopInitializer.setType(getImportRewrite().addImport(loopOverType, ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite())));
    forLoopInitializer.setName(forDeclarationName);
    loopStatement.setParameter(forLoopInitializer);
    loopStatement.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression));
    Block forLoopBody = ast.newBlock();
    forLoopBody.statements().add(createBlankLineStatementWithCursorPosition(rewrite));
    loopStatement.setBody(forLoopBody);
    rewrite.replace(fCurrentNode, loopStatement, null);
    return rewrite;
}
Also used : ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Block(org.eclipse.jdt.core.dom.Block) EnhancedForStatement(org.eclipse.jdt.core.dom.EnhancedForStatement)

Example 23 with SimpleName

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

Example 24 with SimpleName

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

the class UnresolvedElementsSubProcessor method addSimilarVariableProposals.

private static void addSimilarVariableProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, IVariableBinding resolvedField, SimpleName node, boolean isWriteAccess, Collection<ICommandAccess> proposals) {
    int kind = ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY;
    if (!isWriteAccess) {
        // also try to find similar methods
        kind |= ScopeAnalyzer.METHODS;
    }
    IBinding[] varsAndMethodsInScope = (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(node, kind);
    if (varsAndMethodsInScope.length > 0) {
        // avoid corrections like int i= i;
        String otherNameInAssign = null;
        // help with x.getString() -> y.getString()
        String methodSenderName = null;
        String fieldSenderName = null;
        ASTNode parent = node.getParent();
        switch(parent.getNodeType()) {
            case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
                // node must be initializer
                otherNameInAssign = ((VariableDeclarationFragment) parent).getName().getIdentifier();
                break;
            case ASTNode.ASSIGNMENT:
                Assignment assignment = (Assignment) parent;
                if (isWriteAccess && assignment.getRightHandSide() instanceof SimpleName) {
                    otherNameInAssign = ((SimpleName) assignment.getRightHandSide()).getIdentifier();
                } else if (!isWriteAccess && assignment.getLeftHandSide() instanceof SimpleName) {
                    otherNameInAssign = ((SimpleName) assignment.getLeftHandSide()).getIdentifier();
                }
                break;
            case ASTNode.METHOD_INVOCATION:
                MethodInvocation inv = (MethodInvocation) parent;
                if (inv.getExpression() == node) {
                    methodSenderName = inv.getName().getIdentifier();
                }
                break;
            case ASTNode.QUALIFIED_NAME:
                QualifiedName qualName = (QualifiedName) parent;
                if (qualName.getQualifier() == node) {
                    fieldSenderName = qualName.getName().getIdentifier();
                }
                break;
        }
        ITypeBinding guessedType = ASTResolving.guessBindingForReference(node);
        //$NON-NLS-1$
        ITypeBinding objectBinding = astRoot.getAST().resolveWellKnownType("java.lang.Object");
        String identifier = node.getIdentifier();
        boolean isInStaticContext = ASTResolving.isInStaticContext(node);
        ArrayList<CUCorrectionProposal> newProposals = new ArrayList<CUCorrectionProposal>(51);
        loop: for (int i = 0; i < varsAndMethodsInScope.length && newProposals.size() <= 50; i++) {
            IBinding varOrMeth = varsAndMethodsInScope[i];
            if (varOrMeth instanceof IVariableBinding) {
                IVariableBinding curr = (IVariableBinding) varOrMeth;
                String currName = curr.getName();
                if (currName.equals(otherNameInAssign)) {
                    continue loop;
                }
                if (resolvedField != null && Bindings.equals(resolvedField, curr)) {
                    continue loop;
                }
                boolean isFinal = Modifier.isFinal(curr.getModifiers());
                if (isFinal && curr.isField() && isWriteAccess) {
                    continue loop;
                }
                if (isInStaticContext && !Modifier.isStatic(curr.getModifiers()) && curr.isField()) {
                    continue loop;
                }
                int relevance = IProposalRelevance.SIMILAR_VARIABLE_PROPOSAL;
                if (NameMatcher.isSimilarName(currName, identifier)) {
                    // variable with a similar name than the unresolved variable
                    relevance += 3;
                }
                if (currName.equalsIgnoreCase(identifier)) {
                    relevance += 5;
                }
                ITypeBinding varType = curr.getType();
                if (varType != null) {
                    if (guessedType != null && guessedType != objectBinding) {
                        // variable type is compatible with the guessed type
                        if (!isWriteAccess && canAssign(varType, guessedType) || isWriteAccess && canAssign(guessedType, varType)) {
                            // unresolved variable can be assign to this variable
                            relevance += 2;
                        }
                    }
                    if (methodSenderName != null && hasMethodWithName(varType, methodSenderName)) {
                        relevance += 2;
                    }
                    if (fieldSenderName != null && hasFieldWithName(varType, fieldSenderName)) {
                        relevance += 2;
                    }
                }
                if (relevance > 0) {
                    String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changevariable_description, BasicElementLabels.getJavaElementName(currName));
                    newProposals.add(new RenameNodeCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), currName, relevance));
                }
            } else if (varOrMeth instanceof IMethodBinding) {
                IMethodBinding curr = (IMethodBinding) varOrMeth;
                if (!curr.isConstructor() && guessedType != null && canAssign(curr.getReturnType(), guessedType)) {
                    if (NameMatcher.isSimilarName(curr.getName(), identifier)) {
                        AST ast = astRoot.getAST();
                        ASTRewrite rewrite = ASTRewrite.create(ast);
                        String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetomethod_description, ASTResolving.getMethodSignature(curr));
                        Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
                        LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_TO_METHOD, image);
                        newProposals.add(proposal);
                        MethodInvocation newInv = ast.newMethodInvocation();
                        newInv.setName(ast.newSimpleName(curr.getName()));
                        ITypeBinding[] parameterTypes = curr.getParameterTypes();
                        for (int k = 0; k < parameterTypes.length; k++) {
                            ASTNode arg = ASTNodeFactory.newDefaultExpression(ast, parameterTypes[k]);
                            newInv.arguments().add(arg);
                            proposal.addLinkedPosition(rewrite.track(arg), false, null);
                        }
                        rewrite.replace(node, newInv, null);
                    }
                }
            }
        }
        if (newProposals.size() <= 50)
            proposals.addAll(newProposals);
    }
    if (binding != null && binding.isArray()) {
        //$NON-NLS-1$
        String idLength = "length";
        String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changevariable_description, idLength);
        proposals.add(new RenameNodeCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), idLength, IProposalRelevance.CHANGE_VARIABLE));
    }
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) AST(org.eclipse.jdt.core.dom.AST) IBinding(org.eclipse.jdt.core.dom.IBinding) SimpleName(org.eclipse.jdt.core.dom.SimpleName) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) ArrayList(java.util.ArrayList) MethodInvocation(org.eclipse.jdt.core.dom.MethodInvocation) SuperMethodInvocation(org.eclipse.jdt.core.dom.SuperMethodInvocation) IVariableBinding(org.eclipse.jdt.core.dom.IVariableBinding) Image(org.eclipse.swt.graphics.Image) Assignment(org.eclipse.jdt.core.dom.Assignment) RenameNodeCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.RenameNodeCorrectionProposal) CUCorrectionProposal(org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) LinkedCorrectionProposal(org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ScopeAnalyzer(org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 25 with SimpleName

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

the class JavadocContentAccess2 method handleInheritDoc.

/**
     * Handle {&#64;inheritDoc}.
     *
     * @param node
     *         the node
     * @return <code>true</code> iff the node was an {&#64;inheritDoc} node and has been handled
     */
private boolean handleInheritDoc(TagElement node) {
    if (!TagElement.TAG_INHERITDOC.equals(node.getTagName()))
        return false;
    try {
        if (fMethod == null)
            return false;
        TagElement blockTag = (TagElement) node.getParent();
        String blockTagName = blockTag.getTagName();
        if (blockTagName == null) {
            CharSequence inherited = fJavadocLookup.getInheritedMainDescription(fMethod);
            return handleInherited(inherited);
        } else if (TagElement.TAG_PARAM.equals(blockTagName)) {
            List<? extends ASTNode> fragments = blockTag.fragments();
            if (fragments.size() > 0) {
                Object first = fragments.get(0);
                if (first instanceof SimpleName) {
                    String name = ((SimpleName) first).getIdentifier();
                    String[] parameterNames = fMethod.getParameterNames();
                    for (int i = 0; i < parameterNames.length; i++) {
                        if (name.equals(parameterNames[i])) {
                            CharSequence inherited = fJavadocLookup.getInheritedParamDescription(fMethod, i);
                            return handleInherited(inherited);
                        }
                    }
                }
            }
        } else if (TagElement.TAG_RETURN.equals(blockTagName)) {
            CharSequence inherited = fJavadocLookup.getInheritedReturnDescription(fMethod);
            return handleInherited(inherited);
        } else if (TagElement.TAG_THROWS.equals(blockTagName) || TagElement.TAG_EXCEPTION.equals(blockTagName)) {
            List<? extends ASTNode> fragments = blockTag.fragments();
            if (fragments.size() > 0) {
                Object first = fragments.get(0);
                if (first instanceof Name) {
                    String name = ASTNodes.getSimpleNameIdentifier((Name) first);
                    CharSequence inherited = fJavadocLookup.getInheritedExceptionDescription(fMethod, name);
                    return handleInherited(inherited);
                }
            }
        }
    } catch (JavaModelException e) {
        LOG.error(e.getMessage(), e);
    }
    return false;
}
Also used : JavaModelException(org.eclipse.jdt.core.JavaModelException) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ASTNode(org.eclipse.jdt.core.dom.ASTNode) TagElement(org.eclipse.jdt.core.dom.TagElement) List(java.util.List) ArrayList(java.util.ArrayList) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name)

Aggregations

SimpleName (org.eclipse.jdt.core.dom.SimpleName)291 ASTNode (org.eclipse.jdt.core.dom.ASTNode)122 IBinding (org.eclipse.jdt.core.dom.IBinding)70 Expression (org.eclipse.jdt.core.dom.Expression)67 AST (org.eclipse.jdt.core.dom.AST)63 ArrayList (java.util.ArrayList)60 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)57 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)55 IVariableBinding (org.eclipse.jdt.core.dom.IVariableBinding)53 MethodInvocation (org.eclipse.jdt.core.dom.MethodInvocation)47 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)46 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)44 QualifiedName (org.eclipse.jdt.core.dom.QualifiedName)43 ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)41 Name (org.eclipse.jdt.core.dom.Name)40 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)35 Type (org.eclipse.jdt.core.dom.Type)35 Block (org.eclipse.jdt.core.dom.Block)34 ThisExpression (org.eclipse.jdt.core.dom.ThisExpression)33 Assignment (org.eclipse.jdt.core.dom.Assignment)32