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

The following examples show how to use org.eclipse.jdt.core.dom.MethodDeclaration#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: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Checks whether the method has references to type variables or generic
 * types.
 *
 * @param monitor
 *            the progress monitor to display progress
 * @param declaration
 *            the method declaration to check for generic types
 * @param status
 *            the status of the condition checking
 */
protected void checkGenericTypes(final IProgressMonitor monitor, final MethodDeclaration declaration, final RefactoringStatus status) {
	Assert.isNotNull(monitor);
	Assert.isNotNull(declaration);
	Assert.isNotNull(status);
	try {
		monitor.beginTask("", 1); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
		final AstNodeFinder finder= new GenericReferenceFinder(declaration);
		declaration.accept(finder);
		if (!finder.getStatus().isOK())
			status.merge(finder.getStatus());
	} finally {
		monitor.done();
	}
}
 
Example 2
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Sets the new target.
 *
 * @param target
 *            the target to set
 */
public final void setTarget(final IVariableBinding target) {
	Assert.isNotNull(target);
	fTarget= target;
	fTargetType= null;
	try {
		final MethodDeclaration declaration= ASTNodeSearchUtil.getMethodDeclarationNode(fMethod, fSourceRewrite.getRoot());
		if (declaration != null) {
			final AstNodeFinder finder= new ThisReferenceFinder();
			declaration.accept(finder);
			fTargetNode= !finder.getResult().isEmpty();
			return;
		}
	} catch (JavaModelException exception) {
		JavaPlugin.log(exception);
	}
	fTargetNode= true;
}
 
Example 3
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
private void addAdditionalMethodsToTargetClass() {
	AST ast = targetTypeDeclaration.getAST();
	Set<MethodDeclaration> methodsToBeMoved = new LinkedHashSet<MethodDeclaration>(additionalMethodsToBeMoved.values());
	for(MethodDeclaration methodDeclaration : methodsToBeMoved) {
		TypeVisitor typeVisitor = new TypeVisitor();
		methodDeclaration.accept(typeVisitor);
		for(ITypeBinding typeBinding : typeVisitor.getTypeBindings()) {
			this.additionalTypeBindingsToBeImportedInTargetClass.add(typeBinding);
		}
		MethodDeclaration newMethodDeclaration = (MethodDeclaration)ASTNode.copySubtree(ast, methodDeclaration);
		ASTRewrite targetRewriter = ASTRewrite.create(targetCompilationUnit.getAST());
		ListRewrite targetClassBodyRewrite = targetRewriter.getListRewrite(targetTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
		targetClassBodyRewrite.insertLast(newMethodDeclaration, null);
		try {
			TextEdit targetEdit = targetRewriter.rewriteAST();
			targetMultiTextEdit.addChild(targetEdit);
			targetCompilationUnitChange.addTextEditGroup(new TextEditGroup("Add additional moved method", new TextEdit[] {targetEdit}));
		}
		catch(JavaModelException javaModelException) {
			javaModelException.printStackTrace();
		}
	}
}
 
Example 4
Source File: CallerFinder.java    From lapse-plus with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a collection of return statements withing @param methodDeclaration.
 * */
public static Collection<ReturnStatement> findReturns(IProgressMonitor progressMonitor, MethodDeclaration methodDeclaration, JavaProject project) {
	progressMonitor.setTaskName("Looking for returns in " + methodDeclaration.getName());
	final Collection<ReturnStatement> returns = new ArrayList<ReturnStatement>();
	ASTVisitor finder = new ASTVisitor() {			
		public boolean visit(ReturnStatement node) {
			return returns.add(node);
		}
	};
	
	methodDeclaration.accept(finder);
	return returns;
}
 
Example 5
Source File: CodeSearch.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
public boolean visit(MethodDeclaration node){
	
	int start = _unit.getLineNumber(node.getStartPosition());
	int end = _unit.getLineNumber(node.getStartPosition() + node.getLength());
	if(start <= _extendedLine && _extendedLine <= end){
		FindExactLineVisitor visitor = new FindExactLineVisitor();
		node.accept(visitor);
		return false;
	}
	return true;
}
 
Example 6
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks whether the instance method body is compatible with this
 * refactoring.
 *
 * @param monitor
 *            the progress monitor to display progress
 * @param declaration
 *            the method declaration whose body to check
 * @param status
 *            the status of the condition checking
 */
protected void checkMethodBody(final IProgressMonitor monitor, final MethodDeclaration declaration, final RefactoringStatus status) {
	Assert.isNotNull(monitor);
	Assert.isNotNull(declaration);
	Assert.isNotNull(status);
	try {
		monitor.beginTask("", 3); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.MoveInstanceMethodProcessor_checking);
		AstNodeFinder finder= new SuperReferenceFinder();
		declaration.accept(finder);
		if (!finder.getStatus().isOK())
			status.merge(finder.getStatus());
		monitor.worked(1);
		finder= null;
		final IMethodBinding binding= declaration.resolveBinding();
		if (binding != null) {
			final ITypeBinding declaring= binding.getDeclaringClass();
			if (declaring != null)
				finder= new EnclosingInstanceReferenceFinder(declaring);
		}
		if (finder != null) {
			declaration.accept(finder);
			if (!finder.getStatus().isOK())
				status.merge(finder.getStatus());
			monitor.worked(1);
			finder= new RecursiveCallFinder(declaration);
			declaration.accept(finder);
			if (!finder.getStatus().isOK())
				status.merge(finder.getStatus());
			monitor.worked(1);
		}
	} finally {
		monitor.done();
	}
}
 
Example 7
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Computes the target categories for the method to move.
 *
 * @param declaration
 *            the method declaration
 * @return the possible targets as variable bindings of read-only fields and
 *         parameters
 */
protected IVariableBinding[] computeTargetCategories(final MethodDeclaration declaration) {
	Assert.isNotNull(declaration);
	if (fPossibleTargets.length == 0 || fCandidateTargets.length == 0) {
		final List<IVariableBinding> possibleTargets= new ArrayList<IVariableBinding>(16);
		final List<IVariableBinding> candidateTargets= new ArrayList<IVariableBinding>(16);
		final IMethodBinding method= declaration.resolveBinding();
		if (method != null) {
			final ITypeBinding declaring= method.getDeclaringClass();
			IVariableBinding[] bindings= getArgumentBindings(declaration);
			ITypeBinding binding= null;
			for (int index= 0; index < bindings.length; index++) {
				binding= bindings[index].getType();
				if ((binding.isClass() || binding.isEnum() || is18OrHigherInterface(binding)) && binding.isFromSource()) {
					possibleTargets.add(bindings[index]);
					candidateTargets.add(bindings[index]);
				}
			}
			final ReadyOnlyFieldFinder visitor= new ReadyOnlyFieldFinder(declaring);
			declaration.accept(visitor);
			bindings= visitor.getReadOnlyFields();
			for (int index= 0; index < bindings.length; index++) {
				binding= bindings[index].getType();
				if ((binding.isClass() || is18OrHigherInterface(binding)) && binding.isFromSource())
					possibleTargets.add(bindings[index]);
			}
			bindings= visitor.getDeclaredFields();
			for (int index= 0; index < bindings.length; index++) {
				binding= bindings[index].getType();
				if ((binding.isClass() || is18OrHigherInterface(binding)) && binding.isFromSource())
					candidateTargets.add(bindings[index]);
			}
		}
		fPossibleTargets= new IVariableBinding[possibleTargets.size()];
		possibleTargets.toArray(fPossibleTargets);
		fCandidateTargets= new IVariableBinding[candidateTargets.size()];
		candidateTargets.toArray(fCandidateTargets);
	}
	return fPossibleTargets;
}
 
Example 8
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private List<ITypeConstraint> getConstraints(ICompilationUnit unit) {
	if (fConstraintCache.containsKey(unit))
		return fConstraintCache.get(unit);

	CompilationUnit cu= ASTCreator.createAST(unit, null);

	// only generate type constraints for relevant MethodDeclaration subtrees
	if (fMethodBinding != null && fCuToSearchResultGroup.containsKey(unit)){
		SearchResultGroup group= fCuToSearchResultGroup.get(unit);
		ASTNode[] nodes= ASTNodeSearchUtil.getAstNodes(group.getSearchResults(), cu);
		for (int i=0; i < nodes.length; i++){
			ASTNode node = nodes[i];
			if (fMethodBinding != null){
				// find MethodDeclaration above it in the tree
				ASTNode n= node;
				while (n != null && !(n instanceof MethodDeclaration)) {
					n = n.getParent();
				}
				MethodDeclaration md= (MethodDeclaration) n;
				if (md != null)
					md.accept(fCollector);
			}
		}
	} else {
		cu.accept(fCollector);
	}
	List<ITypeConstraint> constraints= Arrays.asList(fCollector.getConstraints());
	fConstraintCache.put(unit, constraints);
	return constraints;
}
 
Example 9
Source File: PromoteTempToFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private RefactoringStatus checkClashesInConstructors() {
	Assert.isTrue(fInitializeIn == INITIALIZE_IN_CONSTRUCTOR);
	Assert.isTrue(!isDeclaredInAnonymousClass());
	final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) getMethodDeclaration().getParent();
	if (declaration instanceof TypeDeclaration) {
		MethodDeclaration[] methods= ((TypeDeclaration) declaration).getMethods();
		for (int i= 0; i < methods.length; i++) {
			MethodDeclaration method= methods[i];
			if (!method.isConstructor())
				continue;
			NameCollector nameCollector= new NameCollector(method) {
				@Override
				protected boolean visitNode(ASTNode node) {
					return true;
				}
			};
			method.accept(nameCollector);
			List<String> names= nameCollector.getNames();
			if (names.contains(fFieldName)) {
				String[] keys= { BasicElementLabels.getJavaElementName(fFieldName), BindingLabelProvider.getBindingLabel(method.resolveBinding(), JavaElementLabels.ALL_FULLY_QUALIFIED)};
				String msg= Messages.format(RefactoringCoreMessages.PromoteTempToFieldRefactoring_Name_conflict, keys);
				return RefactoringStatus.createFatalErrorStatus(msg);
			}
		}
	}
	return null;
}
 
Example 10
Source File: LambdaExpressionsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
static boolean hasReference(MethodDeclaration node) {
	try {
		SuperThisReferenceFinder finder= new SuperThisReferenceFinder();
		ClassInstanceCreation cic= (ClassInstanceCreation) node.getParent().getParent();
		finder.fFunctionalInterface= cic.getType().resolveBinding();
		finder.fMethodDeclaration= node;
		node.accept(finder);
	} catch (AbortSearchException e) {
		return true;
	}
	return false;
}
 
Example 11
Source File: TypeParseVisitor.java    From SimFix with GNU General Public License v2.0 4 votes vote down vote up
public boolean visit(MethodDeclaration node) {

//		ASTNode parent = node.getParent();
//		while(parent != null){
//			if(parent instanceof TypeDeclaration){
//				break;
//			}
//			parent = parent.getParent();
//		}
//		if(parent == null){
//			return true;
//		}
//		
//		String className = ((TypeDeclaration)parent).getName().getFullyQualifiedName();
//		ProjectInfo.addMethodRetType(className, node.getName().getFullyQualifiedName(), node.getReturnType2());
//		
//		String methodName = node.getName().toString();
//		String params = "";
//		for(Object obj : node.parameters()){
//			SingleVariableDeclaration singleVariableDeclaration = (SingleVariableDeclaration) obj;
//			params += ","+singleVariableDeclaration.getType().toString();
//		}
//		methodName += params;
		
		if(node.getBody() == null || node.getParent() instanceof AnonymousClassDeclaration){
			return true;
		}
		
		Pair<String, String> classAndMethodName = NodeUtils.getTypeDecAndMethodDec(node.getBody());
		String className = classAndMethodName.getFirst();
		String methodName = classAndMethodName.getSecond();
		
		ProjectInfo.addMethodRetType(className, node.getName().getFullyQualifiedName(), node.getReturnType2());
		
		for (Object o : node.parameters()) {
			SingleVariableDeclaration svd = (SingleVariableDeclaration) o;
			ProjectInfo.addMethodVariableType(className, methodName, svd.getName().toString(), getType(svd));
		}

		MethodVisitor mv = new MethodVisitor();
		node.accept(mv);

		for (Entry<String, Type> entry : mv.getVarMap().entrySet()) {
			ProjectInfo.addMethodVariableType(className, methodName, entry.getKey(), entry.getValue());
		}

		return true;
	}
 
Example 12
Source File: MethodParser.java    From aDoctor with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static MethodBean parse(MethodDeclaration pMethodNode, Collection<InstanceVariableBean> pClassInstanceVariableBeans) {

    // Instantiate the bean
    MethodBean methodBean = new MethodBean();

    // Set the name
    methodBean.setName(pMethodNode.getName().toString());

    methodBean.setParameters(pMethodNode.parameters());

    methodBean.setReturnType(pMethodNode.getReturnType2());

    // Set the textual content
    methodBean.setTextContent(pMethodNode.toString());

    if ((pMethodNode.toString().contains("static "))) {
        methodBean.setStatic(true);
    } else {
        methodBean.setStatic(false);
    }

    // Get the names in the method
    Collection<String> names = new HashSet<>();
    pMethodNode.accept(new NameVisitor(names));

    // Verify the correspondence between names and instance variables 
    Collection<InstanceVariableBean> usedInstanceVariableBeans = getUsedInstanceVariable(names, pClassInstanceVariableBeans);

    // Set the used instance variables
    methodBean.setUsedInstanceVariables(usedInstanceVariableBeans);

    // Get the invocation names
    Collection<String> invocations = new HashSet<>();
    pMethodNode.accept(new InvocationVisitor(invocations));

    // Get the invocation beans from the invocation names
    Collection<MethodBean> invocationBeans = new ArrayList<>();
    for (String invocation : invocations) {
        invocationBeans.add(InvocationParser.parse(invocation));
    }

    // Set the invocations
    methodBean.setMethodCalls(invocationBeans);

    // Return the bean
    return methodBean;

}
 
Example 13
Source File: AstUtils.java    From RefactoringMiner with MIT License 4 votes vote down vote up
public int countStatements(MethodDeclaration methodDeclaration) {
	counter = 0;
	methodDeclaration.accept(this);
	return counter;
}
 
Example 14
Source File: VariableDeclarationFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private boolean canReturn(MethodDeclaration constructor) {
	final ReturnFinder retFinder= new ReturnFinder();
	constructor.accept(retFinder);
	return retFinder.foundOne;
}