use of org.eclipse.jdt.core.dom.IVariableBinding in project che by eclipse.
the class AddImportsOperation method evaluateEdits.
private TextEdit evaluateEdits(CompilationUnit root, ImportRewrite importRewrite, int offset, int length, IProgressMonitor monitor) throws JavaModelException {
SimpleName nameNode = null;
if (root != null) {
// got an AST
ASTNode node = NodeFinder.perform(root, offset, length);
if (node instanceof MarkerAnnotation) {
node = ((Annotation) node).getTypeName();
}
if (node instanceof QualifiedName) {
nameNode = ((QualifiedName) node).getName();
} else if (node instanceof SimpleName) {
nameNode = (SimpleName) node;
}
}
String name, simpleName, containerName;
int qualifierStart;
int simpleNameStart;
if (nameNode != null) {
simpleName = nameNode.getIdentifier();
simpleNameStart = nameNode.getStartPosition();
if (nameNode.getLocationInParent() == QualifiedName.NAME_PROPERTY) {
Name qualifier = ((QualifiedName) nameNode.getParent()).getQualifier();
containerName = qualifier.getFullyQualifiedName();
name = JavaModelUtil.concatenateName(containerName, simpleName);
qualifierStart = qualifier.getStartPosition();
} else if (nameNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY) {
NameQualifiedType nameQualifiedType = (NameQualifiedType) nameNode.getParent();
Name qualifier = nameQualifiedType.getQualifier();
containerName = qualifier.getFullyQualifiedName();
name = JavaModelUtil.concatenateName(containerName, simpleName);
qualifierStart = qualifier.getStartPosition();
List<Annotation> annotations = nameQualifiedType.annotations();
if (!annotations.isEmpty()) {
// don't remove annotations
simpleNameStart = annotations.get(0).getStartPosition();
}
} else if (nameNode.getLocationInParent() == MethodInvocation.NAME_PROPERTY) {
ASTNode qualifier = ((MethodInvocation) nameNode.getParent()).getExpression();
if (qualifier instanceof Name) {
containerName = ASTNodes.asString(qualifier);
name = JavaModelUtil.concatenateName(containerName, simpleName);
qualifierStart = qualifier.getStartPosition();
} else {
return null;
}
} else {
//$NON-NLS-1$
containerName = "";
name = simpleName;
qualifierStart = simpleNameStart;
}
IBinding binding = nameNode.resolveBinding();
if (binding != null && !binding.isRecovered()) {
if (binding instanceof ITypeBinding) {
ITypeBinding typeBinding = ((ITypeBinding) binding).getTypeDeclaration();
String qualifiedBindingName = typeBinding.getQualifiedName();
if (containerName.length() > 0 && !qualifiedBindingName.equals(name)) {
return null;
}
ImportRewriteContext context = new ContextSensitiveImportRewriteContext(root, qualifierStart, importRewrite);
String res = importRewrite.addImport(typeBinding, context);
if (containerName.length() > 0 && !res.equals(simpleName)) {
// adding import failed
fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_importclash, null);
return null;
}
if (containerName.length() == 0 && res.equals(simpleName)) {
// no change necessary
return null;
}
return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, new String());
} else if (JavaModelUtil.is50OrHigher(fCompilationUnit.getJavaProject()) && (binding instanceof IVariableBinding || binding instanceof IMethodBinding)) {
boolean isField = binding instanceof IVariableBinding;
ITypeBinding declaringClass = isField ? ((IVariableBinding) binding).getDeclaringClass() : ((IMethodBinding) binding).getDeclaringClass();
if (declaringClass == null) {
// variableBinding.getDeclaringClass() is null for array.length
return null;
}
if (Modifier.isStatic(binding.getModifiers())) {
if (containerName.length() > 0) {
if (containerName.equals(declaringClass.getName()) || containerName.equals(declaringClass.getQualifiedName())) {
ASTNode node = nameNode.getParent();
boolean isDirectlyAccessible = false;
while (node != null) {
if (isTypeDeclarationSubTypeCompatible(node, declaringClass)) {
isDirectlyAccessible = true;
break;
}
node = node.getParent();
}
if (!isDirectlyAccessible) {
if (Modifier.isPrivate(declaringClass.getModifiers())) {
fStatus = JavaUIStatus.createError(IStatus.ERROR, Messages.format(CodeGenerationMessages.AddImportsOperation_error_not_visible_class, BasicElementLabels.getJavaElementName(declaringClass.getName())), null);
return null;
}
String res = importRewrite.addStaticImport(declaringClass.getQualifiedName(), binding.getName(), isField);
if (!res.equals(simpleName)) {
// adding import failed
return null;
}
}
//$NON-NLS-1$
return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
}
}
}
// no static imports for packages
return null;
} else {
return null;
}
}
if (binding != null && binding.getKind() != IBinding.TYPE) {
// recovered binding
return null;
}
} else {
IBuffer buffer = fCompilationUnit.getBuffer();
qualifierStart = getNameStart(buffer, offset);
int nameEnd = getNameEnd(buffer, offset + length);
int len = nameEnd - qualifierStart;
name = buffer.getText(qualifierStart, len).trim();
if (name.length() == 0) {
return null;
}
simpleName = Signature.getSimpleName(name);
containerName = Signature.getQualifier(name);
IJavaProject javaProject = fCompilationUnit.getJavaProject();
if (simpleName.length() == 0 || JavaConventionsUtil.validateJavaTypeName(simpleName, javaProject).matches(IStatus.ERROR) || (containerName.length() > 0 && JavaConventionsUtil.validateJavaTypeName(containerName, javaProject).matches(IStatus.ERROR))) {
fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_invalid_selection, null);
return null;
}
simpleNameStart = getSimpleNameStart(buffer, qualifierStart, containerName);
int res = importRewrite.getDefaultImportRewriteContext().findInContext(containerName, simpleName, ImportRewriteContext.KIND_TYPE);
if (res == ImportRewriteContext.RES_NAME_CONFLICT) {
fStatus = JavaUIStatus.createError(IStatus.ERROR, CodeGenerationMessages.AddImportsOperation_error_importclash, null);
return null;
} else if (res == ImportRewriteContext.RES_NAME_FOUND) {
//$NON-NLS-1$
return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
}
}
IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { fCompilationUnit.getJavaProject() });
TypeNameMatch[] types = findAllTypes(simpleName, searchScope, nameNode, new SubProgressMonitor(monitor, 1));
if (types.length == 0) {
fStatus = JavaUIStatus.createError(IStatus.ERROR, Messages.format(CodeGenerationMessages.AddImportsOperation_error_notresolved_message, BasicElementLabels.getJavaElementName(simpleName)), null);
return null;
}
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
TypeNameMatch chosen;
if (types.length > 1 && fQuery != null) {
chosen = fQuery.chooseImport(types, containerName);
if (chosen == null) {
throw new OperationCanceledException();
}
} else {
chosen = types[0];
}
ImportRewriteContext context = root == null ? null : new ContextSensitiveImportRewriteContext(root, simpleNameStart, importRewrite);
importRewrite.addImport(chosen.getFullyQualifiedName(), context);
//$NON-NLS-1$
return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, "");
}
use of org.eclipse.jdt.core.dom.IVariableBinding 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.IVariableBinding 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.IVariableBinding 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.IVariableBinding in project che by eclipse.
the class UnresolvedElementsSubProcessor method hasMethodWithName.
private static boolean hasMethodWithName(ITypeBinding typeBinding, String name) {
IVariableBinding[] fields = typeBinding.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
if (fields[i].getName().equals(name)) {
return true;
}
}
ITypeBinding superclass = typeBinding.getSuperclass();
if (superclass != null) {
return hasMethodWithName(superclass, name);
}
return false;
}
Aggregations