Java Code Examples for org.eclipse.jdt.core.dom.AbstractTypeDeclaration#resolveBinding()

The following examples show how to use org.eclipse.jdt.core.dom.AbstractTypeDeclaration#resolveBinding() . 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: Bindings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the type binding of the node's type context or null if the node is inside
 * an annotation, type parameter, super type declaration, or Javadoc of a top level type.
 * The result of this method is equal to the result of {@link #getBindingOfParentType(ASTNode)} for nodes in the type's body.
 * 
 * @param node an AST node
 * @return the type binding of the node's parent type context, or <code>null</code>
 */
public static ITypeBinding getBindingOfParentTypeContext(ASTNode node) {
	StructuralPropertyDescriptor lastLocation= null;

	while (node != null) {
		if (node instanceof AbstractTypeDeclaration) {
			AbstractTypeDeclaration decl= (AbstractTypeDeclaration) node;
			if (lastLocation == decl.getBodyDeclarationsProperty()
					|| lastLocation == decl.getJavadocProperty()) {
				return decl.resolveBinding();
			} else if (decl instanceof EnumDeclaration && lastLocation == EnumDeclaration.ENUM_CONSTANTS_PROPERTY) {
				return decl.resolveBinding();
			}
		} else if (node instanceof AnonymousClassDeclaration) {
			return ((AnonymousClassDeclaration) node).resolveBinding();
		}
		lastLocation= node.getLocationInParent();
		node= node.getParent();
	}
	return null;
}
 
Example 2
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected final void adjustTypeVisibility(final ITypeBinding binding) throws JavaModelException {
	Assert.isNotNull(binding);
	final IJavaElement element= binding.getJavaElement();
	if (element instanceof IType) {
		final IType type= (IType) element;
		if (!type.isBinary() && !type.isReadOnly() && !Flags.isPublic(type.getFlags())) {
			boolean same= false;
			final CompilationUnitRewrite rewrite= getCompilationUnitRewrite(fRewrites, type.getCompilationUnit());
			final AbstractTypeDeclaration declaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(type, rewrite.getRoot());
			if (declaration != null) {
				final ITypeBinding declaring= declaration.resolveBinding();
				if (declaring != null && Bindings.equals(declaring.getPackage(), fTarget.getType().getPackage()))
					same= true;
				final Modifier.ModifierKeyword keyword= same ? null : Modifier.ModifierKeyword.PUBLIC_KEYWORD;
				final String modifier= same ? RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_default : RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_public;
				if (MemberVisibilityAdjustor.hasLowerVisibility(binding.getModifiers(), same ? Modifier.NONE : keyword == null ? Modifier.NONE : keyword.toFlagValue()) && MemberVisibilityAdjustor.needsVisibilityAdjustments(type, keyword, fAdjustments))
					fAdjustments.put(type, new MemberVisibilityAdjustor.OutgoingMemberVisibilityAdjustment(type, keyword, RefactoringStatus.createWarningStatus(Messages.format(RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_type_warning, new String[] { BindingLabelProvider.getBindingLabel(declaration.resolveBinding(), JavaElementLabels.ALL_FULLY_QUALIFIED), modifier }), JavaStatusContext.create(type.getCompilationUnit(), declaration))));
			}
		}
	}
}
 
Example 3
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addInheritedTypeQualifications(final AbstractTypeDeclaration declaration, final CompilationUnitRewrite targetRewrite, final TextEditGroup group) {
	Assert.isNotNull(declaration);
	Assert.isNotNull(targetRewrite);
	final CompilationUnit unit= (CompilationUnit) declaration.getRoot();
	final ITypeBinding binding= declaration.resolveBinding();
	if (binding != null) {
		Type type= null;
		if (declaration instanceof TypeDeclaration) {
			type= ((TypeDeclaration) declaration).getSuperclassType();
			if (type != null && unit.findDeclaringNode(binding) != null)
				addTypeQualification(type, targetRewrite, group);
		}
		List<Type> types= null;
		if (declaration instanceof TypeDeclaration)
			types= ((TypeDeclaration) declaration).superInterfaceTypes();
		else if (declaration instanceof EnumDeclaration)
			types= ((EnumDeclaration) declaration).superInterfaceTypes();
		if (types != null) {
			for (final Iterator<Type> iterator= types.iterator(); iterator.hasNext();) {
				type= iterator.next();
				if (unit.findDeclaringNode(type.resolveBinding()) != null)
					addTypeQualification(type, targetRewrite, group);
			}
		}
	}
}
 
Example 4
Source File: UnimplementedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean isTypeBindingNull(ASTNode typeNode) {
	if (typeNode instanceof AbstractTypeDeclaration) {
		AbstractTypeDeclaration abstractTypeDeclaration= (AbstractTypeDeclaration) typeNode;
		if (abstractTypeDeclaration.resolveBinding() == null)
			return true;

		return false;
	} else if (typeNode instanceof AnonymousClassDeclaration) {
		AnonymousClassDeclaration anonymousClassDeclaration= (AnonymousClassDeclaration) typeNode;
		if (anonymousClassDeclaration.resolveBinding() == null)
			return true;

		return false;
	} else if (typeNode instanceof EnumConstantDeclaration) {
		return false;
	} else {
		return true;
	}
}
 
Example 5
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the receiver's type binding of the given method invocation.
 *
 * @param invocation method invocation to resolve type of
 * @return the type binding of the receiver
 */
public static ITypeBinding getReceiverTypeBinding(MethodInvocation invocation) {
	ITypeBinding result= null;
	Expression exp= invocation.getExpression();
	if(exp != null) {
		return exp.resolveTypeBinding();
	}
	else {
		AbstractTypeDeclaration type= (AbstractTypeDeclaration)getParent(invocation, AbstractTypeDeclaration.class);
		if (type != null)
			return type.resolveBinding();
	}
	return result;
}
 
Example 6
Source File: MethodDiff.java    From apidiff with MIT License 5 votes vote down vote up
/**
 * @param method
 * @param type
 * @return true, method is deprecated or type is deprecated
 */
private Boolean isDeprecated(MethodDeclaration method, AbstractTypeDeclaration type){
	Boolean isMethodDeprecated =  (method != null && method.resolveBinding() != null && method.resolveBinding().isDeprecated()) ? true: false;
	Boolean isTypeDeprecated = (type != null && type.resolveBinding() != null && type.resolveBinding().isDeprecated()) ? true: false;
	
	return isMethodDeprecated || isTypeDeprecated;
}
 
Example 7
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void modifyAccessToEnclosingInstance(final CompilationUnitRewrite targetRewrite, final AbstractTypeDeclaration declaration, final IProgressMonitor monitor) {
	Assert.isNotNull(targetRewrite);
	Assert.isNotNull(declaration);
	Assert.isNotNull(monitor);
	ITypeBinding typeBinding= declaration.resolveBinding();
	if (typeBinding == null) {
		return;
	}
	final MemberAccessNodeCollector collector= new MemberAccessNodeCollector(typeBinding);
	declaration.accept(collector);
	modifyAccessToMethodsFromEnclosingInstance(targetRewrite, collector.getMethodInvocations(), declaration);
	modifyAccessToFieldsFromEnclosingInstance(targetRewrite, collector.getSimpleFieldNames(), declaration);
}
 
Example 8
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isInstanceFieldCreationMandatory() {
	AbstractTypeDeclaration typeDeclaration= findTypeDeclaration(fType, fSourceRewrite.getRoot());
	ITypeBinding typeBinding= typeDeclaration.resolveBinding();
	if (typeBinding == null || Modifier.isStatic(typeBinding.getModifiers())) {
		return false;
	}
	final MemberAccessNodeCollector collector= new MemberAccessNodeCollector(typeBinding);
	typeDeclaration.accept(collector);
	return containsNonStatic(collector.getMethodInvocations()) || containsNonStatic(collector.getSimpleFieldNames());
}
 
Example 9
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isInsideTypeNestedInDeclaringType(ASTNode node) {
	Assert.isTrue((node instanceof ClassInstanceCreation) || (node instanceof SuperConstructorInvocation));
	final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(node, AbstractTypeDeclaration.class);
	Assert.isNotNull(declaration);
	ITypeBinding enclosing= declaration.resolveBinding();
	while (enclosing != null) {
		if (isCorrespondingTypeBinding(enclosing, fType.getDeclaringType()))
			return true;
		enclosing= enclosing.getDeclaringClass();
	}
	return false;
}
 
Example 10
Source File: AddUnimplementedConstructorsAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public AddUnimplementedConstructorsContentProvider(IType type) throws JavaModelException {
	RefactoringASTParser parser= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL);
	fUnit= parser.parse(type.getCompilationUnit(), true);
	AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) ASTNodes.getParent(NodeFinder.perform(fUnit, type.getNameRange()), AbstractTypeDeclaration.class);
	if (declaration != null) {
		ITypeBinding binding= declaration.resolveBinding();
		if (binding != null)
			fMethodsList= StubUtility2.getVisibleConstructors(binding, true, false);
	}
}
 
Example 11
Source File: ExtractSupertypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the necessary constructors for the extracted supertype.
 *
 * @param targetRewrite
 *            the target compilation unit rewrite
 * @param superType
 *            the super type, or <code>null</code> if no super type (ie.
 *            <code>java.lang.Object</code>) is available
 * @param targetDeclaration
 *            the type declaration of the target type
 * @param status
 *            the refactoring status
 */
protected final void createNecessaryConstructors(final CompilationUnitRewrite targetRewrite, final IType superType, final AbstractTypeDeclaration targetDeclaration, final RefactoringStatus status) {
	Assert.isNotNull(targetRewrite);
	Assert.isNotNull(targetDeclaration);
	if (superType != null) {
		final ITypeBinding binding= targetDeclaration.resolveBinding();
		if (binding != null && binding.isClass()) {
			final IMethodBinding[] bindings= StubUtility2.getVisibleConstructors(binding, true, true);
			int deprecationCount= 0;
			for (int i= 0; i < bindings.length; i++) {
				if (bindings[i].isDeprecated())
					deprecationCount++;
			}
			final ListRewrite rewrite= targetRewrite.getASTRewrite().getListRewrite(targetDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
			if (rewrite != null) {
				boolean createDeprecated= deprecationCount == bindings.length;
				for (int i= 0; i < bindings.length; i++) {
					IMethodBinding curr= bindings[i];
					if (!curr.isDeprecated() || createDeprecated) {
						MethodDeclaration stub;
						try {
							ImportRewriteContext context= new ContextSensitiveImportRewriteContext(targetDeclaration, targetRewrite.getImportRewrite());
							stub= StubUtility2.createConstructorStub(targetRewrite.getCu(), targetRewrite.getASTRewrite(), targetRewrite.getImportRewrite(), context, curr, binding.getName(),
									Modifier.PUBLIC, false, false, fSettings);
							if (stub != null)
								rewrite.insertLast(stub, null);
						} catch (CoreException exception) {
							JavaPlugin.log(exception);
							status.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractSupertypeProcessor_unexpected_exception_on_layer));
						}
					}
				}
			}
		}
	}
}
 
Example 12
Source File: SelfEncapsulateFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void checkInHierarchy(RefactoringStatus status, boolean usingLocalGetter, boolean usingLocalSetter) {
	AbstractTypeDeclaration declaration = ASTNodes.getParent(fFieldDeclaration, AbstractTypeDeclaration.class);
	ITypeBinding type = declaration.resolveBinding();
	if (type != null) {
		ITypeBinding fieldType = fFieldDeclaration.resolveBinding().getType();
		checkMethodInHierarchy(type, fGetterName, fieldType, new ITypeBinding[0], status, usingLocalGetter);
		checkMethodInHierarchy(type, fSetterName, fFieldDeclaration.getAST().resolveWellKnownType("void"), //$NON-NLS-1$
				new ITypeBinding[] { fieldType }, status, usingLocalSetter);
	}
}
 
Example 13
Source File: LocalTypeAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private boolean checkBinding(List<AbstractTypeDeclaration> declarations, ITypeBinding binding) {
	for (Iterator<AbstractTypeDeclaration> iter = declarations.iterator(); iter.hasNext();) {
		AbstractTypeDeclaration declaration = iter.next();
		if (declaration.resolveBinding() == binding) {
			return true;
		}
	}
	return false;
}
 
Example 14
Source File: RefactorProposalUtility.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean isMoveInnerAvailable(AbstractTypeDeclaration declaration) throws JavaModelException {
	ITypeBinding type = declaration.resolveBinding();
	if (type != null) {
		return RefactoringAvailabilityTester.isMoveInnerAvailable((IType) type.getJavaElement());
	}

	return false;
}
 
Example 15
Source File: APIVersion.java    From apidiff with MIT License 5 votes vote down vote up
public AbstractTypeDeclaration getVersionAccessibleType(AbstractTypeDeclaration typeVersrionReference){
	for (AbstractTypeDeclaration typeDeclarion : this.getTypesPublicAndProtected()) {
		if(typeDeclarion.resolveBinding() != null && typeVersrionReference.resolveBinding() != null){
			if(typeDeclarion.resolveBinding().getQualifiedName().equals(typeVersrionReference.resolveBinding().getQualifiedName())){
				return typeDeclarion;
			}
		}
	}
	return null;
}
 
Example 16
Source File: APIVersion.java    From apidiff with MIT License 5 votes vote down vote up
public AbstractTypeDeclaration getVersionNonAccessibleType(AbstractTypeDeclaration typeVersrionReference){
	for (AbstractTypeDeclaration typeDeclarion : this.getTypesPrivateAndDefault()) {
		if(typeDeclarion.resolveBinding() != null && typeVersrionReference.resolveBinding() != null){
			if(typeDeclarion.resolveBinding().getQualifiedName().equals(typeVersrionReference.resolveBinding().getQualifiedName())){
				return typeDeclarion;
			}
		}
	}

	return null;
}
 
Example 17
Source File: FieldDiff.java    From apidiff with MIT License 4 votes vote down vote up
/**
 * @param field
 * @param type
 * @return true, type is deprecated or field is deprecated
 */
private Boolean isDeprecated(FieldDeclaration field, AbstractTypeDeclaration type){
	Boolean isFieldDeprecated = this.isDeprecatedField(field);
	Boolean isTypeDeprecated = (type != null && type.resolveBinding() != null && type.resolveBinding().isDeprecated()) ? true: false;
	return isFieldDeprecated || isTypeDeprecated;
}
 
Example 18
Source File: TypeDiff.java    From apidiff with MIT License 4 votes vote down vote up
private Boolean isDeprecated(final AbstractTypeDeclaration type){
	return (type != null && type.resolveBinding() != null && type.resolveBinding().isDeprecated()) ? true: false;
}
 
Example 19
Source File: OverrideCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public String updateReplacementString(IDocument document, int offset, ImportRewrite importRewrite,
		boolean snippetStringSupport)
				throws CoreException, BadLocationException {
	Document recoveredDocument= new Document();
	CompilationUnit unit= getRecoveredAST(document, offset, recoveredDocument);
	ImportRewriteContext context = new ContextSensitiveImportRewriteContext(unit, offset, importRewrite);

	ITypeBinding declaringType= null;
	ChildListPropertyDescriptor descriptor= null;
	ASTNode node= NodeFinder.perform(unit, offset, 1);
	node= ASTResolving.findParentType(node);
	String result = null;
	if (node instanceof AnonymousClassDeclaration) {
		declaringType= ((AnonymousClassDeclaration) node).resolveBinding();
		descriptor= AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
	} else if (node instanceof AbstractTypeDeclaration) {
		AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) node;
		descriptor= declaration.getBodyDeclarationsProperty();
		declaringType= declaration.resolveBinding();
	}
	if (declaringType != null) {
		ASTRewrite rewrite= ASTRewrite.create(unit.getAST());
		IMethodBinding methodToOverride= Bindings.findMethodInHierarchy(declaringType, fMethodName, fParamTypes);
		if (methodToOverride == null && declaringType.isInterface()) {
			methodToOverride= Bindings.findMethodInType(node.getAST().resolveWellKnownType("java.lang.Object"), fMethodName, fParamTypes); //$NON-NLS-1$
		}
		if (methodToOverride != null) {
			CodeGenerationSettings settings = PreferenceManager.getCodeGenerationSettings(fJavaProject.getProject());
			MethodDeclaration stub = StubUtility2Core.createImplementationStubCore(fCompilationUnit, rewrite, importRewrite,
					context, methodToOverride, declaringType, settings, declaringType.isInterface(), node,
					snippetStringSupport);
			ListRewrite rewriter= rewrite.getListRewrite(node, descriptor);
			rewriter.insertFirst(stub, null);

			ITrackedNodePosition position= rewrite.track(stub);
			try {
				Map<String, String> options = fJavaProject.getOptions(true);

				rewrite.rewriteAST(recoveredDocument, options).apply(recoveredDocument);

				String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength());

				String indentAt = getIndentAt(recoveredDocument, position.getStartPosition(), settings);
				int generatedIndent = IndentManipulation.measureIndentUnits(indentAt, settings.tabWidth,
						settings.indentWidth);
				// Kinda fishy but empirical data shows Override needs to change indent by at
				// least 1
				generatedIndent = Math.max(1, generatedIndent);

				// Cancel generated code indent
				String delimiter = TextUtilities.getDefaultLineDelimiter(document);
				result = IndentManipulation.changeIndent(generatedCode, generatedIndent, settings.tabWidth,
						settings.indentWidth, "", delimiter);

			} catch (MalformedTreeException | BadLocationException exception) {
				JavaLanguageServerPlugin.logException("Unable to compute override proposal", exception);
			}
		}
	}
	return result;
}
 
Example 20
Source File: UtilTools.java    From apidiff with MIT License 4 votes vote down vote up
public static  String getPath(final AbstractTypeDeclaration node){
	return ((node == null) || (node.resolveBinding() == null) || (node.resolveBinding().getQualifiedName() == null))? "" : node.resolveBinding().getQualifiedName();
}