Java Code Examples for org.eclipse.jdt.core.dom.ASTNode#METHOD_DECLARATION

The following examples show how to use org.eclipse.jdt.core.dom.ASTNode#METHOD_DECLARATION . 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: ReplaceInvocationsRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static ASTNode checkNode(ASTNode node) {
		if (node == null)
			return null;
		if (node.getNodeType() == ASTNode.SIMPLE_NAME) {
			node= node.getParent();
		} else if (node.getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
			node= ((ExpressionStatement)node).getExpression();
		}
		switch(node.getNodeType()) {
			case ASTNode.METHOD_DECLARATION:
			case ASTNode.METHOD_INVOCATION:
// not yet...
//			case ASTNode.SUPER_METHOD_INVOCATION:
//			case ASTNode.CONSTRUCTOR_INVOCATION:
				return node;
		}
		return null;
	}
 
Example 2
Source File: RefactoringAvailabilityTester.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static boolean isIntroduceIndirectionAvailable(final JavaTextSelection selection) throws JavaModelException {
	final IJavaElement[] elements= selection.resolveElementAtOffset();
	if (elements.length == 1)
		return (elements[0] instanceof IMethod) && isIntroduceIndirectionAvailable(((IMethod) elements[0]));
	ASTNode[] selectedNodes= selection.resolveSelectedNodes();
	if (selectedNodes == null || selectedNodes.length != 1)
		return false;
	switch (selectedNodes[0].getNodeType()) {
		case ASTNode.METHOD_DECLARATION:
		case ASTNode.METHOD_INVOCATION:
		case ASTNode.SUPER_METHOD_INVOCATION:
			return true;
		default:
			return false;
	}
}
 
Example 3
Source File: CallInliner.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void flowAnalysis() {
	fInvocationScope= fRootScope.findScope(fTargetNode.getStartPosition(), fTargetNode.getLength());
	fInvocationScope.setCursor(fTargetNode.getStartPosition());
	fFlowContext= new FlowContext(0, fNumberOfLocals + 1);
	fFlowContext.setConsiderAccessMode(true);
	fFlowContext.setComputeMode(FlowContext.ARGUMENTS);
	Selection selection= Selection.createFromStartLength(fInvocation.getStartPosition(), fInvocation.getLength());
	switch (fBodyDeclaration.getNodeType()) {
		case ASTNode.INITIALIZER:
		case ASTNode.FIELD_DECLARATION:
		case ASTNode.METHOD_DECLARATION:
		case ASTNode.ENUM_CONSTANT_DECLARATION:
			fFlowInfo= new InputFlowAnalyzer(fFlowContext, selection, true).perform(fBodyDeclaration);
			break;
		default:
			Assert.isTrue(false, "Should not happen");			 //$NON-NLS-1$
	}
}
 
Example 4
Source File: TypenameScopeExtractor.java    From tassal with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Multimap<Scope, String> getClassnames(final ASTNode node) {
	final ClassnameFinder cf = new ClassnameFinder(methodsAsRoots);
	node.accept(cf);

	final Multimap<Scope, String> classnames = TreeMultimap.create();

	for (final Entry<ASTNode, String> classname : cf.types.entries()) {
		final ASTNode parentNode = classname.getKey();
		final Scope sc = new Scope(
				classname.getKey().toString(),
				parentNode.getNodeType() == ASTNode.METHOD_DECLARATION ? ScopeType.SCOPE_METHOD
						: ScopeType.SCOPE_CLASS, TYPENAME,
				parentNode.getNodeType(), -1);
		classnames.put(sc, classname.getValue());
	}
	return classnames;
}
 
Example 5
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Finds and returns the <code>ASTNode</code> for the given source text
 * selection, if it is an entire constructor call or the class name portion
 * of a constructor call or constructor declaration, or null otherwise.
 * @param unit The compilation unit in which the selection was made
 * @param offset The textual offset of the start of the selection
 * @param length The length of the selection in characters
 * @return ClassInstanceCreation or MethodDeclaration
 */
private ASTNode getTargetNode(ICompilationUnit unit, int offset, int length) {
	ASTNode node= ASTNodes.getNormalizedNode(NodeFinder.perform(fCU, offset, length));
	if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION)
		return node;
	if (node.getNodeType() == ASTNode.METHOD_DECLARATION && ((MethodDeclaration)node).isConstructor())
		return node;
	// we have some sub node. Make sure its the right child of the parent
	StructuralPropertyDescriptor location= node.getLocationInParent();
	ASTNode parent= node.getParent();
	if (location == ClassInstanceCreation.TYPE_PROPERTY) {
		return parent;
	} else if (location == MethodDeclaration.NAME_PROPERTY && ((MethodDeclaration)parent).isConstructor()) {
		return parent;
	}
	return null;
}
 
Example 6
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static ASTNode checkNode(ASTNode node) {
	if (node == null)
		return null;
	if (node.getNodeType() == ASTNode.SIMPLE_NAME) {
		node= node.getParent();
	} else if (node.getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
		node= ((ExpressionStatement) node).getExpression();
	}
	switch (node.getNodeType()) {
		case ASTNode.METHOD_INVOCATION:
		case ASTNode.METHOD_DECLARATION:
		case ASTNode.SUPER_METHOD_INVOCATION:
			return node;
	}
	return null;
}
 
Example 7
Source File: TypeResolver.java    From KodeBeagle with Apache License 2.0 6 votes vote down vote up
/**
 * Visits {@link SimpleName} AST nodes. Resolves the binding of the simple
 * name and looks for it in the {variableScope} map. If the binding
 * is found, this is a reference to a variable.
 *
 * @param node
 *            the node to visit
 */
@Override
public boolean visit(final SimpleName node) {
	if (node.getParent().getNodeType() == ASTNode.METHOD_INVOCATION) {
		final MethodInvocation invocation = (MethodInvocation) node
				.getParent();
		if (invocation.getName() == node) {
			return true;
		}

       }
       // method declaration can have same name as variable but this does not mean it is binding to that variable
       // added particularly for enum
       if(node.getParent().getNodeType() == ASTNode.METHOD_DECLARATION){
           return true;
	}
	addBindingData(node.getIdentifier(), node, nodeScopes.get(node));
	return true;
}
 
Example 8
Source File: InlineMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates a new inline method refactoring
 * @param unit the compilation unit or class file
 * @param node the compilation unit node
 * @param selectionStart start
 * @param selectionLength length
 * @return returns the refactoring
 */
public static InlineMethodRefactoring create(ITypeRoot unit, CompilationUnit node, int selectionStart, int selectionLength) {
	ASTNode target= RefactoringAvailabilityTester.getInlineableMethodNode(unit, node, selectionStart, selectionLength);
	if (target == null)
		return null;
	if (target.getNodeType() == ASTNode.METHOD_DECLARATION) {

		return new InlineMethodRefactoring(unit, (MethodDeclaration)target, selectionStart, selectionLength);
	} else {
		ICompilationUnit cu= (ICompilationUnit) unit;
		if (target.getNodeType() == ASTNode.METHOD_INVOCATION) {
			return new InlineMethodRefactoring(cu, (MethodInvocation)target, selectionStart, selectionLength);
		} else if (target.getNodeType() == ASTNode.SUPER_METHOD_INVOCATION) {
			return new InlineMethodRefactoring(cu, (SuperMethodInvocation)target, selectionStart, selectionLength);
		} else if (target.getNodeType() == ASTNode.CONSTRUCTOR_INVOCATION) {
			return new InlineMethodRefactoring(cu, (ConstructorInvocation)target, selectionStart, selectionLength);
		}
	}
	return null;
}
 
Example 9
Source File: JavaTextSelection.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public boolean resolveInMethodBody() {
	if (fInMethodBodyRequested)
		return fInMethodBody;
	fInMethodBodyRequested= true;
	resolveSelectedNodes();
	ASTNode node= getStartNode();
	if (node == null) {
		fInMethodBody= true;
	} else {
		while (node != null) {
			int nodeType= node.getNodeType();
			if (nodeType == ASTNode.BLOCK && node.getParent() instanceof BodyDeclaration) {
				fInMethodBody= node.getParent().getNodeType() == ASTNode.METHOD_DECLARATION;
				break;
			} else if (nodeType == ASTNode.ANONYMOUS_CLASS_DECLARATION) {
				fInMethodBody= false;
				break;
			}
			node= node.getParent();
		}
	}
	return fInMethodBody;
}
 
Example 10
Source File: JavaAddElementFromHistoryImpl.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the corresponding place holder type for the given element.
 * @return a place holder type (see ASTRewrite) or -1 if there is no corresponding placeholder
 */
private int getPlaceHolderType(ITypedElement element) {

	if (element instanceof DocumentRangeNode) {
		JavaNode jn= (JavaNode) element;
		switch (jn.getTypeCode()) {

		case JavaNode.PACKAGE:
		    return ASTNode.PACKAGE_DECLARATION;

		case JavaNode.CLASS:
		case JavaNode.INTERFACE:
			return ASTNode.TYPE_DECLARATION;

		case JavaNode.ENUM:
			return ASTNode.ENUM_DECLARATION;

		case JavaNode.ANNOTATION:
			return ASTNode.ANNOTATION_TYPE_DECLARATION;

		case JavaNode.CONSTRUCTOR:
		case JavaNode.METHOD:
			return ASTNode.METHOD_DECLARATION;

		case JavaNode.FIELD:
			return ASTNode.FIELD_DECLARATION;

		case JavaNode.INIT:
			return ASTNode.INITIALIZER;

		case JavaNode.IMPORT:
		case JavaNode.IMPORT_CONTAINER:
			return ASTNode.IMPORT_DECLARATION;

		case JavaNode.CU:
		    return ASTNode.COMPILATION_UNIT;
		}
	}
	return -1;
}
 
Example 11
Source File: VariableScopeExtractor.java    From api-mining with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean visit(final SingleVariableDeclaration node) {
	final ASTNode parent = node.getParent();
	if (parent.getNodeType() == ASTNode.METHOD_DECLARATION) {
		variableScopes.put(parent, new Variable(node.getName()
				.getIdentifier(), node.getType().toString(),
				ScopeType.SCOPE_METHOD));
	} else {
		variableScopes.put(parent, new Variable(node.getName()
				.getIdentifier(), node.getType().toString(),
				ScopeType.SCOPE_LOCAL));
	}
	return false;
}
 
Example 12
Source File: JdtFlags.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isStatic(BodyDeclaration bodyDeclaration) {
	if (isNestedInterfaceOrAnnotation(bodyDeclaration))
		return true;
	int nodeType= bodyDeclaration.getNodeType();
	if (!(nodeType == ASTNode.METHOD_DECLARATION || nodeType == ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION) &&
			isInterfaceOrAnnotationMember(bodyDeclaration))
		return true;
	if (bodyDeclaration instanceof EnumConstantDeclaration)
		return true;
	if (bodyDeclaration instanceof EnumDeclaration && bodyDeclaration.getParent() instanceof AbstractTypeDeclaration)
		return true;
	return Modifier.isStatic(bodyDeclaration.getModifiers());
}
 
Example 13
Source File: LocalVariableIndex.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Computes the maximum number of local variable declarations in the
 * given body declaration.
 *
 * @param declaration the body declaration. Must either be a method
 *  declaration, or an initializer, or a field declaration.
 * @return the maximum number of local variables
 */
public static int perform(BodyDeclaration declaration) {
	Assert.isTrue(declaration != null);
	switch (declaration.getNodeType()) {
		case ASTNode.METHOD_DECLARATION:
		case ASTNode.FIELD_DECLARATION:
		case ASTNode.INITIALIZER:
			return internalPerform(declaration);
		default:
			throw new IllegalArgumentException(declaration.toString());
	}
}
 
Example 14
Source File: JavaMethodClassCounter.java    From codemining-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void postVisit(final ASTNode node) {

	if (node.getNodeType() == ASTNode.METHOD_DECLARATION)
		noMethods++;

	if (node.getNodeType() == ASTNode.TYPE_DECLARATION
			|| node.getNodeType() == ASTNode.ENUM_DECLARATION)
		noClasses++;
}
 
Example 15
Source File: RefactoringAvailabilityTester.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static ASTNode getInlineableMethodNode(ASTNode node, IJavaElement unit) {
	if (node == null) {
		return null;
	}
	switch (node.getNodeType()) {
		case ASTNode.SIMPLE_NAME:
			StructuralPropertyDescriptor locationInParent = node.getLocationInParent();
			if (locationInParent == MethodDeclaration.NAME_PROPERTY) {
				return node.getParent();
			} else if (locationInParent == MethodInvocation.NAME_PROPERTY || locationInParent == SuperMethodInvocation.NAME_PROPERTY) {
				return unit instanceof ICompilationUnit ? node.getParent() : null; // don't start on invocations in binary
			}
			return null;
		case ASTNode.EXPRESSION_STATEMENT:
			node = ((ExpressionStatement) node).getExpression();
	}
	switch (node.getNodeType()) {
		case ASTNode.METHOD_DECLARATION:
			return node;
		case ASTNode.METHOD_INVOCATION:
		case ASTNode.SUPER_METHOD_INVOCATION:
		case ASTNode.CONSTRUCTOR_INVOCATION:
			return unit instanceof ICompilationUnit ? node : null; // don't start on invocations in binary
	}
	return null;
}
 
Example 16
Source File: JavaTextBufferNode.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the corresponding place holder type for the given element.
 * @return a place holder type (see ASTRewrite) or -1 if there is no corresponding placeholder
 */
static final int getPlaceHolderType(ITypedElement element) {

	if (element instanceof DocumentRangeNode) {
		JavaNode jn= (JavaNode) element;
		switch (jn.getTypeCode()) {

		case JavaNode.PACKAGE:
		    return ASTNode.PACKAGE_DECLARATION;

		case JavaNode.CLASS:
		case JavaNode.INTERFACE:
			return ASTNode.TYPE_DECLARATION;

		case JavaNode.ENUM:
			return ASTNode.ENUM_DECLARATION;

		case JavaNode.ANNOTATION:
			return ASTNode.ANNOTATION_TYPE_DECLARATION;

		case JavaNode.CONSTRUCTOR:
		case JavaNode.METHOD:
			return ASTNode.METHOD_DECLARATION;

		case JavaNode.FIELD:
			return ASTNode.FIELD_DECLARATION;

		case JavaNode.INIT:
			return ASTNode.INITIALIZER;

		case JavaNode.IMPORT:
		case JavaNode.IMPORT_CONTAINER:
			return ASTNode.IMPORT_DECLARATION;

		case JavaNode.CU:
		    return ASTNode.COMPILATION_UNIT;
		}
	}
	return -1;
}
 
Example 17
Source File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public boolean mustInnerClassBeStatic() {
    ITypeBinding typeBinding = ((AbstractTypeDeclaration) ASTNodes.getParent(fAnonymousInnerClassNode, AbstractTypeDeclaration.class)).resolveBinding();
    ASTNode current = fAnonymousInnerClassNode.getParent();
    boolean ans = false;
    while(current != null) {
        switch(current.getNodeType()) {
case ASTNode.SUPER_CONSTRUCTOR_INVOCATION:
case ASTNode.CONSTRUCTOR_INVOCATION:
	return true;
case ASTNode.ANONYMOUS_CLASS_DECLARATION:
            {
                AnonymousClassDeclaration enclosingAnonymousClassDeclaration= (AnonymousClassDeclaration)current;
                ITypeBinding binding= enclosingAnonymousClassDeclaration.resolveBinding();
                if (binding != null && Bindings.isSuperType(typeBinding, binding.getSuperclass())) {
                    return false;
                }
                break;
            }
            case ASTNode.FIELD_DECLARATION:
            {
                FieldDeclaration enclosingFieldDeclaration= (FieldDeclaration)current;
                if (Modifier.isStatic(enclosingFieldDeclaration.getModifiers())) {
                    ans = true;
                }
                break;
            }
            case ASTNode.METHOD_DECLARATION:
            {
                MethodDeclaration enclosingMethodDeclaration = (MethodDeclaration)current;
                if (Modifier.isStatic(enclosingMethodDeclaration.getModifiers())) {
                    ans = true;
                }
                break;
            }
            case ASTNode.TYPE_DECLARATION:
            {
                return ans;
            }
        }
        current = current.getParent();
    }
    return ans;
}
 
Example 18
Source File: SuppressWarningsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Adds a SuppressWarnings proposal if possible and returns whether parent nodes should be processed or not (and with what relevance).
 * 
 * @param cu the compilation unit
 * @param node the node on which to add a SuppressWarning token
 * @param warningToken the warning token to add
 * @param relevance the proposal's relevance
 * @param proposals collector to which the proposal should be added
 * @return <code>0</code> if no further proposals should be added to parent nodes, or the relevance of the next proposal
 * 
 * @since 3.6
 */
private static int addSuppressWarningsProposalIfPossible(ICompilationUnit cu, ASTNode node, String warningToken, int relevance, Collection<ICommandAccess> proposals) {

	ChildListPropertyDescriptor property;
	String name;
	boolean isLocalVariable= false;
	switch (node.getNodeType()) {
		case ASTNode.SINGLE_VARIABLE_DECLARATION:
			property= SingleVariableDeclaration.MODIFIERS2_PROPERTY;
			name= ((SingleVariableDeclaration) node).getName().getIdentifier();
			isLocalVariable= true;
			break;
		case ASTNode.VARIABLE_DECLARATION_STATEMENT:
			property= VariableDeclarationStatement.MODIFIERS2_PROPERTY;
			name= getFirstFragmentName(((VariableDeclarationStatement) node).fragments());
			isLocalVariable= true;
			break;
		case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
			property= VariableDeclarationExpression.MODIFIERS2_PROPERTY;
			name= getFirstFragmentName(((VariableDeclarationExpression) node).fragments());
			isLocalVariable= true;
			break;
		case ASTNode.TYPE_DECLARATION:
			property= TypeDeclaration.MODIFIERS2_PROPERTY;
			name= ((TypeDeclaration) node).getName().getIdentifier();
			break;
		case ASTNode.ANNOTATION_TYPE_DECLARATION:
			property= AnnotationTypeDeclaration.MODIFIERS2_PROPERTY;
			name= ((AnnotationTypeDeclaration) node).getName().getIdentifier();
			break;
		case ASTNode.ENUM_DECLARATION:
			property= EnumDeclaration.MODIFIERS2_PROPERTY;
			name= ((EnumDeclaration) node).getName().getIdentifier();
			break;
		case ASTNode.FIELD_DECLARATION:
			property= FieldDeclaration.MODIFIERS2_PROPERTY;
			name= getFirstFragmentName(((FieldDeclaration) node).fragments());
			break;
		// case ASTNode.INITIALIZER: not used, because Initializer cannot have annotations
		case ASTNode.METHOD_DECLARATION:
			property= MethodDeclaration.MODIFIERS2_PROPERTY;
			name= ((MethodDeclaration) node).getName().getIdentifier() + "()"; //$NON-NLS-1$
			break;
		case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION:
			property= AnnotationTypeMemberDeclaration.MODIFIERS2_PROPERTY;
			name= ((AnnotationTypeMemberDeclaration) node).getName().getIdentifier() + "()"; //$NON-NLS-1$
			break;
		case ASTNode.ENUM_CONSTANT_DECLARATION:
			property= EnumConstantDeclaration.MODIFIERS2_PROPERTY;
			name= ((EnumConstantDeclaration) node).getName().getIdentifier();
			break;
		default:
			return relevance;
	}

	String label= Messages.format(CorrectionMessages.SuppressWarningsSubProcessor_suppress_warnings_label, new String[] { warningToken, BasicElementLabels.getJavaElementName(name) });
	ASTRewriteCorrectionProposal proposal= new SuppressWarningsProposal(warningToken, label, cu, node, property, relevance);

	proposals.add(proposal);
	return isLocalVariable ? relevance - 1 : 0;
}
 
Example 19
Source File: ModifierChangeCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected ASTRewrite getRewrite() throws CoreException {
	CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fNode);
	ASTNode boundNode= astRoot.findDeclaringNode(fBinding);
	ASTNode declNode= null;

	if (boundNode != null) {
		declNode= boundNode; // is same CU
	} else {
		//setSelectionDescription(selectionDescription);
		CompilationUnit newRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
		declNode= newRoot.findDeclaringNode(fBinding.getKey());
	}
	if (declNode != null) {
		AST ast= declNode.getAST();
		ASTRewrite rewrite= ASTRewrite.create(ast);

		if (declNode.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
			VariableDeclarationFragment fragment= (VariableDeclarationFragment)declNode;
			ASTNode parent= declNode.getParent();
			if (parent instanceof FieldDeclaration) {
				FieldDeclaration fieldDecl= (FieldDeclaration) parent;
				if (fieldDecl.fragments().size() > 1 && (fieldDecl.getParent() instanceof AbstractTypeDeclaration)) { // split
					VariableDeclarationRewrite.rewriteModifiers(fieldDecl, new VariableDeclarationFragment[] {fragment}, fIncludedModifiers, fExcludedModifiers, rewrite, null);
					return rewrite;
				}
			} else if (parent instanceof VariableDeclarationStatement) {
				VariableDeclarationStatement varDecl= (VariableDeclarationStatement) parent;
				if (varDecl.fragments().size() > 1 && (varDecl.getParent() instanceof Block)) { // split
					VariableDeclarationRewrite.rewriteModifiers(varDecl, new VariableDeclarationFragment[] {fragment}, fIncludedModifiers, fExcludedModifiers, rewrite, null);
					return rewrite;
				}
			} else if (parent instanceof VariableDeclarationExpression) {
				// can't separate
			}
			declNode= parent;
		} else if (declNode.getNodeType() == ASTNode.METHOD_DECLARATION) {
			MethodDeclaration methodDecl= (MethodDeclaration) declNode;
			if (!methodDecl.isConstructor()) {
				IMethodBinding methodBinding= methodDecl.resolveBinding();
				if (methodDecl.getBody() == null && methodBinding != null && Modifier.isAbstract(methodBinding.getModifiers()) && Modifier.isStatic(fIncludedModifiers)) {
					// add body
					ICompilationUnit unit= getCompilationUnit();
					String delimiter= unit.findRecommendedLineSeparator();
					String bodyStatement= ""; //$NON-NLS-1$
					
					Block body= ast.newBlock();
					rewrite.set(methodDecl, MethodDeclaration.BODY_PROPERTY, body, null);
					Type returnType= methodDecl.getReturnType2();
					if (returnType != null) {
						Expression expression= ASTNodeFactory.newDefaultExpression(ast, returnType, methodDecl.getExtraDimensions());
						if (expression != null) {
							ReturnStatement returnStatement= ast.newReturnStatement();
							returnStatement.setExpression(expression);
							bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, delimiter, unit.getJavaProject().getOptions(true));
						}
					}
					String placeHolder= CodeGeneration.getMethodBodyContent(unit, methodBinding.getDeclaringClass().getName(), methodBinding.getName(), false, bodyStatement, delimiter);
					if (placeHolder != null) {
						ReturnStatement todoNode= (ReturnStatement) rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
						body.statements().add(todoNode);
					}
				}
			}
		}
		ModifierRewrite listRewrite= ModifierRewrite.create(rewrite, declNode);
		PositionInformation trackedDeclNode= listRewrite.setModifiers(fIncludedModifiers, fExcludedModifiers, null);
		
		LinkedProposalPositionGroup positionGroup= new LinkedProposalPositionGroup("group"); //$NON-NLS-1$
		positionGroup.addPosition(trackedDeclNode);
		getLinkedProposalModel().addPositionGroup(positionGroup);
		
		if (boundNode != null) {
			// only set end position if in same CU
			setEndPosition(rewrite.track(fNode));
		}
		return rewrite;
	}
	return null;
}
 
Example 20
Source File: ExtractMethodAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void initReturnType(ImportRewrite rewriter) {
	AST ast= fEnclosingBodyDeclaration.getAST();
	fReturnType= null;
	fReturnTypeBinding= null;
	switch (fReturnKind) {
		case ACCESS_TO_LOCAL:
			VariableDeclaration declaration= ASTNodes.findVariableDeclaration(fReturnValue, fEnclosingBodyDeclaration);
			fReturnType= ASTNodeFactory.newType(ast, declaration, rewriter, new ContextSensitiveImportRewriteContext(declaration, rewriter));
			if (declaration.resolveBinding() != null) {
				fReturnTypeBinding= declaration.resolveBinding().getType();
			}
			break;
		case EXPRESSION:
			Expression expression= (Expression)getFirstSelectedNode();
			if (expression.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
				fExpressionBinding= ((ClassInstanceCreation)expression).getType().resolveBinding();
			} else {
				fExpressionBinding= expression.resolveTypeBinding();
			}
			if (fExpressionBinding != null) {
				if (fExpressionBinding.isNullType()) {
					getStatus().addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_null_type, JavaStatusContext.create(fCUnit, expression));
				} else {
					ITypeBinding normalizedBinding= Bindings.normalizeForDeclarationUse(fExpressionBinding, ast);
					if (normalizedBinding != null) {
						ImportRewriteContext context= new ContextSensitiveImportRewriteContext(fEnclosingBodyDeclaration, rewriter);
						fReturnType= rewriter.addImport(normalizedBinding, ast, context);
						fReturnTypeBinding= normalizedBinding;
					}
				}
			} else {
				fReturnType= ast.newPrimitiveType(PrimitiveType.VOID);
				fReturnTypeBinding= ast.resolveWellKnownType("void"); //$NON-NLS-1$
				getStatus().addError(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_determine_return_type, JavaStatusContext.create(fCUnit, expression));
			}
			break;
		case RETURN_STATEMENT_VALUE:
			LambdaExpression enclosingLambdaExpr= ASTResolving.findEnclosingLambdaExpression(getFirstSelectedNode());
			if (enclosingLambdaExpr != null) {
				fReturnType= ASTNodeFactory.newReturnType(enclosingLambdaExpr, ast, rewriter, null);
				IMethodBinding methodBinding= enclosingLambdaExpr.resolveMethodBinding();
				fReturnTypeBinding= methodBinding != null ? methodBinding.getReturnType() : null;
			} else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) {
				fReturnType= ((MethodDeclaration) fEnclosingBodyDeclaration).getReturnType2();
				fReturnTypeBinding= fReturnType != null ? fReturnType.resolveBinding() : null;
			}
			break;
		default:
			fReturnType= ast.newPrimitiveType(PrimitiveType.VOID);
			fReturnTypeBinding= ast.resolveWellKnownType("void"); //$NON-NLS-1$
	}
	if (fReturnType == null) {
		fReturnType= ast.newPrimitiveType(PrimitiveType.VOID);
		fReturnTypeBinding= ast.resolveWellKnownType("void"); //$NON-NLS-1$
	}
}