Java Code Examples for org.eclipse.jdt.core.dom.IMethodBinding#getDeclaringClass()

The following examples show how to use org.eclipse.jdt.core.dom.IMethodBinding#getDeclaringClass() . 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: TargetProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static TargetProvider create(MethodDeclaration declaration) {
	IMethodBinding method= declaration.resolveBinding();
	if (method == null)
		return new ErrorTargetProvider(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.TargetProvider_method_declaration_not_unique));
	ITypeBinding type= method.getDeclaringClass();
	if (type.isLocal()) {
		if (((IType) type.getJavaElement()).isBinary()) {
			return new ErrorTargetProvider(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.TargetProvider_cannot_local_method_in_binary));
		} else {
			IType declaringClassOfLocal= (IType) type.getDeclaringClass().getJavaElement();
			return new LocalTypeTargetProvider(declaringClassOfLocal.getCompilationUnit(), declaration);
		}
	} else {
		return new MemberTypeTargetProvider(declaration.resolveBinding());
	}
}
 
Example 2
Source File: JUnit3Adapter.java    From sahagin-java with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isRootMethod(IMethodBinding methodBinding) {
    // TODO should check if public and no argument and void return method
    String methodName = methodBinding.getName();
    if (methodName == null || !methodName.startsWith("test")) {
        return false;
    }

    ITypeBinding defClass = methodBinding.getDeclaringClass();
    while (defClass != null) {
        String className = defClass.getQualifiedName();
        if ("junit.framework.TestCase".equals(className)) {
            return true;
        }
        defClass = defClass.getSuperclass();
    }
    return false;
}
 
Example 3
Source File: SemanticHighlightings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean consumes(SemanticToken token) {
	IBinding binding= getBinding(token);
	if (binding != null) {
		if (binding.isDeprecated())
			return true;
		if (binding instanceof IMethodBinding) {
			IMethodBinding methodBinding= (IMethodBinding) binding;
			if (methodBinding.isConstructor() && methodBinding.getJavaElement() == null) {
				ITypeBinding declaringClass= methodBinding.getDeclaringClass();
				if (declaringClass.isAnonymous()) {
					ITypeBinding[] interfaces= declaringClass.getInterfaces();
					if (interfaces.length > 0)
						return interfaces[0].isDeprecated();
					else
						return declaringClass.getSuperclass().isDeprecated();
				}
				return declaringClass.isDeprecated();
			}
		}
	}
	return false;
}
 
Example 4
Source File: VariableDeclarationFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean isWrittenInTypeConstructors(List<SimpleName> writes, ITypeBinding declaringClass) {

			for (int i= 0; i < writes.size(); i++) {
	            SimpleName name= writes.get(i);

	            MethodDeclaration methodDeclaration= getWritingConstructor(name);
	            if (methodDeclaration == null)
	            	return false;

	            if (!methodDeclaration.isConstructor())
	            	return false;

	            IMethodBinding constructor= methodDeclaration.resolveBinding();
	            if (constructor == null)
	            	return false;

	            ITypeBinding declaringClass2= constructor.getDeclaringClass();
	            if (!declaringClass.equals(declaringClass2))
	            	return false;
            }

	        return true;
        }
 
Example 5
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
ParameterNameInitializer createParameterNameInitializer(
		IMethodBinding method,
		WorkingCopyOwner workingCopyOwner,
		JvmExecutable result,
		String handleIdentifier,
		String[] path,
		String name,
		SegmentSequence signaturex) {
	if (method.isConstructor()) {
		ITypeBinding declarator = method.getDeclaringClass();
		if (declarator.isEnum()) {
			return new EnumConstructorParameterNameInitializer(workingCopyOwner, result, handleIdentifier, path, name, signaturex);
		}
		if (declarator.isMember()) {
			return new ParameterNameInitializer(workingCopyOwner, result, handleIdentifier, path, name, signaturex) {
				@Override
				protected void setParameterNames(IMethod javaMethod, java.util.List<JvmFormalParameter> parameters) throws JavaModelException {
					String[] parameterNames = javaMethod.getParameterNames();
					int size = parameters.size();
					if (size == parameterNames.length) {
						super.setParameterNames(javaMethod, parameters);
					} else if (size == parameterNames.length - 1) {
						for (int i = 1; i < parameterNames.length; i++) {
							String string = parameterNames[i];
							parameters.get(i - 1).setName(string);
						}
					} else {
						throw new IllegalStateException("unmatching arity for java method "+javaMethod.toString()+" and "+getExecutable().getIdentifier());
					}
				}
			};
		}
	}
	return new ParameterNameInitializer(workingCopyOwner, result, handleIdentifier, path, name, signaturex);
}
 
Example 6
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static IBinding resolveBinding(ASTNode node) {
	if (node instanceof SimpleName) {
		SimpleName simpleName = (SimpleName) node;
		// workaround for https://bugs.eclipse.org/62605 (constructor name resolves to type, not method)
		ASTNode normalized = ASTNodes.getNormalizedNode(simpleName);
		if (normalized.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) {
			ClassInstanceCreation cic = (ClassInstanceCreation) normalized.getParent();
			IMethodBinding constructorBinding = cic.resolveConstructorBinding();
			if (constructorBinding == null) {
				return null;
			}
			ITypeBinding declaringClass = constructorBinding.getDeclaringClass();
			if (!declaringClass.isAnonymous()) {
				return constructorBinding;
			}
			ITypeBinding superTypeDeclaration = declaringClass.getSuperclass().getTypeDeclaration();
			return resolveSuperclassConstructor(superTypeDeclaration, constructorBinding);
		}
		return simpleName.resolveBinding();

	} else if (node instanceof SuperConstructorInvocation) {
		return ((SuperConstructorInvocation) node).resolveConstructorBinding();
	} else if (node instanceof ConstructorInvocation) {
		return ((ConstructorInvocation) node).resolveConstructorBinding();
	} else if (node instanceof LambdaExpression) {
		return ((LambdaExpression) node).resolveMethodBinding();
	} else {
		return null;
	}
}
 
Example 7
Source File: CallContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ITypeBinding getReceiverType() {
	Expression expression= Invocations.getExpression(invocation);
	if (expression != null) {
		return expression.resolveTypeBinding();
	}
	IMethodBinding method= Invocations.resolveBinding(invocation);
	if (method != null) {
		return method.getDeclaringClass();
	}
	return null;
}
 
Example 8
Source File: SelfEncapsulateFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void checkMethodInHierarchy(ITypeBinding type, String methodName, ITypeBinding returnType, ITypeBinding[] parameters, RefactoringStatus result, boolean reUseMethod) {
	IMethodBinding method= Bindings.findMethodInHierarchy(type, methodName, parameters);
	if (method != null) {
		boolean returnTypeClash= false;
		ITypeBinding methodReturnType= method.getReturnType();
		if (returnType != null && methodReturnType != null) {
			String returnTypeKey= returnType.getKey();
			String methodReturnTypeKey= methodReturnType.getKey();
			if (returnTypeKey == null && methodReturnTypeKey == null) {
				returnTypeClash= returnType != methodReturnType;
			} else if (returnTypeKey != null && methodReturnTypeKey != null) {
				returnTypeClash= !returnTypeKey.equals(methodReturnTypeKey);
			}
		}
		ITypeBinding dc= method.getDeclaringClass();
		if (returnTypeClash) {
			result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_returnTypeClash,
				new Object[] { BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(dc.getName())}),
				JavaStatusContext.create(method));
		} else {
			if (!reUseMethod)
				result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_overrides,
						new Object[] { BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(dc.getName())}),
					JavaStatusContext.create(method));
		}
	} else {
		if (reUseMethod){
			result.addError(Messages.format(RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_nosuchmethod_status_fatalError,
					BasicElementLabels.getJavaElementName(methodName)),
					JavaStatusContext.create(method));
		}
	}
}
 
Example 9
Source File: JdtFlags.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isDefaultMethod(IMethodBinding method) {
	int modifiers= method.getModifiers();
	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=405517#c7
	ITypeBinding declaringClass= method.getDeclaringClass();
	if (declaringClass.isInterface()) {
		return !Modifier.isAbstract(modifiers) && !Modifier.isStatic(modifiers);
	}
	return false;
}
 
Example 10
Source File: ASTNodeMatcher.java    From JDeodorant with MIT License 5 votes vote down vote up
private SimpleName setterMethodForField(MethodInvocation methodInvocation, SimpleName fieldName) {
	IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
	ITypeBinding declaringClassTypeBinding = methodBinding.getDeclaringClass();
	ClassObject declaringClass = ASTReader.getSystemObject().getClassObject(declaringClassTypeBinding.getQualifiedName());
	if(declaringClass != null) {
		ListIterator<MethodObject> methodIterator = declaringClass.getMethodIterator();
		while(methodIterator.hasNext()) {
			MethodObject method = methodIterator.next();
			MethodDeclaration methodDeclaration = method.getMethodDeclaration();
			if(methodDeclaration.resolveBinding().isEqualTo(methodInvocation.resolveMethodBinding())) {
				SimpleName setField = MethodDeclarationUtility.isSetter(methodDeclaration);
				if(setField != null) {
					if(setField.resolveBinding().getKind() == IBinding.VARIABLE &&
							fieldName.resolveBinding().getKind() == IBinding.VARIABLE) {
						IVariableBinding setFieldBinding = (IVariableBinding)setField.resolveBinding();
						IVariableBinding fieldNameBinding = (IVariableBinding)fieldName.resolveBinding();
						if(setFieldBinding.isEqualTo(fieldNameBinding) ||
								(setField.getIdentifier().equals(fieldName.getIdentifier()) &&
								setFieldBinding.getType().isEqualTo(fieldNameBinding.getType()) && setFieldBinding.getType().getQualifiedName().equals(fieldNameBinding.getType().getQualifiedName()))) {
							return setField;
						}
					}
				}
			}
		}
	}
	return null;
}
 
Example 11
Source File: SrcTreeGenerator.java    From sahagin-java with Apache License 2.0 5 votes vote down vote up
@Override
public boolean visit(MethodDeclaration node) {
    IMethodBinding methodBinding = node.resolveBinding();
    Pair<String, CaptureStyle> testDocPair = testDocIfSubMethod(methodBinding);
    if (testDocPair.getLeft() == null) {
        return super.visit(node);
    }

    ITypeBinding classBinding = methodBinding.getDeclaringClass();
    if (!classBinding.isClass() && !classBinding.isInterface()) {
        // enum method, etc
        return super.visit(node);
    }

    TestClass testClass = classBindingTestClass(classBinding);

    TestMethod testMethod = new TestMethod();
    testMethod.setKey(generateMethodKey(methodBinding, false));
    testMethod.setSimpleName(methodBinding.getName());
    testMethod.setTestDoc(testDocPair.getLeft());
    testMethod.setCaptureStyle(testDocPair.getRight());
    for (Object element : node.parameters()) {
        if (!(element instanceof SingleVariableDeclaration)) {
            throw new RuntimeException("not supported yet: " + element);
        }
        SingleVariableDeclaration varDecl = (SingleVariableDeclaration)element;
        testMethod.addArgVariable(varDecl.getName().getIdentifier());
        if (varDecl.isVarargs()) {
            testMethod.setVariableLengthArgIndex(testMethod.getArgVariables().size() - 1);
        }
    }
    testMethod.setTestClassKey(testClass.getKey());
    testMethod.setTestClass(testClass);
    subMethodTable.addTestMethod(testMethod);

    testClass.addTestMethodKey(testMethod.getKey());
    testClass.addTestMethod(testMethod);

    return super.visit(node);
}
 
Example 12
Source File: FullConstraintCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected static Set<ITypeBinding> getDeclaringSuperTypes(IMethodBinding methodBinding) {
	ITypeBinding superClass = methodBinding.getDeclaringClass();
	Set<ITypeBinding> allSuperTypes= new LinkedHashSet<ITypeBinding>();
	allSuperTypes.addAll(Arrays.asList(Bindings.getAllSuperTypes(superClass)));
	if (allSuperTypes.isEmpty())
		allSuperTypes.add(methodBinding.getDeclaringClass()); //TODO: Why only iff empty? The declaring class is not a supertype ...
	Set<ITypeBinding> result= new HashSet<ITypeBinding>();
	for (Iterator<ITypeBinding> iter= allSuperTypes.iterator(); iter.hasNext();) {
		ITypeBinding type= iter.next();
		if (findMethod(methodBinding, type) != null)
			result.add(type);
	}
	return result;
}
 
Example 13
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks whether the instance method body is compatible with this
 * refactoring.
 *
 * @param monitor
 *            the progress monitor to display progress
 * @param declaration
 *            the method declaration whose body to check
 * @param status
 *            the status of the condition checking
 */
protected void checkMethodBody(final IProgressMonitor monitor, final MethodDeclaration declaration, final RefactoringStatus status) {
	Assert.isNotNull(monitor);
	Assert.isNotNull(declaration);
	Assert.isNotNull(status);
	try {
		monitor.beginTask("", 3); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
		AstNodeFinder finder= new SuperReferenceFinder();
		declaration.accept(finder);
		if (!finder.getStatus().isOK())
			status.merge(finder.getStatus());
		monitor.worked(1);
		finder= null;
		final IMethodBinding binding= declaration.resolveBinding();
		if (binding != null) {
			final ITypeBinding declaring= binding.getDeclaringClass();
			if (declaring != null)
				finder= new EnclosingInstanceReferenceFinder(declaring);
		}
		if (finder != null) {
			declaration.accept(finder);
			if (!finder.getStatus().isOK())
				status.merge(finder.getStatus());
			monitor.worked(1);
			finder= new RecursiveCallFinder(declaration);
			declaration.accept(finder);
			if (!finder.getStatus().isOK())
				status.merge(finder.getStatus());
			monitor.worked(1);
		}
	} finally {
		monitor.done();
	}
}
 
Example 14
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Computes the target categories for the method to move.
 *
 * @param declaration
 *            the method declaration
 * @return the possible targets as variable bindings of read-only fields and
 *         parameters
 */
protected IVariableBinding[] computeTargetCategories(final MethodDeclaration declaration) {
	Assert.isNotNull(declaration);
	if (fPossibleTargets.length == 0 || fCandidateTargets.length == 0) {
		final List<IVariableBinding> possibleTargets= new ArrayList<IVariableBinding>(16);
		final List<IVariableBinding> candidateTargets= new ArrayList<IVariableBinding>(16);
		final IMethodBinding method= declaration.resolveBinding();
		if (method != null) {
			final ITypeBinding declaring= method.getDeclaringClass();
			IVariableBinding[] bindings= getArgumentBindings(declaration);
			ITypeBinding binding= null;
			for (int index= 0; index < bindings.length; index++) {
				binding= bindings[index].getType();
				if ((binding.isClass() || binding.isEnum() || is18OrHigherInterface(binding)) && binding.isFromSource()) {
					possibleTargets.add(bindings[index]);
					candidateTargets.add(bindings[index]);
				}
			}
			final ReadyOnlyFieldFinder visitor= new ReadyOnlyFieldFinder(declaring);
			declaration.accept(visitor);
			bindings= visitor.getReadOnlyFields();
			for (int index= 0; index < bindings.length; index++) {
				binding= bindings[index].getType();
				if ((binding.isClass() || is18OrHigherInterface(binding)) && binding.isFromSource())
					possibleTargets.add(bindings[index]);
			}
			bindings= visitor.getDeclaredFields();
			for (int index= 0; index < bindings.length; index++) {
				binding= bindings[index].getType();
				if ((binding.isClass() || is18OrHigherInterface(binding)) && binding.isFromSource())
					candidateTargets.add(bindings[index]);
			}
		}
		fPossibleTargets= new IVariableBinding[possibleTargets.size()];
		possibleTargets.toArray(fPossibleTargets);
		fCandidateTargets= new IVariableBinding[candidateTargets.size()];
		candidateTargets.toArray(fCandidateTargets);
	}
	return fPossibleTargets;
}
 
Example 15
Source File: SuperTypeConstraintsCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * End of visit the specified method invocation.
 *
 * @param binding the method binding
 * @param descendant the constraint variable of the invocation expression
 */
private void endVisit(final IMethodBinding binding, final ConstraintVariable2 descendant) {
	ITypeBinding declaring= null;
	IMethodBinding method= null;
	final Collection<IMethodBinding> originals= getOriginalMethods(binding);
	for (final Iterator<IMethodBinding> iterator= originals.iterator(); iterator.hasNext();) {
		method= iterator.next();
		declaring= method.getDeclaringClass();
		if (declaring != null) {
			final ConstraintVariable2 ancestor= fModel.createDeclaringTypeVariable(declaring);
			if (ancestor != null)
				fModel.createSubtypeConstraint(descendant, ancestor);
		}
	}
}
 
Example 16
Source File: Checks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks if the new method somehow conflicts with an already existing method in
 * the hierarchy. The following checks are done:
 * <ul>
 *   <li> if the new method overrides a method defined in the given type or in one of its
 * 		super classes. </li>
 * </ul>
 * @param type
 * @param methodName
 * @param returnType
 * @param parameters
 * @return the status
 */
public static RefactoringStatus checkMethodInHierarchy(ITypeBinding type, String methodName, ITypeBinding returnType, ITypeBinding[] parameters) {
	RefactoringStatus result= new RefactoringStatus();
	IMethodBinding method= Bindings.findMethodInHierarchy(type, methodName, parameters);
	if (method != null) {
		boolean returnTypeClash= false;
		ITypeBinding methodReturnType= method.getReturnType();
		if (returnType != null && methodReturnType != null) {
			String returnTypeKey= returnType.getKey();
			String methodReturnTypeKey= methodReturnType.getKey();
			if (returnTypeKey == null && methodReturnTypeKey == null) {
				returnTypeClash= returnType != methodReturnType;
			} else if (returnTypeKey != null && methodReturnTypeKey != null) {
				returnTypeClash= !returnTypeKey.equals(methodReturnTypeKey);
			}
		}
		ITypeBinding dc= method.getDeclaringClass();
		if (returnTypeClash) {
			result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_returnTypeClash,
				new Object[] {BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(dc.getName())}),
				JavaStatusContext.create(method));
		} else {
			if (method.isConstructor()) {
				result.addWarning(Messages.format(RefactoringCoreMessages.Checks_methodName_constructor,
						new Object[] { BasicElementLabels.getJavaElementName(dc.getName()) }));
			} else {
				result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_overrides,
						new Object[] { BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(dc.getName()) }),
						JavaStatusContext.create(method));
			}
		}
	}
	return result;
}
 
Example 17
Source File: TypeMismatchSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static void addIncompatibleReturnTypeProposals(IInvocationContext context, IProblemLocationCore problem,
		Collection<ChangeCorrectionProposal> proposals) throws JavaModelException {
	CompilationUnit astRoot= context.getASTRoot();
	ASTNode selectedNode= problem.getCoveringNode(astRoot);
	if (selectedNode == null) {
		return;
	}
	MethodDeclaration decl= ASTResolving.findParentMethodDeclaration(selectedNode);
	if (decl == null) {
		return;
	}
	IMethodBinding methodDeclBinding= decl.resolveBinding();
	if (methodDeclBinding == null) {
		return;
	}

	ITypeBinding returnType= methodDeclBinding.getReturnType();
	IMethodBinding overridden= Bindings.findOverriddenMethod(methodDeclBinding, false);
	if (overridden == null || overridden.getReturnType() == returnType) {
		return;
	}


	ICompilationUnit cu= context.getCompilationUnit();
	IMethodBinding methodDecl= methodDeclBinding.getMethodDeclaration();
	ITypeBinding overriddenReturnType= overridden.getReturnType();
	if (! JavaModelUtil.is50OrHigher(context.getCompilationUnit().getJavaProject())) {
		overriddenReturnType= overriddenReturnType.getErasure();
	}
	proposals.add(new TypeChangeCorrectionProposal(cu, methodDecl, astRoot, overriddenReturnType, false, IProposalRelevance.CHANGE_RETURN_TYPE));

	ICompilationUnit targetCu= cu;

	IMethodBinding overriddenDecl= overridden.getMethodDeclaration();
	ITypeBinding overridenDeclType= overriddenDecl.getDeclaringClass();

	if (overridenDeclType.isFromSource()) {
		targetCu= ASTResolving.findCompilationUnitForBinding(cu, astRoot, overridenDeclType);
		if (targetCu != null && ASTResolving.isUseableTypeInContext(returnType, overriddenDecl, false)) {
			TypeChangeCorrectionProposal proposal= new TypeChangeCorrectionProposal(targetCu, overriddenDecl, astRoot, returnType, false, IProposalRelevance.CHANGE_RETURN_TYPE_OF_OVERRIDDEN);
			if (overridenDeclType.isInterface()) {
				proposal.setDisplayName(Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturnofimplemented_description, BasicElementLabels.getJavaElementName(overriddenDecl.getName())));
			} else {
				proposal.setDisplayName(Messages.format(CorrectionMessages.TypeMismatchSubProcessor_changereturnofoverridden_description, BasicElementLabels.getJavaElementName(overriddenDecl.getName())));
			}
			proposals.add(proposal);
		}
	}
}
 
Example 18
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static void addQualifierToOuterProposal(IInvocationContext context, MethodInvocation invocationNode,
		IMethodBinding binding, Collection<ChangeCorrectionProposal> proposals) {
	ITypeBinding declaringType= binding.getDeclaringClass();
	ITypeBinding parentType= Bindings.getBindingOfParentType(invocationNode);
	ITypeBinding currType= parentType;

	boolean isInstanceMethod= !Modifier.isStatic(binding.getModifiers());

	while (currType != null && !Bindings.isSuperType(declaringType, currType)) {
		if (isInstanceMethod && Modifier.isStatic(currType.getModifiers())) {
			return;
		}
		currType= currType.getDeclaringClass();
	}
	if (currType == null || currType == parentType) {
		return;
	}

	ASTRewrite rewrite= ASTRewrite.create(invocationNode.getAST());

	String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_changetoouter_description,
			org.eclipse.jdt.ls.core.internal.corrections.ASTResolving.getTypeSignature(currType));
	ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(),
			rewrite, IProposalRelevance.QUALIFY_WITH_ENCLOSING_TYPE);

	ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot());
	ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(invocationNode, imports);
	AST ast= invocationNode.getAST();

	String qualifier= imports.addImport(currType, importRewriteContext);
	Name name= ASTNodeFactory.newName(ast, qualifier);

	Expression newExpression;
	if (isInstanceMethod) {
		ThisExpression expr= ast.newThisExpression();
		expr.setQualifier(name);
		newExpression= expr;
	} else {
		newExpression= name;
	}

	rewrite.set(invocationNode, MethodInvocation.EXPRESSION_PROPERTY, newExpression, null);

	proposals.add(proposal);
}
 
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: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates the necessary changes to create the delegate method with the
 * original method body.
 *
 * @param document
 *            the buffer containing the source of the source compilation
 *            unit
 * @param declaration
 *            the method declaration to use as source
 * @param rewrite
 *            the ast rewrite to use for the copy of the method body
 * @param rewrites
 *            the compilation unit rewrites
 * @param adjustments
 *            the map of elements to visibility adjustments
 * @param status
 *            the refactoring status
 * @param monitor
 *            the progress monitor to display progress
 * @throws CoreException
 *             if an error occurs
 */
protected void createMethodCopy(IDocument document, MethodDeclaration declaration, ASTRewrite rewrite, Map<ICompilationUnit, CompilationUnitRewrite> rewrites, Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, RefactoringStatus status, IProgressMonitor monitor) throws CoreException {
	Assert.isNotNull(document);
	Assert.isNotNull(declaration);
	Assert.isNotNull(rewrite);
	Assert.isNotNull(rewrites);
	Assert.isNotNull(adjustments);
	Assert.isNotNull(status);
	Assert.isNotNull(monitor);
	final CompilationUnitRewrite rewriter= getCompilationUnitRewrite(rewrites, getTargetType().getCompilationUnit());
	try {
		rewrite.set(declaration, MethodDeclaration.NAME_PROPERTY, rewrite.getAST().newSimpleName(fMethodName), null);
		boolean same= false;
		final IMethodBinding binding= declaration.resolveBinding();
		if (binding != null) {
			final ITypeBinding declaring= binding.getDeclaringClass();
			if (declaring != null && Bindings.equals(declaring.getPackage(), fTarget.getType().getPackage()))
				same= true;
			final Modifier.ModifierKeyword keyword= same ? null : Modifier.ModifierKeyword.PUBLIC_KEYWORD;
			ModifierRewrite modifierRewrite= ModifierRewrite.create(rewrite, declaration);
			if (JdtFlags.isDefaultMethod(binding) && getTargetType().isClass()) {
				// Remove 'default' modifier and add 'public' visibility
				modifierRewrite.setVisibility(Modifier.PUBLIC, null);
				modifierRewrite.setModifiers(Modifier.NONE, Modifier.DEFAULT, null);
			} else if (!JdtFlags.isDefaultMethod(binding) && getTargetType().isInterface()) {
				// Remove visibility modifiers and add 'default'
				modifierRewrite.setModifiers(Modifier.DEFAULT, Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE, null);
			} else if (MemberVisibilityAdjustor.hasLowerVisibility(binding.getModifiers(), same ? Modifier.NONE : keyword == null ? Modifier.NONE : keyword.toFlagValue())
					&& MemberVisibilityAdjustor.needsVisibilityAdjustments(fMethod, keyword, adjustments)) {
				final MemberVisibilityAdjustor.IncomingMemberVisibilityAdjustment adjustment= new MemberVisibilityAdjustor.IncomingMemberVisibilityAdjustment(fMethod, keyword, RefactoringStatus.createStatus(RefactoringStatus.WARNING, Messages.format(RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_method_warning, new String[] { MemberVisibilityAdjustor.getLabel(fMethod), MemberVisibilityAdjustor.getLabel(keyword) }), JavaStatusContext.create(fMethod), null, RefactoringStatusEntry.NO_CODE, null));
				modifierRewrite.setVisibility(keyword == null ? Modifier.NONE : keyword.toFlagValue(), null);
				adjustment.setNeedsRewriting(false);
				adjustments.put(fMethod, adjustment);
			}
		}
		for (IExtendedModifier modifier : (List<IExtendedModifier>) declaration.modifiers()) {
			if (modifier.isAnnotation()) {
				Annotation annotation= (Annotation) modifier;
				ITypeBinding typeBinding= annotation.resolveTypeBinding();
				if (typeBinding != null && typeBinding.getQualifiedName().equals("java.lang.Override")) { //$NON-NLS-1$
					rewrite.remove(annotation, null);
				}
			}
		}
		createMethodArguments(rewrites, rewrite, declaration, adjustments, status);
		createMethodTypeParameters(rewrite, declaration, status);
		createMethodComment(rewrite, declaration);
		createMethodBody(rewriter, rewrite, declaration);
	} finally {
		if (fMethod.getCompilationUnit().equals(getTargetType().getCompilationUnit()))
			rewriter.clearImportRewrites();
	}
}