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;
}
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;
}
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);
}
}
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));
}
}
use of org.eclipse.jdt.core.dom.SimpleName in project che by eclipse.
the class JavadocContentAccess2 method handleInheritDoc.
/**
* Handle {@inheritDoc}.
*
* @param node
* the node
* @return <code>true</code> iff the node was an {@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;
}
Aggregations