use of org.eclipse.jdt.core.dom.IBinding in project che by eclipse.
the class UnresolvedElementsSubProcessor method getExpressionBaseName.
private static String getExpressionBaseName(Expression expr) {
IBinding argBinding = Bindings.resolveExpressionBinding(expr, true);
if (argBinding instanceof IVariableBinding) {
IJavaProject project = null;
ASTNode root = expr.getRoot();
if (root instanceof CompilationUnit) {
ITypeRoot typeRoot = ((CompilationUnit) root).getTypeRoot();
if (typeRoot != null)
project = typeRoot.getJavaProject();
}
return StubUtility.getBaseName((IVariableBinding) argBinding, project);
}
if (expr instanceof SimpleName)
return ((SimpleName) expr).getIdentifier();
return null;
}
use of org.eclipse.jdt.core.dom.IBinding in project che by eclipse.
the class UnresolvedElementsSubProcessor method getArrayAccessProposals.
public static void getArrayAccessProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
CompilationUnit root = context.getASTRoot();
ASTNode selectedNode = problem.getCoveringNode(root);
if (!(selectedNode instanceof MethodInvocation)) {
return;
}
MethodInvocation decl = (MethodInvocation) selectedNode;
SimpleName nameNode = decl.getName();
String methodName = nameNode.getIdentifier();
IBinding[] bindings = (new ScopeAnalyzer(root)).getDeclarationsInScope(nameNode, ScopeAnalyzer.METHODS);
for (int i = 0; i < bindings.length; i++) {
String currName = bindings[i].getName();
if (NameMatcher.isSimilarName(methodName, currName)) {
String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_arraychangetomethod_description, BasicElementLabels.getJavaElementName(currName));
proposals.add(new RenameNodeCorrectionProposal(label, context.getCompilationUnit(), nameNode.getStartPosition(), nameNode.getLength(), currName, IProposalRelevance.ARRAY_CHANGE_TO_METHOD));
}
}
// always suggest 'length'
//$NON-NLS-1$
String lengthId = "length";
String label = CorrectionMessages.UnresolvedElementsSubProcessor_arraychangetolength_description;
int offset = nameNode.getStartPosition();
int length = decl.getStartPosition() + decl.getLength() - offset;
proposals.add(new RenameNodeCorrectionProposal(label, context.getCompilationUnit(), offset, length, lengthId, IProposalRelevance.ARRAY_CHANGE_TO_LENGTH));
}
use of org.eclipse.jdt.core.dom.IBinding 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;
}
use of org.eclipse.jdt.core.dom.IBinding in project che by eclipse.
the class TypeMismatchSubProcessor method addChangeSenderTypeProposals.
public static void addChangeSenderTypeProposals(IInvocationContext context, Expression nodeToCast, ITypeBinding castTypeBinding, boolean isAssignedNode, int relevance, Collection<ICommandAccess> proposals) throws JavaModelException {
IBinding callerBinding = Bindings.resolveExpressionBinding(nodeToCast, false);
ICompilationUnit cu = context.getCompilationUnit();
CompilationUnit astRoot = context.getASTRoot();
ICompilationUnit targetCu = null;
ITypeBinding declaringType = null;
IBinding callerBindingDecl = callerBinding;
if (callerBinding instanceof IVariableBinding) {
IVariableBinding variableBinding = (IVariableBinding) callerBinding;
if (variableBinding.isEnumConstant()) {
return;
}
if (!variableBinding.isField()) {
targetCu = cu;
} else {
callerBindingDecl = variableBinding.getVariableDeclaration();
ITypeBinding declaringClass = variableBinding.getDeclaringClass();
if (declaringClass == null) {
// array length
return;
}
declaringType = declaringClass.getTypeDeclaration();
}
} else if (callerBinding instanceof IMethodBinding) {
IMethodBinding methodBinding = (IMethodBinding) callerBinding;
if (!methodBinding.isConstructor()) {
declaringType = methodBinding.getDeclaringClass().getTypeDeclaration();
callerBindingDecl = methodBinding.getMethodDeclaration();
}
} else if (callerBinding instanceof ITypeBinding && nodeToCast.getLocationInParent() == SingleMemberAnnotation.TYPE_NAME_PROPERTY) {
declaringType = (ITypeBinding) callerBinding;
//$NON-NLS-1$
callerBindingDecl = Bindings.findMethodInType(declaringType, "value", (String[]) null);
if (callerBindingDecl == null) {
return;
}
}
if (declaringType != null && declaringType.isFromSource()) {
targetCu = ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
}
if (targetCu != null && ASTResolving.isUseableTypeInContext(castTypeBinding, callerBindingDecl, false)) {
proposals.add(new TypeChangeCorrectionProposal(targetCu, callerBindingDecl, astRoot, castTypeBinding, isAssignedNode, relevance));
}
// add interface to resulting type
if (!isAssignedNode) {
ITypeBinding nodeType = nodeToCast.resolveTypeBinding();
if (castTypeBinding.isInterface() && nodeType != null && nodeType.isClass() && !nodeType.isAnonymous() && nodeType.isFromSource()) {
ITypeBinding typeDecl = nodeType.getTypeDeclaration();
ICompilationUnit nodeCu = ASTResolving.findCompilationUnitForBinding(cu, astRoot, typeDecl);
if (nodeCu != null && ASTResolving.isUseableTypeInContext(castTypeBinding, typeDecl, true)) {
proposals.add(new ImplementInterfaceProposal(nodeCu, typeDecl, astRoot, castTypeBinding, relevance - 1));
}
}
}
}
use of org.eclipse.jdt.core.dom.IBinding 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));
}
}
Aggregations