org.eclipse.jdt.core.dom.IPackageBinding Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.IPackageBinding. 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
public static ICompilationUnit findCompilationUnit(ITypeBinding typeBinding, IJavaProject project) throws JavaModelException {
    if (!typeBinding.isFromSource()) {
        return null;
    }
    while (typeBinding != null && !typeBinding.isTopLevel()) {
        typeBinding= typeBinding.getDeclaringClass();
    }
    if (typeBinding != null) {
        IPackageBinding pack= typeBinding.getPackage();
        String packageName= pack.isUnnamed() ? "" : pack.getName(); //$NON-NLS-1$
        IType type= project.findType(packageName, typeBinding.getName());
        if (type != null) {
            return type.getCompilationUnit();
        }
    }
    return null;
}
 
Example #2
Source File: StructCache.java    From junion with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static Entry get(Name type) {
	IBinding b = type.resolveBinding();		
	if(b == null) {
		CompilerError.exec(CompilerError.TYPE_NOT_FOUND, type.toString() + ", " + type.getClass());
		return null;
	}
	if(b instanceof IPackageBinding) {
		return null;
	}
	if(b instanceof ITypeBinding) {
		return get((ITypeBinding)b);
	}
	if(b instanceof IVariableBinding) {
		IVariableBinding vb = (IVariableBinding)b;
		return get(vb.getType());		
	}
	Log.err("IGNORING BINFIND " + b + ", " + b.getClass());
	return null;
}
 
Example #3
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private JvmDeclaredType createType(IType type, ITypeBinding binding) {
	// Maintain a string builder we pass along during recursion 
	// that contains the prefix for the fully qualified name of the binding instance being traversed.
	//
	StringBuilder fqn = new StringBuilder(100);
	IPackageBinding packageBinding = binding.getPackage();
	String packageName = null;
	if (packageBinding != null && !packageBinding.isUnnamed()) {
		packageName = packageBinding.getName();
		fqn.append(packageBinding.getName());
		fqn.append('.');
	}

	JvmDeclaredType result = createType(binding, type.getHandleIdentifier(), Lists.<String>newArrayList(), fqn);
	result.setPackageName(packageName);
	return result;
}
 
Example #4
Source File: ModelUtils.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @return an empty optional if the given package binding is not the top
 *         package of a JtxtUML model; otherwise an optional of the name of
 *         the model (the name is the name of the package if not specified)
 */
public static Optional<String> findModelNameInTopPackage(IPackageBinding packageBinding) {
	List<IAnnotationBinding> annots = Stream.of(packageBinding.getAnnotations())
			.filter(a -> a.getAnnotationType().getQualifiedName().equals(Model.class.getCanonicalName()))
			.collect(Collectors.toList());

	if (annots.size() == 1) {
		Optional<String> name = Stream.of(annots.get(0).getDeclaredMemberValuePairs())
				.filter(p -> p.getName().equals("value")).map(p -> (String) p.getValue()).findAny();
		if (name.isPresent()) {
			return name;
		} else {
			return Optional.of(packageBinding.getName());
		}
	}

	return Optional.empty();
}
 
Example #5
Source File: ElementTypeTeller.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
public static boolean isModelElement(CompilationUnit unit) {
	// careful nullchecking is required below
	// to prevent the workspace problem window from appearing

	PackageDeclaration packageDeclaration = unit.getPackage();
	if (packageDeclaration == null) {
		// the model cannot be in default package
		return false;
	}

	IPackageBinding packageBinding = packageDeclaration.resolveBinding();
	if (packageBinding == null) {
		// wrong package declaration, can't validate
		return false;
	}

	IJavaElement javaElement = packageBinding.getJavaElement();
	if (javaElement == null) {
		// something went wrong during the lookup, can't validate
		return false;
	}

	return isModelPackage((IPackageFragment) javaElement);
}
 
Example #6
Source File: Binding2JavaModel.java    From lapse-plus with GNU General Public License v3.0 5 votes vote down vote up
private static IPath getPathToCompilationUnit(IPackageBinding packageBinding, String topLevelTypeName) {
    IPath result= new Path(""); //$NON-NLS-1$
    String[] packageNames= packageBinding.getNameComponents();
    for (int i= 0; i < packageNames.length; i++) {
        result= result.append(packageNames[i]);
    }
    return result.append(topLevelTypeName + ".java"); //$NON-NLS-1$
}
 
Example #7
Source File: OverrideMethodsOperation.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static List<OverridableMethod> listOverridableMethods(IType type) {
	if (type == null || type.getCompilationUnit() == null) {
		return Collections.emptyList();
	}

	List<OverridableMethod> overridables = new ArrayList<>();
	RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL);
	CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true);
	try {
		ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
		if (typeBinding == null) {
			return overridables;
		}

		IMethodBinding cloneMethod = null;
		ITypeBinding cloneable = astRoot.getAST().resolveWellKnownType("java.lang.Cloneable");
		if (Bindings.isSuperType(cloneable, typeBinding)) {
			cloneMethod = resolveWellKnownCloneMethod(astRoot.getAST());
		}

		IPackageBinding pack = typeBinding.getPackage();
		IMethodBinding[] methods = StubUtility2Core.getOverridableMethods(astRoot.getAST(), typeBinding, false);
		for (IMethodBinding method : methods) {
			if (Bindings.isVisibleInHierarchy(method, pack)) {
				boolean toImplement = Objects.equals(method, cloneMethod);
				overridables.add(convertToSerializableMethod(method, toImplement));
			}
		}
	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.logException("List overridable methods", e);
	}

	return overridables;
}
 
Example #8
Source File: ModelUtils.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
private static IPackageBinding getPackageBinding(CompilationUnit cu) {
	try {
		return cu.getPackage().resolveBinding();
	} catch (NullPointerException e) {
		return null;
	}
}
 
Example #9
Source File: AbstractSourceExporter.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ModelId getModelOf(Class<?> element, ElementExporter elementExporter) throws ElementExportationException {
	try {
		Package ownPackage = element.getPackage();

		if (ownPackage.getAnnotation(Model.class) != null) {
			return new ModelIdImpl(ownPackage.getName());
		}
		String ownPackageName = ownPackage.getName();

		IJavaProject javaProject = ProjectUtils.findJavaProject(elementExporter.getSourceProjectName());

		Stream<ICompilationUnit> stream = PackageUtils.findAllPackageFragmentsAsStream(javaProject)
				.filter(p -> ownPackageName.startsWith(p.getElementName() + "."))
				.map(pf -> pf.getCompilationUnit(PackageUtils.PACKAGE_INFO)).filter(ICompilationUnit::exists);

		String topPackageName = Stream.of(SharedUtils.parseICompilationUnitStream(stream, javaProject))
				.map(CompilationUnit::getPackage).filter(Objects::nonNull).map(PackageDeclaration::resolveBinding)
				.filter(Objects::nonNull).filter(pb -> ModelUtils.findModelNameInTopPackage(pb).isPresent())
				.map(IPackageBinding::getName).findFirst().get();

		return new ModelIdImpl(topPackageName);

	} catch (NotFoundException | JavaModelException | IOException | NoSuchElementException e) {
		e.printStackTrace();
		throw new ElementExportationException();
	}
}
 
Example #10
Source File: MoveStaticMemberAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void rewriteName(Name name, ITypeBinding type) {
	AST creator= name.getAST();
	boolean fullyQualified= false;
	if (name instanceof QualifiedName) {
		SimpleName left= ASTNodes.getLeftMostSimpleName(name);
		if (left.resolveBinding() instanceof IPackageBinding)
			fullyQualified= true;
	}
	if (fullyQualified) {
		fCuRewrite.getASTRewrite().replace(
			name,
			ASTNodeFactory.newName(creator, type.getQualifiedName()),
			fCuRewrite.createGroupDescription(REFERENCE_UPDATE));
		fCuRewrite.getImportRemover().registerRemovedNode(name);
	} else {
		ImportRewriteContext context= new ContextSensitiveImportRewriteContext(name, fCuRewrite.getImportRewrite());
		Type result= fCuRewrite.getImportRewrite().addImport(type, fCuRewrite.getAST(), context);
		fCuRewrite.getImportRemover().registerAddedImport(type.getQualifiedName());
		Name n= ASTNodeFactory.newName(fCuRewrite.getAST(), ASTFlattener.asString(result));
		fCuRewrite.getASTRewrite().replace(
			name,
			n,
			fCuRewrite.createGroupDescription(REFERENCE_UPDATE));
		fCuRewrite.getImportRemover().registerRemovedNode(name);
		fNeedsImport= true;
	}
}
 
Example #11
Source File: Bindings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isVisibleInHierarchy(IMethodBinding member, IPackageBinding pack) {
	int otherflags= member.getModifiers();
	ITypeBinding declaringType= member.getDeclaringClass();
	if (Modifier.isPublic(otherflags) || Modifier.isProtected(otherflags) || (declaringType != null && declaringType.isInterface())) {
		return true;
	} else if (Modifier.isPrivate(otherflags)) {
		return false;
	}
	return declaringType != null && pack == declaringType.getPackage();
}
 
Example #12
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 5 votes vote down vote up
private void setPublicModifierToSourceMethod(IMethodBinding methodBinding, TypeDeclaration sourceTypeDeclaration) {
	MethodDeclaration[] methodDeclarations = sourceTypeDeclaration.getMethods();
	for(MethodDeclaration methodDeclaration : methodDeclarations) {
		if(methodDeclaration.resolveBinding().isEqualTo(methodBinding)) {
			CompilationUnit sourceCompilationUnit = RefactoringUtility.findCompilationUnit(methodDeclaration);
			ASTRewrite sourceRewriter = ASTRewrite.create(sourceCompilationUnit.getAST());
			ListRewrite modifierRewrite = sourceRewriter.getListRewrite(methodDeclaration, MethodDeclaration.MODIFIERS2_PROPERTY);
			Modifier publicModifier = methodDeclaration.getAST().newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD);
			boolean modifierFound = false;
			List<IExtendedModifier> modifiers = methodDeclaration.modifiers();
			for(IExtendedModifier extendedModifier : modifiers) {
				if(extendedModifier.isModifier()) {
					Modifier modifier = (Modifier)extendedModifier;
					if(modifier.getKeyword().equals(Modifier.ModifierKeyword.PUBLIC_KEYWORD)) {
						modifierFound = true;
					}
					else if(modifier.getKeyword().equals(Modifier.ModifierKeyword.PRIVATE_KEYWORD)) {
						modifierFound = true;
						modifierRewrite.replace(modifier, publicModifier, null);
						updateAccessModifier(sourceRewriter, sourceCompilationUnit);
					}
					else if(modifier.getKeyword().equals(Modifier.ModifierKeyword.PROTECTED_KEYWORD)) {
						modifierFound = true;
						IPackageBinding targetTypeDeclarationPackageBinding = this.targetTypeDeclaration.resolveBinding().getPackage();
						IPackageBinding typeDeclarationPackageBinding = sourceTypeDeclaration.resolveBinding().getPackage();
						if(targetTypeDeclarationPackageBinding != null && typeDeclarationPackageBinding != null &&
								!targetTypeDeclarationPackageBinding.isEqualTo(typeDeclarationPackageBinding)) {
							modifierRewrite.replace(modifier, publicModifier, null);
							updateAccessModifier(sourceRewriter, sourceCompilationUnit);
						}
					}
				}
			}
			if(!modifierFound) {
				modifierRewrite.insertFirst(publicModifier, null);
				updateAccessModifier(sourceRewriter, sourceCompilationUnit);
			}
		}
	}
}
 
Example #13
Source File: InJavaImporter.java    From jdt2famix with Eclipse Public License 1.0 4 votes vote down vote up
public Namespace ensureNamespaceFromPackageBinding(IPackageBinding binding) {
	return ensureNamespaceNamed(binding.getName());
}
 
Example #14
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 #15
Source File: StubUtility2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static MethodDeclaration createDelegationStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, IMethodBinding delegate, IVariableBinding delegatingField, CodeGenerationSettings settings) throws CoreException {
	Assert.isNotNull(delegate);
	Assert.isNotNull(delegatingField);
	Assert.isNotNull(settings);

	AST ast= rewrite.getAST();

	MethodDeclaration decl= ast.newMethodDeclaration();
	decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, delegate.getModifiers() & ~Modifier.SYNCHRONIZED & ~Modifier.ABSTRACT & ~Modifier.NATIVE));

	decl.setName(ast.newSimpleName(delegate.getName()));
	decl.setConstructor(false);

	createTypeParameters(imports, context, ast, delegate, decl);

	decl.setReturnType2(imports.addImport(delegate.getReturnType(), ast, context));

	List<SingleVariableDeclaration> params= createParameters(unit.getJavaProject(), imports, context, ast, delegate, null, decl);

	createThrownExceptions(decl, delegate, imports, context, ast);

	Block body= ast.newBlock();
	decl.setBody(body);

	String delimiter= StubUtility.getLineDelimiterUsed(unit);

	Statement statement= null;
	MethodInvocation invocation= ast.newMethodInvocation();
	invocation.setName(ast.newSimpleName(delegate.getName()));
	List<Expression> arguments= invocation.arguments();
	for (int i= 0; i < params.size(); i++)
		arguments.add(ast.newSimpleName(params.get(i).getName().getIdentifier()));
	if (settings.useKeywordThis) {
		FieldAccess access= ast.newFieldAccess();
		access.setExpression(ast.newThisExpression());
		access.setName(ast.newSimpleName(delegatingField.getName()));
		invocation.setExpression(access);
	} else
		invocation.setExpression(ast.newSimpleName(delegatingField.getName()));
	if (delegate.getReturnType().isPrimitive() && delegate.getReturnType().getName().equals("void")) {//$NON-NLS-1$
		statement= ast.newExpressionStatement(invocation);
	} else {
		ReturnStatement returnStatement= ast.newReturnStatement();
		returnStatement.setExpression(invocation);
		statement= returnStatement;
	}
	body.statements().add(statement);

	ITypeBinding declaringType= delegatingField.getDeclaringClass();
	if (declaringType == null) { // can be null for
		return decl;
	}

	String qualifiedName= declaringType.getQualifiedName();
	IPackageBinding packageBinding= declaringType.getPackage();
	if (packageBinding != null) {
		if (packageBinding.getName().length() > 0 && qualifiedName.startsWith(packageBinding.getName()))
			qualifiedName= qualifiedName.substring(packageBinding.getName().length());
	}

	if (settings.createComments) {
		/*
		 * TODO: have API for delegate method comments This is an inlined
		 * version of
		 * {@link CodeGeneration#getMethodComment(ICompilationUnit, String, MethodDeclaration, IMethodBinding, String)}
		 */
		delegate= delegate.getMethodDeclaration();
		String declaringClassQualifiedName= delegate.getDeclaringClass().getQualifiedName();
		String linkToMethodName= delegate.getName();
		String[] parameterTypesQualifiedNames= StubUtility.getParameterTypeNamesForSeeTag(delegate);
		String string= StubUtility.getMethodComment(unit, qualifiedName, decl, delegate.isDeprecated(), linkToMethodName, declaringClassQualifiedName, parameterTypesQualifiedNames, true, delimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example #16
Source File: StubUtility2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static void findUnimplementedInterfaceMethods(ITypeBinding typeBinding, HashSet<ITypeBinding> visited,
		ArrayList<IMethodBinding> allMethods, IPackageBinding currPack, ArrayList<IMethodBinding> toImplement) {
	
	if (visited.add(typeBinding)) {
		IMethodBinding[] typeMethods= typeBinding.getDeclaredMethods();
		
		nextMethod: for (int i= 0; i < typeMethods.length; i++) {
			IMethodBinding curr= typeMethods[i];
			for (Iterator<IMethodBinding> allIter= allMethods.iterator(); allIter.hasNext();) {
				IMethodBinding oneMethod= allIter.next();
				if (Bindings.isSubsignature(oneMethod, curr)) {
					// We've already seen a method that is a subsignature of curr.
					if (!Bindings.isSubsignature(curr, oneMethod)) {
						// oneMethod is a true subsignature of curr; let's go with oneMethod
						continue nextMethod;
					}
					// Subsignatures are equivalent.
					// Check visibility and return types ('getErasure()' tries to achieve effect of "rename type variables")
					if (Bindings.isVisibleInHierarchy(oneMethod, currPack)
							&& oneMethod.getReturnType().getErasure().isSubTypeCompatible(curr.getReturnType().getErasure())) {
						// oneMethod is visible and curr doesn't have a stricter return type; let's go with oneMethod
						continue nextMethod;
					}
					// curr is stricter than oneMethod, so let's remove oneMethod
					allIter.remove();
					toImplement.remove(oneMethod);
				} else if (Bindings.isSubsignature(curr, oneMethod)) {
					// curr is a true subsignature of oneMethod. Let's remove oneMethod.
					allIter.remove();
					toImplement.remove(oneMethod);
				}
			}
			if (Modifier.isAbstract(curr.getModifiers())) {
				toImplement.add(curr);
				allMethods.add(curr);
			}
		}
		ITypeBinding[] superInterfaces= typeBinding.getInterfaces();
		for (int i= 0; i < superInterfaces.length; i++)
			findUnimplementedInterfaceMethods(superInterfaces[i], visited, allMethods, currPack, toImplement);
	}
}