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

The following examples show how to use org.eclipse.jdt.core.dom.MethodDeclaration#setBody() . 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: GenerateHashCodeEqualsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private MethodDeclaration createGetOuterHelper() {
	String outerTypeName= fType.getDeclaringClass().getTypeDeclaration().getName();

	MethodDeclaration helperMethod= fAst.newMethodDeclaration();
	helperMethod.modifiers().addAll(ASTNodeFactory.newModifiers(fAst, Modifier.PRIVATE));
	helperMethod.setName(fAst.newSimpleName(METHODNAME_OUTER_TYPE));
	helperMethod.setConstructor(false);
	helperMethod.setReturnType2(fAst.newSimpleType(fAst.newSimpleName(outerTypeName)));

	Block body= fAst.newBlock();
	helperMethod.setBody(body);

	ThisExpression thisExpression= fAst.newThisExpression();
	thisExpression.setQualifier(fAst.newSimpleName(outerTypeName));

	ReturnStatement endReturn= fAst.newReturnStatement();
	endReturn.setExpression(thisExpression);
	body.statements().add(endReturn);

	return helperMethod;
}
 
Example 2
Source File: DefaultConstructorAppender.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
private MethodDeclaration createConstructor(CompilationUnitModificationDomain domain) {
    AST ast = domain.getAst();

    Block emptyBody = ast.newBlock();
    MethodDeclaration defaultConstructor = ast.newMethodDeclaration();
    defaultConstructor.setBody(emptyBody);
    defaultConstructor.setConstructor(true);
    defaultConstructor.setName(ast.newSimpleName(domain.getOriginalType().getName().toString()));
    defaultConstructor.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));

    if (preferencesManager.getPreferenceValue(ADD_GENERATED_ANNOTATION)) {
        generatedAnnotationPopulator.addGeneratedAnnotation(ast, defaultConstructor);
    }

    return defaultConstructor;
}
 
Example 3
Source File: CreateDoPrivilegedBlockResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private MethodDeclaration createRunMethodDeclaration(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
    AST ast = rewrite.getAST();

    MethodDeclaration methodDeclaration = ast.newMethodDeclaration();
    SimpleName methodName = ast.newSimpleName("run");
    Type returnType = (Type) rewrite.createCopyTarget(classLoaderCreation.getType());
    Block methodBody = createRunMethodBody(rewrite, classLoaderCreation);
    List<Modifier> modifiers = checkedList(methodDeclaration.modifiers());

    modifiers.add(ast.newModifier(PUBLIC_KEYWORD));
    methodDeclaration.setName(methodName);
    methodDeclaration.setReturnType2(returnType);
    methodDeclaration.setBody(methodBody);

    return methodDeclaration;
}
 
Example 4
Source File: StagedBuilderWithMethodAdderFragment.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public void addWithMethodToBuilder(AST ast, TypeDeclaration stagedBuilderType,
        BuilderField builderField,
        StagedBuilderProperties nextStage) {
    Block newBlock = createWithMethodBody(ast, builderField);
    MethodDeclaration newWithMethod = stagedBuilderWithMethodDefiniationCreatorFragment.createNewWithMethod(ast,
            builderField, nextStage);
    newWithMethod.setBody(newBlock);
    markerAnnotationAttacher.attachAnnotation(ast, newWithMethod, OVERRIDE_ANNOTATION);
    stagedBuilderType.bodyDeclarations().add(newWithMethod);
}
 
Example 5
Source File: ExtractMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the signature of the new method.
 *
 * @param methodName the method name used for the new method
 * @return the signature of the extracted method
 */
public String getSignature(String methodName) {
	MethodDeclaration methodDecl= createNewMethodDeclaration();
	methodDecl.setBody(null);
	String str= ASTNodes.asString(methodDecl);
	return str.substring(0, str.indexOf(';'));
}
 
Example 6
Source File: PrivateConstructorAdderFragment.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public void addEmptyPrivateConstructor(AST ast, TypeDeclaration builderType) {
    MethodDeclaration privateConstructorMethod = ast.newMethodDeclaration();
    privateConstructorMethod.setBody(ast.newBlock());
    privateConstructorMethod.setConstructor(true);
    privateConstructorMethod.setName(ast.newSimpleName(builderType.getName().toString()));
    privateConstructorMethod.modifiers().add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD));
    builderType.bodyDeclarations().add(privateConstructorMethod);
}
 
Example 7
Source File: PublicConstructorWithMandatoryFieldsAdderFragment.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
private MethodDeclaration createPublicConstructor(AST ast, Block body, TypeDeclaration builderType, List<BuilderField> fields) {
    MethodDeclaration publicConstructorMethod = ast.newMethodDeclaration();
    publicConstructorMethod.setBody(body);
    publicConstructorMethod.setConstructor(true);
    publicConstructorMethod.setName(ast.newSimpleName(builderType.getName().toString()));
    publicConstructorMethod.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));

    for (BuilderField field : fields) {
        SingleVariableDeclaration parameter = createParameter(ast, field.getFieldType(), field.getBuilderFieldName());
        publicConstructorMethod.parameters().add(parameter);
    }

    return publicConstructorMethod;

}
 
Example 8
Source File: RegularBuilderCopyInstanceConstructorAdderFragment.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
private MethodDeclaration createCopyConstructorWithBody(AST ast, TypeDeclaration builderType, TypeDeclaration originalType, String parameterName,
        Block body) {
    MethodDeclaration copyConstructor = ast.newMethodDeclaration();
    copyConstructor.setBody(body);
    copyConstructor.setConstructor(true);
    copyConstructor.setName(ast.newSimpleName(builderType.getName().toString()));
    copyConstructor.modifiers().add(ast.newModifier(PRIVATE_KEYWORD));
    copyConstructor.parameters().add(createParameter(ast, originalType, parameterName));
    return copyConstructor;
}
 
Example 9
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private MethodDeclaration createGetter(ParameterInfo pi, String declaringType, CompilationUnitRewrite cuRewrite) throws CoreException {
	AST ast= cuRewrite.getAST();
	ICompilationUnit cu= cuRewrite.getCu();
	IJavaProject project= cu.getJavaProject();

	MethodDeclaration methodDeclaration= ast.newMethodDeclaration();
	String fieldName= pi.getNewName();
	String getterName= getGetterName(pi, ast, project);
	String lineDelim= StubUtility.getLineDelimiterUsed(cu);
	String bareFieldname= NamingConventions.getBaseName(NamingConventions.VK_INSTANCE_FIELD, fieldName, project);
	if (createComments(project)) {
		String comment= CodeGeneration.getGetterComment(cu, declaringType, getterName, fieldName, pi.getNewTypeName(), bareFieldname, lineDelim);
		if (comment != null)
			methodDeclaration.setJavadoc((Javadoc) cuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC));
	}
	methodDeclaration.setName(ast.newSimpleName(getterName));
	methodDeclaration.setReturnType2(importBinding(pi.getNewTypeBinding(), cuRewrite));
	methodDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
	Block block= ast.newBlock();
	methodDeclaration.setBody(block);
	boolean useThis= StubUtility.useThisForFieldAccess(project);
	if (useThis) {
		fieldName= "this." + fieldName; //$NON-NLS-1$
	}
	String bodyContent= CodeGeneration.getGetterMethodBodyContent(cu, declaringType, getterName, fieldName, lineDelim);
	ASTNode getterBody= cuRewrite.getASTRewrite().createStringPlaceholder(bodyContent, ASTNode.EXPRESSION_STATEMENT);
	block.statements().add(getterBody);
	return methodDeclaration;
}
 
Example 10
Source File: ExtractMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private MethodDeclaration createNewMethod(ASTNode[] selectedNodes, String lineDelimiter, TextEditGroup substitute) throws CoreException {
	MethodDeclaration result= createNewMethodDeclaration();
	result.setBody(createMethodBody(selectedNodes, substitute, result.getModifiers()));
	if (fGenerateJavadoc) {
		AbstractTypeDeclaration enclosingType=
			(AbstractTypeDeclaration)ASTNodes.getParent(fAnalyzer.getEnclosingBodyDeclaration(), AbstractTypeDeclaration.class);
		String string= CodeGeneration.getMethodComment(fCUnit, enclosingType.getName().getIdentifier(), result, null, lineDelimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc)fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
			result.setJavadoc(javadoc);
		}
	}
	return result;
}
 
Example 11
Source File: SelfEncapsulateFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private MethodDeclaration createGetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
	FieldDeclaration field= (FieldDeclaration)ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
	Type type= field.getType();
	MethodDeclaration result= ast.newMethodDeclaration();
	result.setName(ast.newSimpleName(fGetterName));
	result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
	Type returnType= DimensionRewrite.copyTypeAndAddDimensions(type, fFieldDeclaration.extraDimensions(), rewriter);
	result.setReturnType2(returnType);

	Block block= ast.newBlock();
	result.setBody(block);

	String body= CodeGeneration.getGetterMethodBodyContent(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), lineDelimiter);
	if (body != null) {
		ASTNode getterNode= rewriter.createStringPlaceholder(body, ASTNode.BLOCK);
    	block.statements().add(getterNode);
	} else {
		ReturnStatement rs= ast.newReturnStatement();
		rs.setExpression(ast.newSimpleName(fField.getElementName()));
		block.statements().add(rs);
	}
    if (fGenerateJavadoc) {
		String string= CodeGeneration.getGetterComment(
			fField.getCompilationUnit() , getTypeName(field.getParent()), fGetterName,
			fField.getElementName(), ASTNodes.asString(type),
			StubUtility.getBaseName(fField),
			lineDelimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc)fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
			result.setJavadoc(javadoc);
		}
	}
	return result;
}
 
Example 12
Source File: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void addFieldInitializationToConstructor(ASTRewrite rewrite, MethodDeclaration constructor) throws JavaModelException {
	if (constructor.getBody() == null) {
		constructor.setBody(fCURewrite.getAST().newBlock());
	}

	Statement newStatement = createNewAssignmentStatement();
	rewrite.getListRewrite(constructor.getBody(), Block.STATEMENTS_PROPERTY).insertLast(newStatement, null);
}
 
Example 13
Source File: ConstructorFromSuperclassProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private MethodDeclaration createNewMethodDeclaration(AST ast, IMethodBinding binding, ASTRewrite rewrite, ImportRewriteContext importRewriteContext, CodeGenerationSettings commentSettings) throws CoreException {
	String name= fTypeNode.getName().getIdentifier();
	MethodDeclaration decl= ast.newMethodDeclaration();
	decl.setConstructor(true);
	decl.setName(ast.newSimpleName(name));
	Block body= ast.newBlock();
	decl.setBody(body);

	SuperConstructorInvocation invocation= null;

	List<SingleVariableDeclaration> parameters= decl.parameters();
	String[] paramNames= getArgumentNames(binding);

	ITypeBinding enclosingInstance= getEnclosingInstance();
	if (enclosingInstance != null) {
		invocation= addEnclosingInstanceAccess(rewrite, importRewriteContext, parameters, paramNames, enclosingInstance);
	}

	if (binding == null) {
		decl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
	} else {
		decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, binding.getModifiers()));

		ITypeBinding[] params= binding.getParameterTypes();
		for (int i= 0; i < params.length; i++) {
			SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
			var.setType(getImportRewrite().addImport(params[i], ast, importRewriteContext, TypeLocation.LOCAL_VARIABLE));
			var.setName(ast.newSimpleName(paramNames[i]));
			parameters.add(var);
		}

		List<Type> thrownExceptions= decl.thrownExceptionTypes();
		ITypeBinding[] excTypes= binding.getExceptionTypes();
		for (int i= 0; i < excTypes.length; i++) {
			Type excType= getImportRewrite().addImport(excTypes[i], ast, importRewriteContext, TypeLocation.EXCEPTION);
			thrownExceptions.add(excType);
		}

		if (invocation == null) {
			invocation= ast.newSuperConstructorInvocation();
		}

		List<Expression> arguments= invocation.arguments();
		for (int i= 0; i < paramNames.length; i++) {
			Name argument= ast.newSimpleName(paramNames[i]);
			arguments.add(argument);
			addLinkedPosition(rewrite.track(argument), false, "arg_name_" + paramNames[i]); //$NON-NLS-1$
		}
	}

	String bodyStatement = (invocation == null) ? "" : ASTNodes.asFormattedString(invocation, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true)); //$NON-NLS-1$
	String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), name, name, true, bodyStatement, String.valueOf('\n'));
	if (placeHolder != null) {
		ASTNode todoNode= rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
		body.statements().add(todoNode);
	}
	if (commentSettings != null) {
		String string= CodeGeneration.getMethodComment(getCompilationUnit(), name, decl, null, String.valueOf('\n'));
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 14
Source File: Purification.java    From SimFix with GNU General Public License v2.0 4 votes vote down vote up
public boolean visit(MethodDeclaration node){
			if(node.getName().getFullyQualifiedName().equals(_methodName)){
				ASTNode parent = node.getParent();
				while(parent != null){
					if(parent instanceof TypeDeclaration){
						break;
					}
					parent = parent.getParent();
				}
				if(parent == null){
					return false;
				}
				TypeDeclaration typeDeclaration = (TypeDeclaration) parent;
				Set<Integer> assertLines = analysis(node);
				if(assertLines.size() <= 1){
					_purifiedTestCases.add(_clazz + "::" + _methodName);
				} else {
					int methodID = 1;
					for(Integer line : assertLines){
						AST ast = AST.newAST(AST.JLS8);
						MethodDeclaration newMethod = ast.newMethodDeclaration();
						String newName = _methodName + "_purify_" + methodID;
						methodID ++;
						newMethod.setName(ast.newSimpleName(newName));
						newMethod.modifiers().addAll(ASTNode.copySubtrees(ast, node.modifiers()));
						if(node.thrownExceptionTypes().size() > 0){
							newMethod.thrownExceptionTypes().addAll(ASTNode.copySubtrees(ast, node.thrownExceptionTypes()));
						}
						newMethod.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
						List<ASTNode> result = new ArrayList<>();
						for(int i = 0; i < line; i++){
							if(assertLines.contains(i)){
								continue;
							}
							result.add((ASTNode) node.getBody().statements().get(i));
						}
						result.add((ASTNode) node.getBody().statements().get(line));
						// cannot simply remove duplicate assignment since it may cause side-effect
//						result = simplify(result);
						Block body = ast.newBlock();
						for(ASTNode astNode : result){
							body.statements().add(ASTNode.copySubtree(ast, astNode));
						}
						newMethod.setBody(body);
						typeDeclaration.bodyDeclarations().add(ASTNode.copySubtree(node.getAST(), newMethod));
						_purifiedTestCases.add(_clazz + "::" + newName);
					}
					node.getBody().statements().clear();
				}
				return false;
			}
			return true;
		}
 
Example 15
Source File: SelfEncapsulateFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private MethodDeclaration createSetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
	FieldDeclaration field = ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
	Type type = field.getType();
	MethodDeclaration result = ast.newMethodDeclaration();
	result.setName(ast.newSimpleName(fSetterName));
	result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
	if (fSetterMustReturnValue) {
		result.setReturnType2((Type) rewriter.createCopyTarget(type));
	}
	SingleVariableDeclaration param = ast.newSingleVariableDeclaration();
	result.parameters().add(param);
	param.setName(ast.newSimpleName(fArgName));
	param.setType((Type) rewriter.createCopyTarget(type));
	List<Dimension> extraDimensions = DimensionRewrite.copyDimensions(fFieldDeclaration.extraDimensions(), rewriter);
	param.extraDimensions().addAll(extraDimensions);

	Block block = ast.newBlock();
	result.setBody(block);

	String fieldAccess = createFieldAccess();
	String body = CodeGeneration.getSetterMethodBodyContent(fField.getCompilationUnit(), getTypeName(field.getParent()), fSetterName, fieldAccess, fArgName, lineDelimiter);
	if (body != null) {
		body = body.substring(0, body.lastIndexOf(lineDelimiter));
		ASTNode setterNode = rewriter.createStringPlaceholder(body, ASTNode.BLOCK);
		block.statements().add(setterNode);
	} else {
		Assignment ass = ast.newAssignment();
		ass.setLeftHandSide((Expression) rewriter.createStringPlaceholder(fieldAccess, ASTNode.QUALIFIED_NAME));
		ass.setRightHandSide(ast.newSimpleName(fArgName));
		block.statements().add(ass);
	}
	if (fSetterMustReturnValue) {
		ReturnStatement rs = ast.newReturnStatement();
		rs.setExpression(ast.newSimpleName(fArgName));
		block.statements().add(rs);
	}
	if (fGenerateJavadoc) {
		String string = CodeGeneration.getSetterComment(fField.getCompilationUnit(), getTypeName(field.getParent()), fSetterName, fField.getElementName(), ASTNodes.asString(type), fArgName, StubUtility.getBaseName(fField),
				lineDelimiter);
		if (string != null) {
			Javadoc javadoc = (Javadoc) fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
			result.setJavadoc(javadoc);
		}
	}
	return result;
}
 
Example 16
Source File: StubUtility2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static MethodDeclaration createConstructorStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, ITypeBinding typeBinding, IMethodBinding superConstructor, IVariableBinding[] variableBindings, int modifiers, CodeGenerationSettings settings) throws CoreException {
	AST ast= rewrite.getAST();

	MethodDeclaration decl= ast.newMethodDeclaration();
	decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers & ~Modifier.ABSTRACT & ~Modifier.NATIVE));
	decl.setName(ast.newSimpleName(typeBinding.getName()));
	decl.setConstructor(true);

	List<SingleVariableDeclaration> parameters= decl.parameters();
	if (superConstructor != null) {
		createTypeParameters(imports, context, ast, superConstructor, decl);

		createParameters(unit.getJavaProject(), imports, context, ast, superConstructor, null, decl);

		createThrownExceptions(decl, superConstructor, imports, context, ast);
	}

	Block body= ast.newBlock();
	decl.setBody(body);

	String delimiter= StubUtility.getLineDelimiterUsed(unit);

	if (superConstructor != null) {
		SuperConstructorInvocation invocation= ast.newSuperConstructorInvocation();
		SingleVariableDeclaration varDecl= null;
		for (Iterator<SingleVariableDeclaration> iterator= parameters.iterator(); iterator.hasNext();) {
			varDecl= iterator.next();
			invocation.arguments().add(ast.newSimpleName(varDecl.getName().getIdentifier()));
		}
		body.statements().add(invocation);
	}

	List<String> prohibited= new ArrayList<String>();
	for (final Iterator<SingleVariableDeclaration> iterator= parameters.iterator(); iterator.hasNext();)
		prohibited.add(iterator.next().getName().getIdentifier());
	String param= null;
	List<String> list= new ArrayList<String>(prohibited);
	String[] excluded= null;
	for (int i= 0; i < variableBindings.length; i++) {
		SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
		var.setType(imports.addImport(variableBindings[i].getType(), ast, context));
		excluded= new String[list.size()];
		list.toArray(excluded);
		param= suggestParameterName(unit, variableBindings[i], excluded);
		list.add(param);
		var.setName(ast.newSimpleName(param));
		parameters.add(var);
	}

	list= new ArrayList<String>(prohibited);
	for (int i= 0; i < variableBindings.length; i++) {
		excluded= new String[list.size()];
		list.toArray(excluded);
		final String paramName= suggestParameterName(unit, variableBindings[i], excluded);
		list.add(paramName);
		final String fieldName= variableBindings[i].getName();
		Expression expression= null;
		if (paramName.equals(fieldName) || settings.useKeywordThis) {
			FieldAccess access= ast.newFieldAccess();
			access.setExpression(ast.newThisExpression());
			access.setName(ast.newSimpleName(fieldName));
			expression= access;
		} else
			expression= ast.newSimpleName(fieldName);
		Assignment assignment= ast.newAssignment();
		assignment.setLeftHandSide(expression);
		assignment.setRightHandSide(ast.newSimpleName(paramName));
		assignment.setOperator(Assignment.Operator.ASSIGN);
		body.statements().add(ast.newExpressionStatement(assignment));
	}

	if (settings != null && settings.createComments) {
		String string= CodeGeneration.getMethodComment(unit, typeBinding.getName(), decl, superConstructor, delimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 17
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates and returns a new MethodDeclaration that represents the factory method to be used in
 * place of direct calls to the constructor in question.
 * 
 * @param ast An AST used as a factory for various AST nodes
 * @param ctorBinding binding for the constructor being wrapped
 * @param unitRewriter the ASTRewrite to be used
 * @return the new method declaration
 * @throws CoreException if an exception occurs while accessing its corresponding resource
 */
private MethodDeclaration createFactoryMethod(AST ast, IMethodBinding ctorBinding, ASTRewrite unitRewriter) throws CoreException{
	MethodDeclaration		newMethod= ast.newMethodDeclaration();
	SimpleName				newMethodName= ast.newSimpleName(fNewMethodName);
	ClassInstanceCreation	newCtorCall= ast.newClassInstanceCreation();
	ReturnStatement			ret= ast.newReturnStatement();
	Block		body= ast.newBlock();
	List<Statement>		stmts= body.statements();
	String		retTypeName= ctorBinding.getName();

	createFactoryMethodSignature(ast, newMethod);

	newMethod.setName(newMethodName);
	newMethod.setBody(body);

	ITypeBinding declaringClass= fCtorBinding.getDeclaringClass();
	ITypeBinding[] ctorOwnerTypeParameters= declaringClass.getTypeParameters();

	setMethodReturnType(newMethod, retTypeName, ctorOwnerTypeParameters, ast);

	newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.STATIC | Modifier.PUBLIC));

	setCtorTypeArguments(newCtorCall, retTypeName, ctorOwnerTypeParameters, ast);

	createFactoryMethodConstructorArgs(ast, newCtorCall);

	if (Modifier.isAbstract(declaringClass.getModifiers())) {
		AnonymousClassDeclaration decl= ast.newAnonymousClassDeclaration();
		IMethodBinding[] unimplementedMethods= getUnimplementedMethods(declaringClass);
		CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(fCUHandle.getJavaProject());
		ImportRewriteContext context= new ContextSensitiveImportRewriteContext(fFactoryCU, decl.getStartPosition(), fImportRewriter);
		for (int i= 0; i < unimplementedMethods.length; i++) {
			IMethodBinding unImplementedMethod= unimplementedMethods[i];
			MethodDeclaration newMethodDecl= StubUtility2.createImplementationStub(fCUHandle, unitRewriter, fImportRewriter, context, unImplementedMethod, unImplementedMethod.getDeclaringClass()
					.getName(), settings, false);
			decl.bodyDeclarations().add(newMethodDecl);
		}
		newCtorCall.setAnonymousClassDeclaration(decl);
	}

	ret.setExpression(newCtorCall);
	stmts.add(ret);

	return newMethod;
}
 
Example 18
Source File: StubUtility2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static MethodDeclaration createDelegationStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, IMethodBinding delegate, IVariableBinding delegatingField, CodeGenerationSettings settings) throws CoreException {
	Assert.isNotNull(delegate);
	Assert.isNotNull(delegatingField);
	Assert.isNotNull(settings);

	AST ast= rewrite.getAST();

	MethodDeclaration decl= ast.newMethodDeclaration();
	decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, delegate.getModifiers() & ~Modifier.SYNCHRONIZED & ~Modifier.ABSTRACT & ~Modifier.NATIVE));

	decl.setName(ast.newSimpleName(delegate.getName()));
	decl.setConstructor(false);

	createTypeParameters(imports, context, ast, delegate, decl);

	decl.setReturnType2(imports.addImport(delegate.getReturnType(), ast, context));

	List<SingleVariableDeclaration> params= createParameters(unit.getJavaProject(), imports, context, ast, delegate, null, decl);

	createThrownExceptions(decl, delegate, imports, context, ast);

	Block body= ast.newBlock();
	decl.setBody(body);

	String delimiter= StubUtility.getLineDelimiterUsed(unit);

	Statement statement= null;
	MethodInvocation invocation= ast.newMethodInvocation();
	invocation.setName(ast.newSimpleName(delegate.getName()));
	List<Expression> arguments= invocation.arguments();
	for (int i= 0; i < params.size(); i++)
		arguments.add(ast.newSimpleName(params.get(i).getName().getIdentifier()));
	if (settings.useKeywordThis) {
		FieldAccess access= ast.newFieldAccess();
		access.setExpression(ast.newThisExpression());
		access.setName(ast.newSimpleName(delegatingField.getName()));
		invocation.setExpression(access);
	} else
		invocation.setExpression(ast.newSimpleName(delegatingField.getName()));
	if (delegate.getReturnType().isPrimitive() && delegate.getReturnType().getName().equals("void")) {//$NON-NLS-1$
		statement= ast.newExpressionStatement(invocation);
	} else {
		ReturnStatement returnStatement= ast.newReturnStatement();
		returnStatement.setExpression(invocation);
		statement= returnStatement;
	}
	body.statements().add(statement);

	ITypeBinding declaringType= delegatingField.getDeclaringClass();
	if (declaringType == null) { // can be null for
		return decl;
	}

	String qualifiedName= declaringType.getQualifiedName();
	IPackageBinding packageBinding= declaringType.getPackage();
	if (packageBinding != null) {
		if (packageBinding.getName().length() > 0 && qualifiedName.startsWith(packageBinding.getName()))
			qualifiedName= qualifiedName.substring(packageBinding.getName().length());
	}

	if (settings.createComments) {
		/*
		 * TODO: have API for delegate method comments This is an inlined
		 * version of
		 * {@link CodeGeneration#getMethodComment(ICompilationUnit, String, MethodDeclaration, IMethodBinding, String)}
		 */
		delegate= delegate.getMethodDeclaration();
		String declaringClassQualifiedName= delegate.getDeclaringClass().getQualifiedName();
		String linkToMethodName= delegate.getName();
		String[] parameterTypesQualifiedNames= StubUtility.getParameterTypeNamesForSeeTag(delegate);
		String string= StubUtility.getMethodComment(unit, qualifiedName, decl, delegate.isDeprecated(), linkToMethodName, declaringClassQualifiedName, parameterTypesQualifiedNames, true, delimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 19
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void createIntermediaryMethod() throws CoreException {

		CompilationUnitRewrite imRewrite= getCachedCURewrite(fIntermediaryType.getCompilationUnit());
		AST ast= imRewrite.getAST();
		MethodDeclaration intermediary= ast.newMethodDeclaration();

		// Intermediary class is non-anonymous
		AbstractTypeDeclaration type= (AbstractTypeDeclaration)typeToDeclaration(fIntermediaryType, imRewrite.getRoot());

		// Name
		intermediary.setName(ast.newSimpleName(fIntermediaryMethodName));

		// Flags
		List<IExtendedModifier> modifiers= intermediary.modifiers();
		if (!fIntermediaryType.isInterface()) {
			modifiers.add(imRewrite.getAST().newModifier(ModifierKeyword.PUBLIC_KEYWORD));
		}
		modifiers.add(imRewrite.getAST().newModifier(ModifierKeyword.STATIC_KEYWORD));

		// Parameters
		String targetParameterName= StubUtility.suggestArgumentName(getProject(), fIntermediaryFirstParameterType.getName(), fTargetMethod.getParameterNames());

		ImportRewriteContext context= new ContextSensitiveImportRewriteContext(type, imRewrite.getImportRewrite());
		if (!isStaticTarget()) {
			// Add first param
			SingleVariableDeclaration parameter= imRewrite.getAST().newSingleVariableDeclaration();
			Type t= imRewrite.getImportRewrite().addImport(fIntermediaryFirstParameterType, imRewrite.getAST(), context);
			if (fIntermediaryFirstParameterType.isGenericType()) {
				ParameterizedType parameterized= imRewrite.getAST().newParameterizedType(t);
				ITypeBinding[] typeParameters= fIntermediaryFirstParameterType.getTypeParameters();
				for (int i= 0; i < typeParameters.length; i++)
					parameterized.typeArguments().add(imRewrite.getImportRewrite().addImport(typeParameters[i], imRewrite.getAST()));
				t= parameterized;
			}
			parameter.setType(t);
			parameter.setName(imRewrite.getAST().newSimpleName(targetParameterName));
			intermediary.parameters().add(parameter);
		}
		// Add other params
		copyArguments(intermediary, imRewrite);

		// Add type parameters of declaring type (and enclosing types)
		if (!isStaticTarget() && fIntermediaryFirstParameterType.isGenericType())
			addTypeParameters(imRewrite, intermediary.typeParameters(), fIntermediaryFirstParameterType);

		// Add type params of method
		copyTypeParameters(intermediary, imRewrite);

		// Return type
		intermediary.setReturnType2(imRewrite.getImportRewrite().addImport(fTargetMethodBinding.getReturnType(), ast, context));

		// Exceptions
		copyExceptions(intermediary, imRewrite);

		// Body
		MethodInvocation invocation= imRewrite.getAST().newMethodInvocation();
		invocation.setName(imRewrite.getAST().newSimpleName(fTargetMethod.getElementName()));
		if (isStaticTarget()) {
			Type importedType= imRewrite.getImportRewrite().addImport(fTargetMethodBinding.getDeclaringClass(), ast, context);
			invocation.setExpression(ASTNodeFactory.newName(ast, ASTNodes.asString(importedType)));
		} else {
			invocation.setExpression(imRewrite.getAST().newSimpleName(targetParameterName));
		}
		copyInvocationParameters(invocation, ast);
		Statement call= encapsulateInvocation(intermediary, invocation);

		final Block body= imRewrite.getAST().newBlock();
		body.statements().add(call);
		intermediary.setBody(body);

		// method comment
		ICompilationUnit targetCU= imRewrite.getCu();
		if (StubUtility.doAddComments(targetCU.getJavaProject())) {
			String comment= CodeGeneration.getMethodComment(targetCU, getIntermediaryTypeName(), intermediary, null, StubUtility.getLineDelimiterUsed(targetCU));
			if (comment != null) {
				Javadoc javadoc= (Javadoc) imRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC);
				intermediary.setJavadoc(javadoc);
			}
		}

		// Add the completed method to the intermediary type:
		ChildListPropertyDescriptor typeBodyDeclarationsProperty= typeToBodyDeclarationProperty(fIntermediaryType, imRewrite.getRoot());

		ListRewrite bodyDeclarationsListRewrite= imRewrite.getASTRewrite().getListRewrite(type, typeBodyDeclarationsProperty);
		bodyDeclarationsListRewrite.insertAt(intermediary, ASTNodes.getInsertionIndex(intermediary, type.bodyDeclarations()), imRewrite
				.createGroupDescription(RefactoringCoreMessages.IntroduceIndirectionRefactoring_group_description_create_new_method));
	}
 
Example 20
Source File: RegularBuilderBuilderMethodCreator.java    From SparkBuilderGenerator with MIT License 4 votes vote down vote up
private void addBuilderMethod(AST ast, ListRewrite listRewrite, TypeDeclaration typeDeclaration, TypeDeclaration builderType) {
    Block builderMethodBlock = blockWithNewBuilderCreationFragment.createReturnBlock(ast, builderType);
    MethodDeclaration builderMethod = builderMethodDefinitionCreatorFragment.createBuilderMethod(ast, typeDeclaration, builderType.getName().toString());
    builderMethod.setBody(builderMethodBlock);
    listRewrite.insertLast(builderMethod, null);
}