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

The following examples show how to use org.eclipse.jdt.core.dom.ITypeBinding#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: Binding2JavaModel.java    From lapse-plus with GNU General Public License v3.0 6 votes vote down vote up
private static void createName(ITypeBinding type, boolean includePackage, StringBuffer buffer) {
    ITypeBinding baseType= type;
    if (type.isArray()) {
        baseType= type.getElementType();
    }
    if (!baseType.isPrimitive() && !baseType.isNullType()) {
        ITypeBinding declaringType= baseType.getDeclaringClass();
        if (declaringType != null) {
            createName(declaringType, includePackage, buffer);
            buffer.append('.');
        } else if (includePackage && !baseType.getPackage().isUnnamed()) {
            buffer.append(baseType.getPackage().getName());
            buffer.append('.');
        }
    }
    if (!baseType.isAnonymous()) {
        buffer.append(type.getName());
    } else {
        buffer.append("$local$"); //$NON-NLS-1$
    }
}
 
Example 2
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addTypeQualification(final Type type, final CompilationUnitRewrite targetRewrite, final TextEditGroup group) {
	Assert.isNotNull(type);
	Assert.isNotNull(targetRewrite);
	final ITypeBinding binding= type.resolveBinding();
	if (binding != null) {
		final ITypeBinding declaring= binding.getDeclaringClass();
		if (declaring != null) {
			if (type instanceof SimpleType) {
				final SimpleType simpleType= (SimpleType) type;
				addSimpleTypeQualification(targetRewrite, declaring, simpleType, group);
			} else if (type instanceof ParameterizedType) {
				final ParameterizedType parameterizedType= (ParameterizedType) type;
				final Type rawType= parameterizedType.getType();
				if (rawType instanceof SimpleType)
					addSimpleTypeQualification(targetRewrite, declaring, (SimpleType) rawType, group);
			}
		}
	}
}
 
Example 3
Source File: ConstructorFromSuperclassProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private ITypeBinding getEnclosingInstance() {
	ITypeBinding currBinding= fTypeNode.resolveBinding();
	if (currBinding == null || Modifier.isStatic(currBinding.getModifiers())) {
		return null;
	}
	ITypeBinding superBinding= currBinding.getSuperclass();
	if (superBinding == null || superBinding.getDeclaringClass() == null || Modifier.isStatic(superBinding.getModifiers())) {
		return null;
	}
	ITypeBinding enclosing= superBinding.getDeclaringClass();

	while (currBinding != null) {
		if (Bindings.isSuperType(enclosing, currBinding)) {
			return null; // enclosing in scope
		}
		if (Modifier.isStatic(currBinding.getModifiers())) {
			return null; // no more enclosing instances
		}
		currBinding= currBinding.getDeclaringClass();
	}
	return enclosing;
}
 
Example 4
Source File: TypeProposalUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
static void createName(ITypeBinding type, boolean includePackage,
		List<String> list) {
	ITypeBinding baseType = type;
	if (type.isArray()) {
		baseType = type.getElementType();
	}
	if (!baseType.isPrimitive() && !baseType.isNullType()) {
		ITypeBinding declaringType = baseType.getDeclaringClass();
		if (declaringType != null) {
			createName(declaringType, includePackage, list);
		} else if (includePackage && !baseType.getPackage().isUnnamed()) {
			String[] components = baseType.getPackage().getNameComponents();
			for (int i = 0; i < components.length; i++) {
				list.add(components[i]);
			}
		}
	}
	if (!baseType.isAnonymous()) {
		list.add(type.getName());
	} else {
		list.add("$local$"); //$NON-NLS-1$
	}
}
 
Example 5
Source File: JdtUtils.java    From j2cl with Apache License 2.0 6 votes vote down vote up
private static String getJsNamespace(
    ITypeBinding typeBinding, PackageInfoCache packageInfoCache) {
  checkArgument(!typeBinding.isPrimitive());
  String jsNamespace = JsInteropAnnotationUtils.getJsNamespace(typeBinding);
  if (jsNamespace != null) {
    return jsNamespace;
  }

  // Maybe namespace is set via package-info file?
  boolean isTopLevelType = typeBinding.getDeclaringClass() == null;
  if (isTopLevelType) {
    return packageInfoCache.getJsNamespace(
        getBinaryNameFromTypeBinding(toTopLevelTypeBinding(typeBinding)));
  }
  return null;
}
 
Example 6
Source File: JdtUtils.java    From j2cl with Apache License 2.0 6 votes vote down vote up
private static List<String> getClassComponents(ITypeBinding typeBinding) {
  List<String> classComponents = new ArrayList<>();
  ITypeBinding currentType = typeBinding;
  while (currentType != null) {
    checkArgument(currentType.getTypeDeclaration() != null);
    if (currentType.isLocal()) {
      // JDT binary name for local class is like package.components.EnclosingClass$1SimpleName
      // Extract the generated name by taking the part after the binary name of the declaring
      // class.
      String binaryName = getBinaryNameFromTypeBinding(currentType);
      String declaringClassPrefix =
          getBinaryNameFromTypeBinding(currentType.getDeclaringClass()) + "$";
      checkState(binaryName.startsWith(declaringClassPrefix));
      classComponents.add(0, binaryName.substring(declaringClassPrefix.length()));
    } else {
      classComponents.add(0, currentType.getName());
    }
    currentType = currentType.getDeclaringClass();
  }
  return classComponents;
}
 
Example 7
Source File: Bindings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static void createName(ITypeBinding type, boolean includePackage, List<String> list) {
	ITypeBinding baseType= type;
	if (type.isArray()) {
		baseType= type.getElementType();
	}
	if (!baseType.isPrimitive() && !baseType.isNullType()) {
		ITypeBinding declaringType= baseType.getDeclaringClass();
		if (declaringType != null) {
			createName(declaringType, includePackage, list);
		} else if (includePackage && !baseType.getPackage().isUnnamed()) {
			String[] components= baseType.getPackage().getNameComponents();
			for (int i= 0; i < components.length; i++) {
				list.add(components[i]);
			}
		}
	}
	if (!baseType.isAnonymous()) {
		list.add(type.getName());
	} else {
		list.add("$local$"); //$NON-NLS-1$
	}
}
 
Example 8
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new enclosing instance reference finder.
 *
 * @param binding
 *            the declaring type
 */
public EnclosingInstanceReferenceFinder(final ITypeBinding binding) {
	Assert.isNotNull(binding);
	ITypeBinding declaring= binding.getDeclaringClass();
	while (declaring != null) {
		fEnclosingTypes.add(declaring);
		declaring= declaring.getDeclaringClass();
	}
}
 
Example 9
Source File: TypeURIHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
protected void createResourceURIForClass(ITypeBinding typeBinding, StringBuilder uriBuilder) { 
	ITypeBinding declaringClass = typeBinding.getDeclaringClass();
	if (declaringClass != null) {
		createResourceURIForClass(declaringClass, uriBuilder);
	} else {
		createResourceURIForClassImpl2(typeBinding.getErasure().getQualifiedName(), uriBuilder);
	}
}
 
Example 10
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns a type reference for the given type binding. If the binding is null, an {@link JvmUnknownTypeReference unknown}
 * type reference is returned.
 */
// @NonNull 
protected JvmTypeReference createTypeReference(/* @Nullable */ ITypeBinding typeBinding) {
	if (typeBinding == null) {
		return TypesFactory.eINSTANCE.createJvmUnknownTypeReference();
	}
	if (typeBinding.isArray()) {
		ITypeBinding componentType = typeBinding.getComponentType();
		JvmTypeReference componentTypeReference = createTypeReference(componentType);
		JvmGenericArrayTypeReference typeReference = TypesFactory.eINSTANCE.createJvmGenericArrayTypeReference();
		typeReference.setComponentType(componentTypeReference);
		return typeReference;
	}
	ITypeBinding outer = null;
	if (typeBinding.isMember() && !Modifier.isStatic(typeBinding.getModifiers())) {
		outer = typeBinding.getDeclaringClass();
	}
	JvmParameterizedTypeReference result;
	if (outer != null) {
		JvmParameterizedTypeReference outerReference = (JvmParameterizedTypeReference) createTypeReference(outer);
		result = TypesFactory.eINSTANCE.createJvmInnerTypeReference();
		((JvmInnerTypeReference) result).setOuter(outerReference);
	} else {
		result = TypesFactory.eINSTANCE.createJvmParameterizedTypeReference();
	}
	ITypeBinding[] typeArguments = typeBinding.getTypeArguments();
	if (typeArguments.length != 0) {
		ITypeBinding erasure = typeBinding.getErasure();
		result.setType(createProxy(erasure));
		InternalEList<JvmTypeReference> arguments = (InternalEList<JvmTypeReference>)result.getArguments();
		for (int i = 0; i < typeArguments.length; i++) {
			JvmTypeReference argument = createTypeArgument(typeArguments[i]);
			arguments.addUnique(argument);
		}
	} else {
		result.setType(createProxy(typeBinding));
	}
	return result;
}
 
Example 11
Source File: ScopeAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Collects all elements available in a type: its hierarchy and its outer scopes.
 * @param binding The type binding
 * @param flags Flags defining the elements to report
 * @param requestor the requestor to which all results are reported
 * @return return <code>true</code> if the requestor has reported the binding as found and no further results are required
 */
private boolean addTypeDeclarations(ITypeBinding binding, int flags, IBindingRequestor requestor) {
	if (hasFlag(TYPES, flags) && !binding.isAnonymous()) {
		if (requestor.acceptBinding(binding))
			return true;

		ITypeBinding[] typeParameters= binding.getTypeParameters();
		for (int i= 0; i < typeParameters.length; i++) {
			if (requestor.acceptBinding(typeParameters[i]))
				return true;
		}
	}

	addInherited(binding, flags, requestor); // add inherited

	if (binding.isLocal()) {
		addOuterDeclarationsForLocalType(binding, flags, requestor);
	} else {
		ITypeBinding declaringClass= binding.getDeclaringClass();
		if (declaringClass != null) {
			if (addTypeDeclarations(declaringClass, flags, requestor)) // Recursively add inherited
				return true;
		} else if (hasFlag(TYPES, flags)) {
			if (fRoot.findDeclaringNode(binding) != null) {
				List<AbstractTypeDeclaration> types= fRoot.types();
				for (int i= 0; i < types.size(); i++) {
					if (requestor.acceptBinding(types.get(i).resolveBinding()))
						return true;
				}
			}
		}
	}
	return false;
}
 
Example 12
Source File: InJavaImporter.java    From jdt2famix with Eclipse Public License 1.0 5 votes vote down vote up
private ContainerEntity ensureContainerEntityForTypeBinding(ITypeBinding binding) {
	if (binding.getDeclaringClass() != null)
		return ensureTypeFromTypeBinding(binding.getDeclaringClass());
	if (binding.getPackage() != null)
		return ensureNamespaceFromPackageBinding(binding.getPackage());
	return unknownNamespace();
}
 
Example 13
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isAccessToOuter(ITypeBinding binding) {
	binding= binding.getTypeDeclaration();
	if (Bindings.isSuperType(binding, fCurrentType, false)) {
		return false;
	}
	ITypeBinding outer= fCurrentType.getDeclaringClass();
	while (outer != null) {
		if (Bindings.isSuperType(binding, outer, false)) {
			return true;
		}
		outer= outer.getDeclaringClass();
	}
	return false;
}
 
Example 14
Source File: ScopeAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static ITypeBinding getDeclaringType(IBinding binding) {
	switch (binding.getKind()) {
		case IBinding.VARIABLE:
			return ((IVariableBinding) binding).getDeclaringClass();
		case IBinding.METHOD:
			return ((IMethodBinding) binding).getDeclaringClass();
		case IBinding.TYPE:
			ITypeBinding typeBinding= (ITypeBinding) binding;
			if (typeBinding.getDeclaringClass() != null) {
				return typeBinding;
			}
			return typeBinding;
	}
	return null;
}
 
Example 15
Source File: Bindings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ITypeBinding getTopLevelType(ITypeBinding type) {
	ITypeBinding parent= type.getDeclaringClass();
	while (parent != null) {
		type= parent;
		parent= type.getDeclaringClass();
	}
	return type;
}
 
Example 16
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void modifyInterfaceMemberModifiers(final ITypeBinding binding) {
	Assert.isNotNull(binding);
	ITypeBinding declaring= binding.getDeclaringClass();
	while (declaring != null && !declaring.isInterface()) {
		declaring= declaring.getDeclaringClass();
	}
	if (declaring != null) {
		final ASTNode node= ASTNodes.findDeclaration(binding, fSourceRewrite.getRoot());
		if (node instanceof AbstractTypeDeclaration) {
			ModifierRewrite.create(fSourceRewrite.getASTRewrite(), node).setVisibility(Modifier.PUBLIC, null);
		}
	}
}
 
Example 17
Source File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean classNameHidesEnclosingType() {
    ITypeBinding type= ((AbstractTypeDeclaration) ASTNodes.getParent(fAnonymousInnerClassNode, AbstractTypeDeclaration.class)).resolveBinding();
    while (type != null) {
        if (fClassName.equals(type.getName()))
            return true;
        type= type.getDeclaringClass();
    }
    return false;
}
 
Example 18
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private FieldDeclaration performFieldRewrite(IType type, ParameterObjectFactory pof, RefactoringStatus status) throws CoreException {
	fBaseCURewrite= new CompilationUnitRewrite(type.getCompilationUnit());
	SimpleName name= (SimpleName) NodeFinder.perform(fBaseCURewrite.getRoot(), type.getNameRange());
	TypeDeclaration typeNode= (TypeDeclaration) ASTNodes.getParent(name, ASTNode.TYPE_DECLARATION);
	ASTRewrite rewrite= fBaseCURewrite.getASTRewrite();
	int modifier= Modifier.PRIVATE;
	TextEditGroup removeFieldGroup= fBaseCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractClassRefactoring_group_remove_field);
	FieldDeclaration lastField= null;
	initializeDeclaration(typeNode);
	for (Iterator<FieldInfo> iter= fVariables.values().iterator(); iter.hasNext();) {
		FieldInfo pi= iter.next();
		if (isCreateField(pi)) {
			VariableDeclarationFragment vdf= pi.declaration;
			FieldDeclaration parent= (FieldDeclaration) vdf.getParent();
			if (lastField == null)
				lastField= parent;
			else if (lastField.getStartPosition() < parent.getStartPosition())
				lastField= parent;

			ListRewrite listRewrite= rewrite.getListRewrite(parent, FieldDeclaration.FRAGMENTS_PROPERTY);
			removeNode(vdf, removeFieldGroup, fBaseCURewrite);
			if (listRewrite.getRewrittenList().size() == 0) {
				removeNode(parent, removeFieldGroup, fBaseCURewrite);
			}

			if (fDescriptor.isCreateTopLevel()) {
				IVariableBinding binding= vdf.resolveBinding();
				ITypeRoot typeRoot= fBaseCURewrite.getCu();
				if (binding == null || binding.getType() == null){
					status.addFatalError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_fatal_error_cannot_resolve_binding, BasicElementLabels.getJavaElementName(pi.name)), JavaStatusContext.create(typeRoot, vdf));
				} else {
					ITypeBinding typeBinding= binding.getType();
					if (Modifier.isPrivate(typeBinding.getModifiers())){
						status.addError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_error_referencing_private_class, BasicElementLabels.getJavaElementName(typeBinding.getName())), JavaStatusContext.create(typeRoot, vdf));
					} else if (Modifier.isProtected(typeBinding.getModifiers())){
						ITypeBinding declaringClass= typeBinding.getDeclaringClass();
						if (declaringClass != null) {
							IPackageBinding package1= declaringClass.getPackage();
							if (package1 != null && !fDescriptor.getPackage().equals(package1.getName())){
								status.addError(Messages.format(RefactoringCoreMessages.ExtractClassRefactoring_error_referencing_protected_class, new String[] {BasicElementLabels.getJavaElementName(typeBinding.getName()), BasicElementLabels.getJavaElementName(fDescriptor.getPackage())}), JavaStatusContext.create(typeRoot, vdf));
							}
						}
					}
				}
			}
			Expression initializer= vdf.getInitializer();
			if (initializer != null)
				pi.initializer= initializer;
			int modifiers= parent.getModifiers();
			if (!MemberVisibilityAdjustor.hasLowerVisibility(modifiers, modifier)){
				modifier= modifiers;
			}
		}
	}
	FieldDeclaration fieldDeclaration= createParameterObjectField(pof, typeNode, modifier);
	ListRewrite bodyDeclList= rewrite.getListRewrite(typeNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
	if (lastField != null)
		bodyDeclList.insertAfter(fieldDeclaration, lastField, null);
	else
		bodyDeclList.insertFirst(fieldDeclaration, null);
	return fieldDeclaration;
}
 
Example 19
Source File: ElementTypeTeller.java    From txtUML with Eclipse Public License 1.0 4 votes vote down vote up
public static boolean isContained(ITypeBinding value) {
	ITypeBinding parent = (ITypeBinding) value.getDeclaringClass();
	return Stream.of(parent.getDeclaredTypes()).filter(d -> d != value)
			.anyMatch(d -> isContainer(d));
}
 
Example 20
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void createCompilationUnitRewrite(final ITypeBinding[] parameters, final CompilationUnitRewrite targetRewrite, final Map<ICompilationUnit, SearchMatch[]> typeReferences, final Map<ICompilationUnit, SearchMatch[]> constructorReferences, boolean visibilityWasAdjusted, final ICompilationUnit sourceUnit, final ICompilationUnit targetUnit, final boolean remove, final RefactoringStatus status, final IProgressMonitor monitor) throws CoreException {
	Assert.isNotNull(parameters);
	Assert.isNotNull(targetRewrite);
	Assert.isNotNull(typeReferences);
	Assert.isNotNull(constructorReferences);
	Assert.isNotNull(sourceUnit);
	Assert.isNotNull(targetUnit);
	final CompilationUnit root= targetRewrite.getRoot();
	final ASTRewrite rewrite= targetRewrite.getASTRewrite();
	if (targetUnit.equals(sourceUnit)) {
		final AbstractTypeDeclaration declaration= findTypeDeclaration(fType, root);
		final TextEditGroup qualifierGroup= fSourceRewrite.createGroupDescription(RefactoringCoreMessages.MoveInnerToTopRefactoring_change_qualifier);
		ITypeBinding binding= declaration.resolveBinding();
		if (!remove) {
			if (!JdtFlags.isStatic(fType) && fCreateInstanceField) {
				if (JavaElementUtil.getAllConstructors(fType).length == 0)
					createConstructor(declaration, rewrite);
				else
					modifyConstructors(declaration, rewrite);
				addInheritedTypeQualifications(declaration, targetRewrite, qualifierGroup);
				addEnclosingInstanceDeclaration(declaration, rewrite);
			}
			fTypeImports= new HashSet<ITypeBinding>();
			fStaticImports= new HashSet<IBinding>();
			ImportRewriteUtil.collectImports(fType.getJavaProject(), declaration, fTypeImports, fStaticImports, false);
			if (binding != null)
				fTypeImports.remove(binding);
		}
		addEnclosingInstanceTypeParameters(parameters, declaration, rewrite);
		modifyAccessToEnclosingInstance(targetRewrite, declaration, monitor);
		if (binding != null) {
			modifyInterfaceMemberModifiers(binding);
			final ITypeBinding declaring= binding.getDeclaringClass();
			if (declaring != null)
				declaration.accept(new TypeReferenceQualifier(binding, null));
		}
		final TextEditGroup groupMove= targetRewrite.createGroupDescription(RefactoringCoreMessages.MoveInnerToTopRefactoring_change_label);
		if (remove) {
			rewrite.remove(declaration, groupMove);
			targetRewrite.getImportRemover().registerRemovedNode(declaration);
		} else {
			// Bug 101017/96308: Rewrite the visibility of the element to be
			// moved and add a warning.

			// Note that this cannot be done in the MemberVisibilityAdjustor, as the private and
			// static flags must always be cleared when moving to new type.
			int newFlags= JdtFlags.clearFlag(Modifier.STATIC, declaration.getModifiers());

			if (!visibilityWasAdjusted) {
				if (Modifier.isPrivate(declaration.getModifiers()) || Modifier.isProtected(declaration.getModifiers())) {
					newFlags= JdtFlags.clearFlag(Modifier.PROTECTED | Modifier.PRIVATE, newFlags);
					final RefactoringStatusEntry entry= new RefactoringStatusEntry(RefactoringStatus.WARNING, Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_change_visibility_type_warning, new String[] { BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_FULLY_QUALIFIED)}), JavaStatusContext.create(fSourceRewrite.getCu()));
					if (!containsStatusEntry(status, entry))
						status.addEntry(entry);
				}
			}

			ModifierRewrite.create(rewrite, declaration).setModifiers(newFlags, groupMove);
		}
	}
	ASTNode[] references= getReferenceNodesIn(root, typeReferences, targetUnit);
	for (int index= 0; index < references.length; index++)
		updateTypeReference(parameters, references[index], targetRewrite, targetUnit);
	references= getReferenceNodesIn(root, constructorReferences, targetUnit);
	for (int index= 0; index < references.length; index++)
		updateConstructorReference(parameters, references[index], targetRewrite, targetUnit);
}