Java Code Examples for org.eclipse.jdt.core.dom.CompilationUnit#types()

The following examples show how to use org.eclipse.jdt.core.dom.CompilationUnit#types() . 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: XbaseHoverDocumentationProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Javadoc getJavaDoc() {
	if (context == null || context.eResource() == null || context.eResource().getResourceSet() == null)
		return null;
	Object classpathURIContext = ((XtextResourceSet) context.eResource().getResourceSet()).getClasspathURIContext();
	if (classpathURIContext instanceof IJavaProject) {
		IJavaProject javaProject = (IJavaProject) classpathURIContext;
		@SuppressWarnings("all")
		ASTParser parser = ASTParser.newParser(AST.JLS3);
		parser.setProject(javaProject);
		Map<String, String> options = javaProject.getOptions(true);
		options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212207
		parser.setCompilerOptions(options);
		String source = rawJavaDoc + "class C{}"; //$NON-NLS-1$
		parser.setSource(source.toCharArray());
		CompilationUnit root = (CompilationUnit) parser.createAST(null);
		if (root == null)
			return null;
		List<AbstractTypeDeclaration> types = root.types();
		if (types.size() != 1)
			return null;
		AbstractTypeDeclaration type = types.get(0);
		return type.getJavadoc();
	}
	return null;
}
 
Example 2
Source File: JavadocContentAccess2.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static Javadoc getJavadocNode(IJavaElement element, String rawJavadoc) {
	//FIXME: take from SharedASTProvider if available
	//Caveat: Javadoc nodes are not available when Javadoc processing has been disabled!
	//https://bugs.eclipse.org/bugs/show_bug.cgi?id=212207

	String source = rawJavadoc + "class C{}"; //$NON-NLS-1$
	CompilationUnit root = createAST(element, source);
	if (root == null) {
		return null;
	}
	List<AbstractTypeDeclaration> types = root.types();
	if (types.size() != 1) {
		return null;
	}
	AbstractTypeDeclaration type = types.get(0);
	return type.getJavadoc();
}
 
Example 3
Source File: UMLModelASTReader.java    From RefactoringMiner with MIT License 6 votes vote down vote up
protected void processCompilationUnit(String sourceFilePath, CompilationUnit compilationUnit) {
	PackageDeclaration packageDeclaration = compilationUnit.getPackage();
	String packageName = null;
	if(packageDeclaration != null)
		packageName = packageDeclaration.getName().getFullyQualifiedName();
	else
		packageName = "";
	
	List<ImportDeclaration> imports = compilationUnit.imports();
	List<String> importedTypes = new ArrayList<String>();
	for(ImportDeclaration importDeclaration : imports) {
		importedTypes.add(importDeclaration.getName().getFullyQualifiedName());
	}
	List<AbstractTypeDeclaration> topLevelTypeDeclarations = compilationUnit.types();
       for(AbstractTypeDeclaration abstractTypeDeclaration : topLevelTypeDeclarations) {
       	if(abstractTypeDeclaration instanceof TypeDeclaration) {
       		TypeDeclaration topLevelTypeDeclaration = (TypeDeclaration)abstractTypeDeclaration;
       		processTypeDeclaration(compilationUnit, topLevelTypeDeclaration, packageName, sourceFilePath, importedTypes);
       	}
       	else if(abstractTypeDeclaration instanceof EnumDeclaration) {
       		EnumDeclaration enumDeclaration = (EnumDeclaration)abstractTypeDeclaration;
       		processEnumDeclaration(compilationUnit, enumDeclaration, packageName, sourceFilePath, importedTypes);
       	}
       }
}
 
Example 4
Source File: ImportRewriteAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static int getFirstTypeBeginPos(CompilationUnit root) {
	List types= root.types();
	if (!types.isEmpty()) {
		return root.getExtendedStartPosition(((ASTNode) types.get(0)));
	}
	return -1;
}
 
Example 5
Source File: SM_TypeTest.java    From DesigniteJava with Apache License 2.0 5 votes vote down vote up
@Test
public void SM_Type_getName() {
	CompilationUnit unit = project.createCU(getTestingPath() + File.separator + "test_package" +File.separator + "TestClass.java");
	List<TypeDeclaration> typeList = unit.types();

	SM_Type type = null;
	for (TypeDeclaration typeDecl : typeList)
		type = new SM_Type(typeDecl, unit, new SM_Package("Test", project, null), null);
		
	assertEquals(type.getName(), "TestClass");		
}
 
Example 6
Source File: JavadocContentAccess2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Javadoc getJavadocNode(IJavaElement element, String rawJavadoc) {
	//FIXME: take from SharedASTProvider if available
	//Caveat: Javadoc nodes are not available when Javadoc processing has been disabled!
	//https://bugs.eclipse.org/bugs/show_bug.cgi?id=212207

	String source= rawJavadoc + "class C{}"; //$NON-NLS-1$
	CompilationUnit root= createAST(element, source);
	if (root == null)
		return null;
	List<AbstractTypeDeclaration> types= root.types();
	if (types.size() != 1)
		return null;
	AbstractTypeDeclaration type= types.get(0);
	return type.getJavadoc();
}
 
Example 7
Source File: ASTProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a string for the given AST used for debugging.
 *
 * @param ast the compilation unit AST
 * @return a string used for debugging
 */
private String toString(CompilationUnit ast) {
	if (ast == null)
		return "null"; //$NON-NLS-1$

	List<AbstractTypeDeclaration> types= ast.types();
	if (types != null && types.size() > 0)
		return types.get(0).getName().getIdentifier() + "(" + ast.hashCode() + ")"; //$NON-NLS-1$//$NON-NLS-2$
	else
		return "AST without any type"; //$NON-NLS-1$
}
 
Example 8
Source File: ASTNodeFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static Type newType(AST ast, String content) {
	StringBuffer buffer= new StringBuffer(TYPE_HEADER);
	buffer.append(content);
	buffer.append(TYPE_FOOTER);
	ASTParser p= ASTParser.newParser(ast.apiLevel());
	p.setSource(buffer.toString().toCharArray());
	CompilationUnit root= (CompilationUnit) p.createAST(null);
	List<AbstractTypeDeclaration> list= root.types();
	TypeDeclaration typeDecl= (TypeDeclaration) list.get(0);
	MethodDeclaration methodDecl= typeDecl.getMethods()[0];
	ASTNode type= methodDecl.getReturnType2();
	ASTNode result= ASTNode.copySubtree(ast, type);
	result.accept(new PositionClearer());
	return (Type)result;
}
 
Example 9
Source File: ASTNodeFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static TypeParameter newTypeParameter(AST ast, String content) {
	StringBuffer buffer= new StringBuffer(TYPEPARAM_HEADER);
	buffer.append(content);
	buffer.append(TYPEPARAM_FOOTER);
	ASTParser p= ASTParser.newParser(ast.apiLevel());
	p.setSource(buffer.toString().toCharArray());
	CompilationUnit root= (CompilationUnit) p.createAST(null);
	List<AbstractTypeDeclaration> list= root.types();
	TypeDeclaration typeDecl= (TypeDeclaration) list.get(0);
	MethodDeclaration methodDecl= typeDecl.getMethods()[0];
	TypeParameter tp= (TypeParameter) methodDecl.typeParameters().get(0);
	ASTNode result= ASTNode.copySubtree(ast, tp);
	result.accept(new PositionClearer());
	return (TypeParameter) result;
}
 
Example 10
Source File: Utils.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static List<AbstractTypeDeclaration> getSequenceDiagrams(CompilationUnit node) {
	List<AbstractTypeDeclaration> types = node.types();
	List<AbstractTypeDeclaration> sequenceDiagrams = types.stream().map(td -> ((AbstractTypeDeclaration) td))
			.filter(td -> implementsInteraction(td.resolveBinding())).collect(toList());
	return sequenceDiagrams;
}
 
Example 11
Source File: WizardUtils.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @return the list of types in the given compilation unit.
 */
private synchronized static List<?> getTypes(ICompilationUnit compilationUnit) {
	ASTParser parser = ASTParser.newParser(AST.JLS8);
	parser.setResolveBindings(true);
	parser.setSource(compilationUnit);
	CompilationUnit cu = (CompilationUnit) parser.createAST(null);
	return cu.types();
}
 
Example 12
Source File: SM_MethodTest.java    From DesigniteJava with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void setUp() {
	project = new SM_Project(new InputArgs(getTestingPath() + File.separator + "test_package", getTestingPath()));
	CompilationUnit unit = project.createCU(getTestingPath() + File.separator + "test_package" + File.separator + "TestMethods.java");
	List<TypeDeclaration> typeList = unit.types();
	
	for(TypeDeclaration typeDecl: typeList){
		type = new SM_Type(typeDecl, unit, new SM_Package("Test", project, null), null);
		type.parse();
	}

	methods = type.getMethodList();
}
 
Example 13
Source File: SM_TypeTest.java    From DesigniteJava with Apache License 2.0 5 votes vote down vote up
@Test(expected = NullPointerException.class)
public void SM_Type_nullCompilationUnit() {
	CompilationUnit unit = project.createCU(getTestingPath() + File.separator +"test_package"+File.separator +"TestClass.java");
	List<TypeDeclaration> listOfTypes = unit.types();
	
	type = new SM_Type(listOfTypes.get(0), null, null, null);	
}
 
Example 14
Source File: SM_TypeTest.java    From DesigniteJava with Apache License 2.0 5 votes vote down vote up
@Test
public void SM_Type_check_isInterface() {
	CompilationUnit unit = project.createCU(getTestingPath() + File.separator +"test_package"+File.separator +"Interface.java");
	List<TypeDeclaration> typeList = unit.types();

	SM_Type type = null;
	for (TypeDeclaration typeDecl : typeList)
		type = new SM_Type(typeDecl, unit, new SM_Package("Test", project, null), null);
	assertTrue(type.isInterface());		
}
 
Example 15
Source File: SM_TypeTest.java    From DesigniteJava with Apache License 2.0 5 votes vote down vote up
@Test
public void SM_Type_check_isAbstract() {
	CompilationUnit unit = project.createCU(getTestingPath() + File.separator +"test_package" + File.separator + "AbstractClass.java");
	List<TypeDeclaration> typeList = unit.types();

	SM_Type type = null;
	for (TypeDeclaration typeDecl : typeList)
		type = new SM_Type(typeDecl, unit, new SM_Package("Test", project, null), null);
	assertTrue(type.isAbstract());		
}
 
Example 16
Source File: SM_TypeTest.java    From DesigniteJava with Apache License 2.0 5 votes vote down vote up
@Test
public void SM_Type_checkDefaultAccess() {
	CompilationUnit unit = project.createCU(getTestingPath() + File.separator + "test_package" +File.separator + "DefaultClass.java");
	List<TypeDeclaration> typeList = unit.types();

	SM_Type type = null;
	for (TypeDeclaration typeDecl : typeList)
		type = new SM_Type(typeDecl, unit, new SM_Package("Test", project, null), null);
	assertEquals(type.getAccessModifier(), AccessStates.DEFAULT);		
}
 
Example 17
Source File: ReorgCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static void getWrongTypeNameProposals(IInvocationContext context, IProblemLocationCore problem,
		Collection<ChangeCorrectionProposal> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();
	boolean isLinked = cu.getResource().isLinked();

	IJavaProject javaProject= cu.getJavaProject();
	String sourceLevel= javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
	String compliance= javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);

	CompilationUnit root= context.getASTRoot();

	ASTNode coveredNode= problem.getCoveredNode(root);
	if (!(coveredNode instanceof SimpleName)) {
		return;
	}

	ASTNode parentType= coveredNode.getParent();
	if (!(parentType instanceof AbstractTypeDeclaration)) {
		return;
	}

	String currTypeName= ((SimpleName) coveredNode).getIdentifier();
	String newTypeName= JavaCore.removeJavaLikeExtension(cu.getElementName());


	boolean hasOtherPublicTypeBefore = false;

	boolean found = false;
	List<AbstractTypeDeclaration> types= root.types();
	for (int i= 0; i < types.size(); i++) {
		AbstractTypeDeclaration curr= types.get(i);
		if (parentType != curr) {
			if (newTypeName.equals(curr.getName().getIdentifier())) {
				return;
			}
			if (!found && Modifier.isPublic(curr.getModifiers())) {
				hasOtherPublicTypeBefore = true;
			}
		} else {
			found = true;
		}
	}

	if (!JavaConventions.validateJavaTypeName(newTypeName, sourceLevel, compliance).matches(IStatus.ERROR)) {
		proposals.add(new CorrectMainTypeNameProposal(cu, context, currTypeName, newTypeName, IProposalRelevance.RENAME_TYPE));
	}

	if (!hasOtherPublicTypeBefore && JavaLanguageServerPlugin.getPreferencesManager().getClientPreferences().isResourceOperationSupported()) {
		String newCUName = JavaModelUtil.getRenamedCUName(cu, currTypeName);
		ICompilationUnit newCU = ((IPackageFragment) (cu.getParent())).getCompilationUnit(newCUName);
		if (!newCU.exists() && !isLinked && !JavaConventions.validateCompilationUnitName(newCUName, sourceLevel, compliance).matches(IStatus.ERROR)) {
			RenameCompilationUnitChange change = new RenameCompilationUnitChange(cu, newCUName);

			// rename CU
			String label = Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_renamecu_description, BasicElementLabels.getResourceName(newCUName));
			proposals.add(new ChangeCorrectionProposal(label, CodeActionKind.QuickFix, change, IProposalRelevance.RENAME_CU));
		}
	}

}
 
Example 18
Source File: PlantUmlExporter.java    From txtUML with Eclipse Public License 1.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private TypeDeclaration getSequenceDiagramTypeDeclaration(String sequenceDiagramName, CompilationUnit cu) {
	List<TypeDeclaration> declarations = cu.types();
	return declarations.stream()
			.filter(decl -> decl.resolveBinding().getQualifiedName().equals(sequenceDiagramName)).findFirst().get();
}
 
Example 19
Source File: ReorgCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void getWrongTypeNameProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ICompilationUnit cu= context.getCompilationUnit();
	boolean isLinked= cu.getResource().isLinked();

	IJavaProject javaProject= cu.getJavaProject();
	String sourceLevel= javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
	String compliance= javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);

	CompilationUnit root= context.getASTRoot();

	ASTNode coveredNode= problem.getCoveredNode(root);
	if (!(coveredNode instanceof SimpleName))
		return;

	ASTNode parentType= coveredNode.getParent();
	if (!(parentType instanceof AbstractTypeDeclaration))
		return;

	String currTypeName= ((SimpleName) coveredNode).getIdentifier();
	String newTypeName= JavaCore.removeJavaLikeExtension(cu.getElementName());

	boolean hasOtherPublicTypeBefore= false;

	boolean found= false;
	List<AbstractTypeDeclaration> types= root.types();
	for (int i= 0; i < types.size(); i++) {
		AbstractTypeDeclaration curr= types.get(i);
		if (parentType != curr) {
			if (newTypeName.equals(curr.getName().getIdentifier())) {
				return;
			}
			if (!found && Modifier.isPublic(curr.getModifiers())) {
				hasOtherPublicTypeBefore= true;
			}
		} else {
			found= true;
		}
	}
	if (!JavaConventions.validateJavaTypeName(newTypeName, sourceLevel, compliance).matches(IStatus.ERROR)) {
		proposals.add(new CorrectMainTypeNameProposal(cu, context, currTypeName, newTypeName, IProposalRelevance.RENAME_TYPE));
	}

	if (!hasOtherPublicTypeBefore) {
		String newCUName= JavaModelUtil.getRenamedCUName(cu, currTypeName);
		ICompilationUnit newCU= ((IPackageFragment) (cu.getParent())).getCompilationUnit(newCUName);
		if (!newCU.exists() && !isLinked && !JavaConventions.validateCompilationUnitName(newCUName, sourceLevel, compliance).matches(IStatus.ERROR)) {
			RenameCompilationUnitChange change= new RenameCompilationUnitChange(cu, newCUName);

			// rename CU
			String label= Messages.format(CorrectionMessages.ReorgCorrectionsSubProcessor_renamecu_description, BasicElementLabels.getResourceName(newCUName));
			proposals.add(new ChangeCorrectionProposal(label, change, IProposalRelevance.RENAME_CU, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_RENAME)));
		}
	}
}