org.eclipse.jdt.core.dom.CompilationUnit#accept ( )源码实例Demo

下面列出了org.eclipse.jdt.core.dom.CompilationUnit#accept ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

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);
}
 
源代码2 项目: api-mining   文件: JavaMethodClassCounter.java
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);
}
 
源代码3 项目: tassal   文件: MethodRetriever.java
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;
}
 
源代码4 项目: lapse-plus   文件: DeclarationInfoManager.java
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;
}
 
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;
}
 
源代码6 项目: CogniCrypt   文件: ProblemMarkerBuilder.java
/**
 * 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));
}
 
源代码7 项目: api-mining   文件: JavaTypeHierarchyExtractor.java
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();
}
 
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;
}
 
源代码9 项目: api-mining   文件: ASTVisitors.java
/**
 * 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;
}
 
源代码10 项目: SimFix   文件: CommentTestCase.java
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());
	}
}
 
源代码11 项目: SimFix   文件: SimpleFilter.java
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;
}
 
/**
 * @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;
}
 
@Override
protected void validate(CompilationUnit unit, ProblemCollector collector) {
	if (!ElementTypeTeller.isModelElement(unit)) {
		unit.accept(new SequenceDiagramVisitor(collector));
	}
}
 
源代码14 项目: sahagin-java   文件: SrcTreeGenerator.java
@Override
public void acceptAST(String sourceFilePath, CompilationUnit ast) {
    ast.accept(new CollectCodeVisitor(
            subClassTable, rootMethodTable, subMethodTable, fieldTable, ast));
}
 
源代码15 项目: SimFix   文件: NodeUtils.java
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();
}
 
源代码16 项目: eclipse.jdt.ls   文件: ASTNodeSearchUtil.java
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;
}
 
@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;
}
 
源代码18 项目: txtUML   文件: ModelTest.java
@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();
}
 
源代码19 项目: txtUML   文件: ModelTest.java
@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();
}
 
源代码20 项目: txtUML   文件: ModelTest.java
@Test
public void testInvalidTypeInModel() throws Exception {
	CompilationUnit compilationUnit = prepareAST("InvalidTypeInModelClass.java");

	compilationUnit.accept(new ModelVisitor(mockCollector));

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

	checkNoOtherErrorRaised();
}