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

The following examples show how to use org.eclipse.jdt.core.dom.CompilationUnit#accept() . 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: JavaMethodClassCounter.java    From api-mining with GNU General Public License v3.0 6 votes vote down vote up
public static void countMethodsClasses(final File projectDir)
		throws IOException {

	System.out.println("\n===== Project " + projectDir);
	final MethodClassCountVisitor mccv = new MethodClassCountVisitor();
	final JavaASTExtractor astExtractor = new JavaASTExtractor(false);

	final List<File> files = (List<File>) FileUtils.listFiles(projectDir,
			new String[] { "java" }, true);

	int count = 0;
	for (final File file : files) {

		final CompilationUnit cu = astExtractor.getAST(file);
		cu.accept(mccv);

		if (count % 1000 == 0)
			System.out.println("At file " + count + " of " + files.size());
		count++;
	}

	System.out.println("Project " + projectDir);
	System.out.println("No. *.java files " + files.size());
	System.out.println("No. Methods: " + mccv.noMethods);
	System.out.println("No. Classes: " + mccv.noClasses);
}
 
Example 2
Source File: ControlStatementsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit,
		boolean convertSingleStatementToBlock,
		boolean removeUnnecessaryBlock,
		boolean removeUnnecessaryBlockContainingReturnOrThrow) {

	if (!convertSingleStatementToBlock && !removeUnnecessaryBlock && !removeUnnecessaryBlockContainingReturnOrThrow)
		return null;

	List<CompilationUnitRewriteOperation> operations= new ArrayList<CompilationUnitRewriteOperation>();
	ControlStatementFinder finder= new ControlStatementFinder(convertSingleStatementToBlock, removeUnnecessaryBlock, removeUnnecessaryBlockContainingReturnOrThrow, operations);
	compilationUnit.accept(finder);

	if (operations.isEmpty())
		return null;

	CompilationUnitRewriteOperation[] ops= operations.toArray(new CompilationUnitRewriteOperation[operations.size()]);
	return new ControlStatementsFix(FixMessages.ControlStatementsFix_change_name, compilationUnit, ops);
}
 
Example 3
Source File: TempDeclarationFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @return <code>null</code> if the selection is invalid or does not cover a temp
 * declaration or reference.
 */
public static VariableDeclaration findTempDeclaration(CompilationUnit cu, int selectionOffset, int selectionLength) {
	TempSelectionAnalyzer analyzer= new TempSelectionAnalyzer(selectionOffset, selectionLength);
	cu.accept(analyzer);

	ASTNode[] selected= analyzer.getSelectedNodes();
	if (selected == null || selected.length != 1)
		return null;

	ASTNode selectedNode= selected[0];
	if (selectedNode instanceof VariableDeclaration)
		return (VariableDeclaration)selectedNode;

	if (selectedNode instanceof Name){
		Name reference= (Name)selectedNode;
		IBinding binding= reference.resolveBinding();
		if (binding == null)
			return null;
		ASTNode declaringNode= cu.findDeclaringNode(binding);
		if (declaringNode instanceof VariableDeclaration)
			return (VariableDeclaration)declaringNode;
		else
			return null;
	} else if (selectedNode instanceof VariableDeclarationStatement){
		VariableDeclarationStatement vds= (VariableDeclarationStatement)selectedNode;
		if (vds.fragments().size() != 1)
			return null;
		return (VariableDeclaration)vds.fragments().get(0);
	}
	return null;
}
 
Example 4
Source File: SimpleFilter.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
public List<Pair<CodeBlock, Double>> filter(String srcPath, double guard){
	List<String> files = JavaFile.ergodic(srcPath, new ArrayList<String>());
	List<Pair<CodeBlock, Double>> filtered = new ArrayList<>();
	CollectorVisitor collectorVisitor = new CollectorVisitor();
	for(String file : files){
		CompilationUnit unit = JavaFile.genASTFromFile(file);
		collectorVisitor.setUnit(file, unit);
		unit.accept(collectorVisitor);
		filtered = filter(filtered, guard);
	}
	
	Set<String> exist = new HashSet<>();
	for(Pair<CodeBlock, Double> pair : filtered){
		if(exist.contains(pair.getFirst().toSrcString().toString())){
			continue;
		}
		exist.add(pair.getFirst().toSrcString().toString());
		double similarity = CodeBlockMatcher.getRewardSimilarity(_buggyCode, pair.getFirst()) + pair.getSecond();
		pair.setSecond(similarity);
	}
	
	Collections.sort(filtered, new Comparator<Pair<CodeBlock, Double>>() {
		@Override
		public int compare(Pair<CodeBlock, Double> o1, Pair<CodeBlock, Double> o2) {
			if(o1.getSecond() < o2.getSecond()){
				return 1;
			} else if(o1.getSecond() > o2.getSecond()){
				return -1;
			} else {
				return 0;
			}
		}
	});
	
	return filtered;
}
 
Example 5
Source File: CommentTestCase.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
public static void comment(String fileBasePath, List<String> testcases, String avoid){
	Map<String, Set<String>> clazzAndMethods = new HashMap<>();
	for(String test : testcases){
		if(test.equals(avoid)){
			continue;
		}
		String[] testInfo = test.split("::");
		if(testInfo.length != 2){
			System.err.println("Test case format error : " + test);
			continue;
		}
		Set<String> methods = clazzAndMethods.get(testInfo[0]);
		if(methods == null){
			methods = new HashSet<>();
		}
		methods.add(testInfo[1]);
		clazzAndMethods.put(testInfo[0], methods);
	}
	
	for(Entry<String, Set<String>> entry : clazzAndMethods.entrySet()){
		String fileName = fileBasePath + "/" + entry.getKey().replace(".", "/") + ".java";
		CompilationUnit cUnit = JavaFile.genASTFromFile(fileName);
		CommentTestCaseVisitor visitor = new CommentTestCaseVisitor(entry.getValue());
		cUnit.accept(visitor);
		JavaFile.writeStringToFile(fileName, cUnit.toString());
	}
}
 
Example 6
Source File: ASTVisitors.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get covering Block/Class node, returning the root node if there is none
 */
public static ASTNode getCoveringBlock(final CompilationUnit root, final ASTNode node) {

	final CoveringBlockFinderVisitor finder = new CoveringBlockFinderVisitor(node.getStartPosition(),
			node.getLength());
	root.accept(finder);
	final ASTNode coveringBlock = finder.getCoveringBlock();

	if (coveringBlock != null)
		return coveringBlock;
	else
		return root;
}
 
Example 7
Source File: JavaTextSelection.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ASTNode[] resolveSelectedNodes() {
	if (fNodesRequested)
		return fSelectedNodes;
	fNodesRequested= true;
	CompilationUnit root= resolvePartialAstAtOffset();
	if (root == null)
		return null;
	Selection ds= Selection.createFromStartLength(getOffset(), getLength());
	SelectionAnalyzer analyzer= new SelectionAnalyzer(ds, false);
	root.accept(analyzer);
	fSelectedNodes= analyzer.getSelectedNodes();
	fCoveringNode= analyzer.getLastCoveringNode();
	return fSelectedNodes;
}
 
Example 8
Source File: MethodRetriever.java    From tassal with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Map<String, MethodDeclaration> getMethodNodes(final File file)
		throws IOException {
	final JavaASTExtractor astExtractor = new JavaASTExtractor(false);
	final MethodRetriever m = new MethodRetriever();
	final CompilationUnit cu = astExtractor.getAST(file);
	cu.accept(m);
	return m.methods;
}
 
Example 9
Source File: JavaTypeHierarchyExtractor.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
private Collection<Pair<String, String>> getParentTypeRelationshipsFrom(
		final File file) {
	final JavaASTExtractor ex = new JavaASTExtractor(true);
	try {
		final CompilationUnit ast = ex.getAST(file);
		final HierarchyExtractor hEx = new HierarchyExtractor();
		ast.accept(hEx);
		return hEx.parentChildRelationships;
	} catch (final IOException e) {
		LOGGER.warning(ExceptionUtils.getFullStackTrace(e));
	}
	return Collections.emptySet();
}
 
Example 10
Source File: ProblemMarkerBuilder.java    From CogniCrypt with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * setupParser Method that sets up the Parser and creates a visitor for a specific unit
 *
 * @param unit Unit from getUnitForParser
 */
private void setupParser(final ICompilationUnit unit) {
	final ASTParser parser = ASTParser.newParser(AST.JLS10);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setSource(unit);
	parser.setResolveBindings(true);
	final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
	cu.accept(createMarkerVisitor(unit, cu));
}
 
Example 11
Source File: TypeContextChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Type parseType(String typeString, IJavaProject javaProject, List<String> problemsCollector) {
	if ("".equals(typeString.trim())) //speed up for a common case //$NON-NLS-1$
		return null;
	if (! typeString.trim().equals(typeString))
		return null;

	StringBuffer cuBuff= new StringBuffer();
	cuBuff.append("interface A{"); //$NON-NLS-1$
	int offset= cuBuff.length();
	cuBuff.append(typeString).append(" m();}"); //$NON-NLS-1$

	ASTParser p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	p.setSource(cuBuff.toString().toCharArray());
	p.setProject(javaProject);
	CompilationUnit cu= (CompilationUnit) p.createAST(null);
	Selection selection= Selection.createFromStartLength(offset, typeString.length());
	SelectionAnalyzer analyzer= new SelectionAnalyzer(selection, false);
	cu.accept(analyzer);
	ASTNode selected= analyzer.getFirstSelectedNode();
	if (!(selected instanceof Type))
		return null;
	Type type= (Type)selected;
	if (MethodTypesSyntaxChecker.isVoidArrayType(type))
		return null;
	IProblem[] problems= ASTNodes.getProblems(type, ASTNodes.NODE_ONLY, ASTNodes.PROBLEMS);
	if (problems.length > 0) {
		for (int i= 0; i < problems.length; i++)
			problemsCollector.add(problems[i].getMessage());
	}

	String typeNodeRange= cuBuff.substring(type.getStartPosition(), ASTNodes.getExclusiveEnd(type));
	if (typeString.equals(typeNodeRange))
		return type;
	else
		return null;
}
 
Example 12
Source File: DeclarationInfoManager.java    From lapse-plus with GNU General Public License v3.0 5 votes vote down vote up
public static DeclarationInfo retrieveDeclarationInfo(CompilationUnit unit) {
	DeclarationInfo info  = (DeclarationInfo) unit2info.get(unit);
	if(info == null) {
		DeclarationFinderVisitor visitor = new DeclarationFinderVisitor();
		unit.accept(visitor);
		info = visitor.getInfo();
		// save for future use
		unit2info.put(unit, info);
		visitor = null;
	}
	
	return info;
}
 
Example 13
Source File: SelfEncapsulateFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
	pm.beginTask(NO_NAME, 12);
	pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_checking_preconditions);

	RefactoringStatus result = new RefactoringStatus();
	fRewriter = ASTRewrite.create(fRoot.getAST());
	fChangeManager.clear();

	boolean usingLocalGetter = isUsingLocalGetter();
	boolean usingLocalSetter = isUsingLocalSetter();
	result.merge(checkMethodNames(usingLocalGetter, usingLocalSetter));
	pm.worked(1);
	if (result.hasFatalError()) {
		return result;
	}
	pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_searching_for_cunits);
	final SubProgressMonitor subPm = new SubProgressMonitor(pm, 5);
	ICompilationUnit[] affectedCUs = RefactoringSearchEngine.findAffectedCompilationUnits(SearchPattern.createPattern(fField, IJavaSearchConstants.REFERENCES), RefactoringScopeFactory.create(fField, fConsiderVisibility), subPm, result,
			true);

	checkInHierarchy(result, usingLocalGetter, usingLocalSetter);
	if (result.hasFatalError()) {
		return result;
	}

	pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_analyzing);
	IProgressMonitor sub = new SubProgressMonitor(pm, 5);
	sub.beginTask(NO_NAME, affectedCUs.length);
	IVariableBinding fieldIdentifier = fFieldDeclaration.resolveBinding();
	ITypeBinding declaringClass = ASTNodes.getParent(fFieldDeclaration, AbstractTypeDeclaration.class).resolveBinding();
	List<TextEditGroup> ownerDescriptions = new ArrayList<>();
	ICompilationUnit owner = fField.getCompilationUnit();
	fImportRewrite = StubUtility.createImportRewrite(fRoot, true);

	for (int i = 0; i < affectedCUs.length; i++) {
		ICompilationUnit unit = affectedCUs[i];
		sub.subTask(BasicElementLabels.getFileName(unit));
		CompilationUnit root = null;
		ASTRewrite rewriter = null;
		ImportRewrite importRewrite;
		List<TextEditGroup> descriptions;
		if (owner.equals(unit)) {
			root = fRoot;
			rewriter = fRewriter;
			importRewrite = fImportRewrite;
			descriptions = ownerDescriptions;
		} else {
			root = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(unit, true);
			rewriter = ASTRewrite.create(root.getAST());
			descriptions = new ArrayList<>();
			importRewrite = StubUtility.createImportRewrite(root, true);
		}
		checkCompileErrors(result, root, unit);
		AccessAnalyzer analyzer = new AccessAnalyzer(this, unit, fieldIdentifier, declaringClass, rewriter, importRewrite);
		root.accept(analyzer);
		result.merge(analyzer.getStatus());
		if (!fSetterMustReturnValue) {
			fSetterMustReturnValue= analyzer.getSetterMustReturnValue();
		}
		if (result.hasFatalError()) {
			fChangeManager.clear();
			return result;
		}
		descriptions.addAll(analyzer.getGroupDescriptions());
		if (!owner.equals(unit)) {
			createEdits(unit, rewriter, descriptions, importRewrite);
		}
		sub.worked(1);
		if (pm.isCanceled()) {
			throw new OperationCanceledException();
		}
	}
	ownerDescriptions.addAll(addGetterSetterChanges(fRoot, fRewriter, owner.findRecommendedLineSeparator(), usingLocalSetter, usingLocalGetter));
	createEdits(owner, fRewriter, ownerDescriptions, fImportRewrite);

	sub.done();
	IFile[] filesToBeModified = ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits());
	result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext(), pm));
	if (result.hasFatalError()) {
		return result;
	}
	ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1));
	return result;
}
 
Example 14
Source File: SrcTreeGenerator.java    From sahagin-java with Apache License 2.0 4 votes vote down vote up
@Override
public void acceptAST(String sourceFilePath, CompilationUnit ast) {
    ast.accept(new CollectCodeVisitor(
            subClassTable, rootMethodTable, subMethodTable, fieldTable, ast));
}
 
Example 15
Source File: SequenceDiagramCompilationParticipant.java    From txtUML with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected void validate(CompilationUnit unit, ProblemCollector collector) {
	if (!ElementTypeTeller.isModelElement(unit)) {
		unit.accept(new SequenceDiagramVisitor(collector));
	}
}
 
Example 16
Source File: NodeUtils.java    From SimFix with GNU General Public License v2.0 4 votes vote down vote up
public static Map<String, Type> getUsableVarTypes(String file, int line){
	CompilationUnit unit = JavaFile.genASTFromFile(file);
	VariableVisitor variableVisitor = new VariableVisitor(line, unit);
	unit.accept(variableVisitor);
	return variableVisitor.getVars();
}
 
Example 17
Source File: ASTNodeSearchUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static ASTNode getAstNode(CompilationUnit cuNode, int start, int length){
	SelectionAnalyzer analyzer= new SelectionAnalyzer(Selection.createFromStartLength(start, length), true);
	cuNode.accept(analyzer);
	//XXX workaround for jdt core feature 23527
	ASTNode node= analyzer.getFirstSelectedNode();
	if (node == null && analyzer.getLastCoveringNode() instanceof SuperConstructorInvocation) {
		node= analyzer.getLastCoveringNode().getParent();
	} else if (node == null && analyzer.getLastCoveringNode() instanceof ConstructorInvocation) {
		node= analyzer.getLastCoveringNode().getParent();
	}

	if (node == null) {
		return null;
	}

	ASTNode parentNode= node.getParent();

	if (parentNode instanceof MethodDeclaration){
		MethodDeclaration md= (MethodDeclaration)parentNode;
		if (!(node instanceof SimpleName)
			&& md.isConstructor()
		    && md.getBody() != null
		    && md.getBody().statements().size() > 0
		    &&(md.getBody().statements().get(0) instanceof ConstructorInvocation || md.getBody().statements().get(0) instanceof SuperConstructorInvocation)
		    &&((ASTNode)md.getBody().statements().get(0)).getLength() == length + 1) {
			return (ASTNode)md.getBody().statements().get(0);
		}
	}

	if (parentNode instanceof SuperConstructorInvocation){
		if (parentNode.getLength() == length + 1) {
			return parentNode;
		}
	}
	if (parentNode instanceof ConstructorInvocation){
		if (parentNode.getLength() == length + 1) {
			return parentNode;
		}
	}
	return node;
}
 
Example 18
Source File: ModelTest.java    From txtUML with Eclipse Public License 1.0 3 votes vote down vote up
@Test
public void testInvalidTypeInModel() throws Exception {
	CompilationUnit compilationUnit = prepareAST("InvalidTypeInModelClass.java");

	compilationUnit.accept(new ModelVisitor(mockCollector));

	verify(mockCollector).report(is(INVALID_ATTRIBUTE_TYPE));

	checkNoOtherErrorRaised();
}
 
Example 19
Source File: ModelTest.java    From txtUML with Eclipse Public License 1.0 3 votes vote down vote up
@Test
public void testMethodInSignal() throws Exception {
	CompilationUnit compilationUnit = prepareAST("MethodInSignal.java");

	compilationUnit.accept(new ModelVisitor(mockCollector));

	verify(mockCollector, times(1)).report(is(INVALID_SIGNAL_CONTENT));

	checkNoOtherErrorRaised();
}
 
Example 20
Source File: ModelTest.java    From txtUML with Eclipse Public License 1.0 3 votes vote down vote up
@Test
public void testInvalidTypeInSignal() throws Exception {
	CompilationUnit compilationUnit = prepareAST("InvalidTypeInSignal.java");

	compilationUnit.accept(new ModelVisitor(mockCollector));

	verify(mockCollector, times(2)).report(is(INVALID_ATTRIBUTE_TYPE));

	checkNoOtherErrorRaised();
}