Java Code Examples for org.eclipse.jdt.core.dom.ITypeBinding#getTypeDeclaration()

The following examples show how to use org.eclipse.jdt.core.dom.ITypeBinding#getTypeDeclaration() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TypeChangeCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void sortTypes(ITypeBinding[] typeProposals) {
	ITypeBinding oldType;
	if (fBinding instanceof IMethodBinding) {
		oldType= ((IMethodBinding) fBinding).getReturnType();
	} else {
		oldType= ((IVariableBinding) fBinding).getType();
	}
	if (! oldType.isParameterizedType()) {
		return;
	}

	final ITypeBinding oldTypeDeclaration= oldType.getTypeDeclaration();
	Arrays.sort(typeProposals, new Comparator<ITypeBinding>() {
		@Override
		public int compare(ITypeBinding o1, ITypeBinding o2) {
			return rank(o2) - rank(o1);
		}

		private int rank(ITypeBinding type) {
			if (type.getTypeDeclaration().equals(oldTypeDeclaration)) {
				return 1;
			}
			return 0;
		}
	});
}
 
Example 2
Source File: TypeChangeCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void sortTypes(ITypeBinding[] typeProposals) {
	ITypeBinding oldType;
	if (fBinding instanceof IMethodBinding) {
		oldType= ((IMethodBinding) fBinding).getReturnType();
	} else {
		oldType= ((IVariableBinding) fBinding).getType();
	}
	if (! oldType.isParameterizedType())
		return;
	
	final ITypeBinding oldTypeDeclaration= oldType.getTypeDeclaration();
	Arrays.sort(typeProposals, new Comparator<ITypeBinding>() {
		public int compare(ITypeBinding o1, ITypeBinding o2) {
			return rank(o2) - rank(o1);
		}

		private int rank(ITypeBinding type) {
			if (type.getTypeDeclaration().equals(oldTypeDeclaration))
				return 1;
			return 0;
		}
	});
}
 
Example 3
Source File: ScopeAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Evaluates if the declaration is visible in a certain context.
 * @param binding The binding of the declaration to examine
 * @param context The context to test in
 * @return Returns
 */
public static boolean isVisible(IBinding binding, ITypeBinding context) {
	if (binding.getKind() == IBinding.VARIABLE && !((IVariableBinding) binding).isField()) {
		return true; // all local variables found are visible
	}
	ITypeBinding declaring= getDeclaringType(binding);
	if (declaring == null) {
		return false;
	}

	declaring= declaring.getTypeDeclaration();

	int modifiers= binding.getModifiers();
	if (Modifier.isPublic(modifiers) || declaring.isInterface()) {
		return true;
	} else if (Modifier.isProtected(modifiers) || !Modifier.isPrivate(modifiers)) {
		if (declaring.getPackage() == context.getPackage()) {
			return true;
		}
		return isTypeInScope(declaring, context, Modifier.isProtected(modifiers));
	}
	// private visibility
	return isTypeInScope(declaring, context, false);
}
 
Example 4
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private ITypeBinding getExpressionType(final MethodInvocation invocation, ITypeBinding typeBinding) {
	if (typeBinding == null)
		return null;
	for (IMethodBinding iMethodBinding : typeBinding.getDeclaredMethods()) {
		if (invocation.resolveMethodBinding() == iMethodBinding)
			return typeBinding.getTypeDeclaration();
	}
	ITypeBinding expressionType= getExpressionType(invocation, typeBinding.getSuperclass());
	if (expressionType != null) {
		return expressionType;
	}
	for (ITypeBinding interfaceBinding : typeBinding.getInterfaces()) {
		expressionType= getExpressionType(invocation, interfaceBinding);
		if (expressionType != null) {
			return expressionType;
		}
	}
	return null;
}
 
Example 5
Source File: SourceProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void updateTypeReferences(ASTRewrite rewriter, CallContext context) {
	ImportRewrite importer= context.importer;
	for (Iterator<SimpleName> iter= fAnalyzer.getTypesToImport().iterator(); iter.hasNext();) {
		Name element= iter.next();
		ITypeBinding binding= ASTNodes.getTypeBinding(element);
		if (binding != null && !binding.isLocal()) {
			// We have collected names not types. So we have to import
			// the declaration type if we reference a parameterized type
			// since we have an entry for every name node (e.g. one for
			// Vector and one for Integer in Vector<Integer>.
			if (binding.isParameterizedType()) {
				binding= binding.getTypeDeclaration();
			}
			String s= importer.addImport(binding);
			if (!ASTNodes.asString(element).equals(s)) {
				rewriter.replace(element, rewriter.createStringPlaceholder(s, ASTNode.SIMPLE_NAME), null);
			}
		}
	}
}
 
Example 6
Source File: ReferenceAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(TypeDeclaration node) {
	ITypeBinding binding= node.resolveBinding();
	if (binding != null) {
		binding= binding.getTypeDeclaration();
		if (isMovedMember(binding))
			return false;
	}
	return super.visit(node);
}
 
Example 7
Source File: ASTNodeMatcher.java    From JDeodorant with MIT License 5 votes vote down vote up
private boolean subclassTypeMismatch(ITypeBinding nodeTypeBinding, ITypeBinding otherTypeBinding) {
	if(nodeTypeBinding.isParameterizedType() && otherTypeBinding.isParameterizedType()) {
		ITypeBinding declarationTypeBinding1 = nodeTypeBinding.getTypeDeclaration();
		ITypeBinding declarationTypeBinding2 = otherTypeBinding.getTypeDeclaration();
		return !declarationTypeBinding1.isEqualTo(declarationTypeBinding2) || !typeBindingMatch(nodeTypeBinding, otherTypeBinding);
	}
	return !nodeTypeBinding.isEqualTo(otherTypeBinding) || !nodeTypeBinding.getQualifiedName().equals(otherTypeBinding.getQualifiedName());
}
 
Example 8
Source File: CodeStyleFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static String getThisExpressionQualifier(ITypeBinding declaringClass, ImportRewrite imports, SimpleName name) {
	ITypeBinding parentType= Bindings.getBindingOfParentType(name);
	ITypeBinding currType= parentType;
	while (currType != null && !Bindings.isSuperType(declaringClass, currType)) {
		currType= currType.getDeclaringClass();
	}
	if (currType == null) {
		declaringClass= declaringClass.getTypeDeclaration();
		currType= parentType;
		while (currType != null && !Bindings.isSuperType(declaringClass, currType)) {
			currType= currType.getDeclaringClass();
		}
	}
	if (currType != parentType) {
		if (currType == null)
			return null;

		if (currType.isAnonymous())
			//If we access a field of a super class of an anonymous class
			//then we can only qualify with 'this' but not with outer.this
			//see bug 115277
			return null;

		return imports.addImport(currType);
	} else {
		return ""; //$NON-NLS-1$
	}
}
 
Example 9
Source File: Bindings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns <code>true</code> if the given type is a super type of a candidate.
 * <code>true</code> is returned if the two type bindings are identical (TODO)
 * @param possibleSuperType the type to inspect
 * @param type the type whose super types are looked at
 * @param considerTypeArguments if <code>true</code>, consider type arguments of <code>type</code>
 * @return <code>true</code> iff <code>possibleSuperType</code> is
 * 		a super type of <code>type</code> or is equal to it
 */
public static boolean isSuperType(ITypeBinding possibleSuperType, ITypeBinding type, boolean considerTypeArguments) {
	if (type.isArray() || type.isPrimitive()) {
		return false;
	}
	if (! considerTypeArguments) {
		type= type.getTypeDeclaration();
	}
	if (Bindings.equals(type, possibleSuperType)) {
		return true;
	}
	ITypeBinding superClass= type.getSuperclass();
	if (superClass != null) {
		if (isSuperType(possibleSuperType, superClass, considerTypeArguments)) {
			return true;
		}
	}

	if (possibleSuperType.isInterface()) {
		ITypeBinding[] superInterfaces= type.getInterfaces();
		for (int i= 0; i < superInterfaces.length; i++) {
			if (isSuperType(possibleSuperType, superInterfaces[i], considerTypeArguments)) {
				return true;
			}
		}
	}
	return false;
}
 
Example 10
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static void addNewFieldProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding,
		ITypeBinding declaringTypeBinding, SimpleName simpleName, boolean isWriteAccess,
		Collection<ChangeCorrectionProposal> proposals) throws JavaModelException {
	// new variables
	ICompilationUnit targetCU;
	ITypeBinding senderDeclBinding;
	if (binding != null) {
		senderDeclBinding= binding.getTypeDeclaration();
		targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
	} else { // binding is null for accesses without qualifier
		senderDeclBinding= declaringTypeBinding;
		targetCU= cu;
	}

	if (!senderDeclBinding.isFromSource() || targetCU == null) {
		return;
	}

	boolean mustBeConst= ASTResolving.isInsideModifiers(simpleName);

	addNewFieldForType(targetCU, binding, senderDeclBinding, simpleName, isWriteAccess, mustBeConst, proposals);

	if (binding == null && senderDeclBinding.isNested()) {
		ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
		if (anonymDecl != null) {
			ITypeBinding bind= Bindings.getBindingOfParentType(anonymDecl.getParent());
			if (!bind.isAnonymous()) {
				addNewFieldForType(targetCU, bind, bind, simpleName, isWriteAccess, mustBeConst, proposals);
			}
		}
	}
}
 
Example 11
Source File: ScopeAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean isTypeInScope(ITypeBinding declaring, ITypeBinding context, boolean includeHierarchy) {
	ITypeBinding curr= context.getTypeDeclaration();
	while (curr != null && curr != declaring) {
		if (includeHierarchy && isInSuperTypeHierarchy(declaring, curr)) {
			return true;
		}
		curr= curr.getDeclaringClass();
	}
	return curr == declaring;
}
 
Example 12
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void addNewFieldProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, ITypeBinding declaringTypeBinding, SimpleName simpleName, boolean isWriteAccess, Collection<ICommandAccess> proposals) throws JavaModelException {
	// new variables
	ICompilationUnit targetCU;
	ITypeBinding senderDeclBinding;
	if (binding != null) {
		senderDeclBinding= binding.getTypeDeclaration();
		targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
	} else { // binding is null for accesses without qualifier
		senderDeclBinding= declaringTypeBinding;
		targetCU= cu;
	}

	if (!senderDeclBinding.isFromSource() || targetCU == null) {
		return;
	}

	boolean mustBeConst= ASTResolving.isInsideModifiers(simpleName);

	addNewFieldForType(targetCU, binding, senderDeclBinding, simpleName, isWriteAccess, mustBeConst, proposals);

	if (binding == null && senderDeclBinding.isNested()) {
		ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
		if (anonymDecl != null) {
			ITypeBinding bind= Bindings.getBindingOfParentType(anonymDecl.getParent());
			if (!bind.isAnonymous()) {
				addNewFieldForType(targetCU, bind, bind, simpleName, isWriteAccess, mustBeConst, proposals);
			}
		}
	}
}
 
Example 13
Source File: StubUtility.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static String[] getVariableNameSuggestions(int variableKind, IJavaProject project, ITypeBinding expectedType, Expression assignedExpression, Collection<String> excluded) {
	LinkedHashSet<String> res= new LinkedHashSet<String>(); // avoid duplicates but keep order

	if (assignedExpression != null) {
		String nameFromExpression= getBaseNameFromExpression(project, assignedExpression, variableKind);
		if (nameFromExpression != null) {
			add(getVariableNameSuggestions(variableKind, project, nameFromExpression, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural.
		}

		String nameFromParent= getBaseNameFromLocationInParent(assignedExpression);
		if (nameFromParent != null) {
			add(getVariableNameSuggestions(variableKind, project, nameFromParent, 0, excluded, false), res); // pass 0 as dimension, base name already contains plural.
		}
	}
	if (expectedType != null) {
		expectedType= Bindings.normalizeTypeBinding(expectedType);
		if (expectedType != null) {
			int dim= 0;
			if (expectedType.isArray()) {
				dim= expectedType.getDimensions();
				expectedType= expectedType.getElementType();
			}
			if (expectedType.isParameterizedType()) {
				expectedType= expectedType.getTypeDeclaration();
			}
			String typeName= expectedType.getName();
			if (typeName.length() > 0) {
				add(getVariableNameSuggestions(variableKind, project, typeName, dim, excluded, false), res);
			}
		}
	}
	if (res.isEmpty()) {
		return getDefaultVariableNameSuggestions(variableKind, excluded);
	}
	return res.toArray(new String[res.size()]);
}
 
Example 14
Source File: JdtUtils.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private static IBinding getDeclaringMember(ITypeBinding typeBinding) {
  ITypeBinding typeDeclaration = typeBinding.getTypeDeclaration();
  IBinding declaringMember = typeDeclaration.getDeclaringMember();
  if (declaringMember == null) {
    // Work around for b/147690014, in which getDeclaringMember returns null, but there is
    // a declaring member and is returned by getDeclaringMethod.
    declaringMember = typeDeclaration.getDeclaringMethod();
  }
  return declaringMember;
}
 
Example 15
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static void addNewMethodProposals(ICompilationUnit cu, CompilationUnit astRoot, Expression sender, List<Expression> arguments, boolean isSuperInvocation, ASTNode invocationNode, String methodName, Collection<ICommandAccess> proposals) throws JavaModelException {
	ITypeBinding nodeParentType= Bindings.getBindingOfParentType(invocationNode);
	ITypeBinding binding= null;
	if (sender != null) {
		binding= sender.resolveTypeBinding();
	} else {
		binding= nodeParentType;
		if (isSuperInvocation && binding != null) {
			binding= binding.getSuperclass();
		}
	}
	if (binding != null && binding.isFromSource()) {
		ITypeBinding senderDeclBinding= binding.getTypeDeclaration();

		ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
		if (targetCU != null) {
			String label;
			Image image;
			ITypeBinding[] parameterTypes= getParameterTypes(arguments);
			if (parameterTypes != null) {
				String sig= ASTResolving.getMethodSignature(methodName, parameterTypes, false);

				if (ASTResolving.isUseableTypeInContext(parameterTypes, senderDeclBinding, false)) {
					if (nodeParentType == senderDeclBinding) {
						label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_description, sig);
						image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE);
					} else {
						label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, new Object[] { sig, BasicElementLabels.getJavaElementName(senderDeclBinding.getName()) } );
						image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
					}
					proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode, arguments, senderDeclBinding, IProposalRelevance.CREATE_METHOD, image));
				}
				if (senderDeclBinding.isNested() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(senderDeclBinding, methodName, (ITypeBinding[]) null) == null) { // no covering method
					ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
					if (anonymDecl != null) {
						senderDeclBinding= Bindings.getBindingOfParentType(anonymDecl.getParent());
						if (!senderDeclBinding.isAnonymous() && ASTResolving.isUseableTypeInContext(parameterTypes, senderDeclBinding, false)) {
							String[] args= new String[] { sig, ASTResolving.getTypeSignature(senderDeclBinding) };
							label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, args);
							image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED);
							proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode, arguments, senderDeclBinding, IProposalRelevance.CREATE_METHOD, image));
						}
					}
				}
			}
		}
	}
}
 
Example 16
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public final boolean visit(final SimpleName node) {
	Assert.isNotNull(node);
	final AST ast= node.getAST();
	final ASTRewrite rewrite= fRewrite;
	final IBinding binding= node.resolveBinding();
	if (binding instanceof ITypeBinding) {
		ITypeBinding type= (ITypeBinding) binding;
		String name= fTargetRewrite.getImportRewrite().addImport(type.getTypeDeclaration());
		if (name != null && name.indexOf('.') != -1) {
			fRewrite.replace(node, ASTNodeFactory.newName(ast, name), null);
			return false;
		}
	}
	if (Bindings.equals(fTarget, binding))
		if (fAnonymousClass > 0) {
			final ThisExpression target= ast.newThisExpression();
			target.setQualifier(ast.newSimpleName(fTargetType.getElementName()));
			fRewrite.replace(node, target, null);
		} else
			rewrite.replace(node, ast.newThisExpression(), null);
	else if (binding instanceof IVariableBinding) {
		final IVariableBinding variable= (IVariableBinding) binding;
		final IMethodBinding method= fDeclaration.resolveBinding();
		ITypeBinding declaring= variable.getDeclaringClass();
		if (method != null) {
			if (declaring != null && Bindings.isSuperType(declaring, method.getDeclaringClass(), false)) {
				declaring= declaring.getTypeDeclaration();
				if (JdtFlags.isStatic(variable))
					rewrite.replace(node, ast.newQualifiedName(ASTNodeFactory.newName(ast, fTargetRewrite.getImportRewrite().addImport(declaring)), ast.newSimpleName(node.getFullyQualifiedName())), null);
				else {
					final FieldAccess access= ast.newFieldAccess();
					access.setExpression(ast.newSimpleName(fTargetName));
					access.setName(ast.newSimpleName(node.getFullyQualifiedName()));
					rewrite.replace(node, access, null);
				}
			} else if (!(node.getParent() instanceof QualifiedName) && JdtFlags.isStatic(variable) && !fStaticImports.contains(variable) && !Checks.isEnumCase(node.getParent())) {
				rewrite.replace(node, ast.newQualifiedName(ASTNodeFactory.newName(ast, fTargetRewrite.getImportRewrite().addImport(declaring)), ast.newSimpleName(node.getFullyQualifiedName())), null);
			}
		}
	}
	return false;
}
 
Example 17
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static void addNewMethodProposals(ICompilationUnit cu, CompilationUnit astRoot, Expression sender,
		List<Expression> arguments, boolean isSuperInvocation, ASTNode invocationNode, String methodName,
		Collection<ChangeCorrectionProposal> proposals) throws JavaModelException {
	ITypeBinding nodeParentType= Bindings.getBindingOfParentType(invocationNode);
	ITypeBinding binding= null;
	if (sender != null) {
		binding= sender.resolveTypeBinding();
	} else {
		binding= nodeParentType;
		if (isSuperInvocation && binding != null) {
			binding= binding.getSuperclass();
		}
	}
	if (binding != null && binding.isFromSource()) {
		ITypeBinding senderDeclBinding= binding.getTypeDeclaration();

		ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
		if (targetCU != null) {
			String label;
			ITypeBinding[] parameterTypes= getParameterTypes(arguments);
			if (parameterTypes != null) {
				String sig = org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getMethodSignature(methodName, parameterTypes, false);
				boolean is18OrHigher= JavaModelUtil.is18OrHigher(targetCU.getJavaProject());

				boolean isSenderBindingInterface= senderDeclBinding.isInterface();
				if (nodeParentType == senderDeclBinding) {
					label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_description, sig);
				} else {
					label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, new Object[] { sig, BasicElementLabels.getJavaElementName(senderDeclBinding.getName()) } );
				}
				if (is18OrHigher || !isSenderBindingInterface
						|| (nodeParentType != senderDeclBinding && (!(sender instanceof SimpleName) || !((SimpleName) sender).getIdentifier().equals(senderDeclBinding.getName())))) {
					proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode, arguments,
							senderDeclBinding, IProposalRelevance.CREATE_METHOD));
				}

				if (senderDeclBinding.isNested() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(senderDeclBinding, methodName, (ITypeBinding[]) null) == null) { // no covering method
					ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
					if (anonymDecl != null) {
						senderDeclBinding= Bindings.getBindingOfParentType(anonymDecl.getParent());
						isSenderBindingInterface= senderDeclBinding.isInterface();
						if (!senderDeclBinding.isAnonymous()) {
							if (is18OrHigher || !isSenderBindingInterface) {
								String[] args = new String[] { sig,
										org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getTypeSignature(senderDeclBinding) };
								label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createmethod_other_description, args);
								proposals.add(new NewMethodCorrectionProposal(label, targetCU, invocationNode,
										arguments, senderDeclBinding, IProposalRelevance.CREATE_METHOD));
							}
						}
					}
				}
			}
		}
	}
}
 
Example 18
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private RefactoringStatus updateReferences(IProgressMonitor monitor) throws CoreException {

		RefactoringStatus result= new RefactoringStatus();

		monitor.beginTask("", 90); //$NON-NLS-1$

		if (monitor.isCanceled())
			throw new OperationCanceledException();

		IMethod[] ripple= RippleMethodFinder2.getRelatedMethods(fTargetMethod, false, new NoOverrideProgressMonitor(monitor, 10), null);

		if (monitor.isCanceled())
			throw new OperationCanceledException();

		SearchResultGroup[] references= Checks.excludeCompilationUnits(getReferences(ripple, new NoOverrideProgressMonitor(monitor, 10), result), result);

		if (result.hasFatalError())
			return result;

		result.merge(Checks.checkCompileErrorsInAffectedFiles(references));

		if (monitor.isCanceled())
			throw new OperationCanceledException();

		int ticksPerCU= references.length == 0 ? 0 : 70 / references.length;

		for (int i= 0; i < references.length; i++) {
			SearchResultGroup group= references[i];
			SearchMatch[] searchResults= group.getSearchResults();
			CompilationUnitRewrite currentCURewrite= getCachedCURewrite(group.getCompilationUnit());

			for (int j= 0; j < searchResults.length; j++) {

				SearchMatch match= searchResults[j];
				if (match.isInsideDocComment())
					continue;

				IMember enclosingMember= (IMember) match.getElement();
				ASTNode target= getSelectedNode(group.getCompilationUnit(), currentCURewrite.getRoot(), match.getOffset(), match.getLength());

				if (target instanceof SuperMethodInvocation) {
					// Cannot retarget calls to super - add a warning
					result.merge(createWarningAboutCall(enclosingMember, target, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_super_keyword));
					continue;
				}

				Assert.isTrue(target instanceof MethodInvocation, "Element of call should be a MethodInvocation."); //$NON-NLS-1$

				MethodInvocation invocation= (MethodInvocation) target;
				ITypeBinding typeBinding= getExpressionType(invocation);

				if (fIntermediaryFirstParameterType == null) {
					// no highest type yet
					fIntermediaryFirstParameterType= typeBinding.getTypeDeclaration();
				} else {
					// check if current type is higher
					result.merge(findCommonParent(typeBinding.getTypeDeclaration()));
				}

				if (result.hasFatalError())
					return result;

				// create an edit for this particular call
				result.merge(updateMethodInvocation(invocation, enclosingMember, currentCURewrite));

				// does call see the intermediary method?
				// => increase visibility of the type of the intermediary method.
				result.merge(adjustVisibility(fIntermediaryType, enclosingMember.getDeclaringType(), new NoOverrideProgressMonitor(monitor, 0)));

				if (monitor.isCanceled())
					throw new OperationCanceledException();
			}

			if (!isRewriteKept(group.getCompilationUnit()))
				createChangeAndDiscardRewrite(group.getCompilationUnit());

			monitor.worked(ticksPerCU);
		}

		monitor.done();
		return result;
	}
 
Example 19
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Attempts to qualify a "this" expression for a method invocation with an appropriate qualifier.
 * The invoked method is analyzed according to the following specs:
 *
 * 'this' must be qualified iff method is declared in an enclosing type or a supertype of an enclosing type
 *
 * 1) The method is declared somewhere outside of the cu of the invocation
 *      1a) inside a supertype of the current type
 *      1b) inside a supertype of an enclosing type
 * 2) The method is declared inside of the cu of the invocation
 * 		2a) inside the type of the invocation
 * 		2b) outside the type of the invocation
 *
 * In case of 1a) and 2b), qualify with the enclosing type.
 * @param expr a {@link ThisExpression}
 * @param originalInvocation the original method invocation
 * @param enclosing the enclosing member of the original method invocation
 * @param unitRewriter the rewrite
 * @return resulting status
 *
 */
private RefactoringStatus qualifyThisExpression(ThisExpression expr, MethodInvocation originalInvocation, IMember enclosing, CompilationUnitRewrite unitRewriter) {

	RefactoringStatus status= new RefactoringStatus();

	IMethodBinding methodBinding= originalInvocation.resolveMethodBinding();
	MethodDeclaration methodDeclaration= (MethodDeclaration) ASTNodes.findDeclaration(methodBinding, originalInvocation.getRoot());

	ITypeBinding currentTypeBinding= null;
	if (methodDeclaration != null) {
		// Case 1) : Declaring type is inside this cu => use its name if it's declared in an enclosing type
		if (ASTNodes.isParent(originalInvocation, methodDeclaration.getParent()))
			currentTypeBinding= methodBinding.getDeclaringClass();
		else
			currentTypeBinding= ASTNodes.getEnclosingType(originalInvocation);
	} else {
		// Case 2) : Declaring type is outside of this cu => find subclass in this cu
		ASTNode currentTypeDeclaration= getEnclosingTypeDeclaration(originalInvocation);
		currentTypeBinding= ASTNodes.getEnclosingType(currentTypeDeclaration);
		while (currentTypeDeclaration != null && (Bindings.findMethodInHierarchy(currentTypeBinding, methodBinding.getName(), methodBinding.getParameterTypes()) == null)) {
			currentTypeDeclaration= getEnclosingTypeDeclaration(currentTypeDeclaration.getParent());
			currentTypeBinding= ASTNodes.getEnclosingType(currentTypeDeclaration);
		}
	}

	if (currentTypeBinding == null) {
		status.merge(createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_declaring_type_not_found));
		return status;
	}

	currentTypeBinding= currentTypeBinding.getTypeDeclaration();

	ITypeBinding typeOfCall= ASTNodes.getEnclosingType(originalInvocation);
	if (!typeOfCall.equals(currentTypeBinding)) {
		if (currentTypeBinding.isAnonymous()) {
			// Cannot qualify, see bug 115277
			status.merge(createWarningAboutCall(enclosing, originalInvocation, RefactoringCoreMessages.IntroduceIndirectionRefactoring_call_warning_anonymous_cannot_qualify));
		} else {
			expr.setQualifier(unitRewriter.getAST().newSimpleName(currentTypeBinding.getName()));
		}
	} else {
		// do not qualify, only use "this.".
	}

	return status;
}
 
Example 20
Source File: ContextSensitiveImportRewriteContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private boolean isConflictingType(ITypeBinding binding, String qualifier, String name) {
	binding= binding.getTypeDeclaration();
	return !isSameType(binding, qualifier, name) && isConflicting(binding, name);
}