Java Code Examples for org.eclipse.jdt.core.dom.AST#newMethodDeclaration()

The following examples show how to use org.eclipse.jdt.core.dom.AST#newMethodDeclaration() . 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: CreateSyncMethodProposal.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected MethodDeclaration createMethodDeclaration(AST ast) {
  MethodDeclaration syncMethodDecl = ast.newMethodDeclaration();

  // New method has same name as original
  String methodName = getAsyncMethodDeclaration().getName().getIdentifier();
  syncMethodDecl.setName(ast.newSimpleName(methodName));

  syncMethodDecl.setReturnType2(Util.computeSyncReturnType(ast,
      getAsyncMethodDeclaration(), getImportRewrite()));

  addSyncParameters(ast, syncMethodDecl);

  // TODO: generate comments for new method

  return syncMethodDecl;
}
 
Example 2
Source File: PushDownRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private MethodDeclaration createNewMethodDeclarationNode(MemberActionInfo info, TypeVariableMaplet[] mapping, CompilationUnitRewrite rewriter, MethodDeclaration oldMethod) throws JavaModelException {
	Assert.isTrue(!info.isFieldInfo());
	IMethod method= (IMethod) info.getMember();
	ASTRewrite rewrite= rewriter.getASTRewrite();
	AST ast= rewrite.getAST();
	MethodDeclaration newMethod= ast.newMethodDeclaration();
	copyBodyOfPushedDownMethod(rewrite, method, oldMethod, newMethod, mapping);
	newMethod.setConstructor(oldMethod.isConstructor());
	copyExtraDimensions(oldMethod, newMethod);
	if (info.copyJavadocToCopiesInSubclasses())
		copyJavadocNode(rewrite, oldMethod, newMethod);
	final IJavaProject project= rewriter.getCu().getJavaProject();
	if (info.isNewMethodToBeDeclaredAbstract() && JavaModelUtil.is50OrHigher(project) && JavaPreferencesSettings.getCodeGenerationSettings(project).overrideAnnotation) {
		final MarkerAnnotation annotation= ast.newMarkerAnnotation();
		annotation.setTypeName(ast.newSimpleName("Override")); //$NON-NLS-1$
		newMethod.modifiers().add(annotation);
	}
	copyAnnotations(oldMethod, newMethod);
	newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, info.getNewModifiersForCopyInSubclass(oldMethod.getModifiers())));
	newMethod.setName(ast.newSimpleName(oldMethod.getName().getIdentifier()));
	copyReturnType(rewrite, method.getCompilationUnit(), oldMethod, newMethod, mapping);
	copyParameters(rewrite, method.getCompilationUnit(), oldMethod, newMethod, mapping);
	copyThrownExceptions(oldMethod, newMethod);
	copyTypeParameters(oldMethod, newMethod);
	return newMethod;
}
 
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: PullUpRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addMethodStubForAbstractMethod(final IMethod sourceMethod, final CompilationUnit declaringCuNode, final AbstractTypeDeclaration typeToCreateStubIn, final ICompilationUnit newCu, final CompilationUnitRewrite rewriter, final Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, final IProgressMonitor monitor, final RefactoringStatus status) throws CoreException {
	final MethodDeclaration methodToCreateStubFor= ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod, declaringCuNode);
	final AST ast= rewriter.getRoot().getAST();
	final MethodDeclaration newMethod= ast.newMethodDeclaration();
	newMethod.setBody(createMethodStub(methodToCreateStubFor, ast));
	newMethod.setConstructor(false);
	copyExtraDimensions(methodToCreateStubFor, newMethod);
	newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getModifiersWithUpdatedVisibility(sourceMethod, JdtFlags.clearFlag(Modifier.NATIVE | Modifier.ABSTRACT, methodToCreateStubFor.getModifiers()), adjustments, new SubProgressMonitor(monitor, 1), false, status)));
	newMethod.setName(((SimpleName) ASTNode.copySubtree(ast, methodToCreateStubFor.getName())));
	final TypeVariableMaplet[] mapping= TypeVariableUtil.composeMappings(TypeVariableUtil.subTypeToSuperType(getDeclaringType(), getDestinationType()), TypeVariableUtil.superTypeToInheritedType(getDestinationType(), ((IType) typeToCreateStubIn.resolveBinding().getJavaElement())));
	copyReturnType(rewriter.getASTRewrite(), getDeclaringType().getCompilationUnit(), methodToCreateStubFor, newMethod, mapping);
	copyParameters(rewriter.getASTRewrite(), getDeclaringType().getCompilationUnit(), methodToCreateStubFor, newMethod, mapping);
	copyThrownExceptions(methodToCreateStubFor, newMethod);
	newMethod.setJavadoc(createJavadocForStub(typeToCreateStubIn.getName().getIdentifier(), methodToCreateStubFor, newMethod, newCu, rewriter.getASTRewrite()));
	ImportRewriteContext context= new ContextSensitiveImportRewriteContext(typeToCreateStubIn, rewriter.getImportRewrite());
	ImportRewriteUtil.addImports(rewriter, context, newMethod, new HashMap<Name, String>(), new HashMap<Name, String>(), false);
	rewriter.getASTRewrite().getListRewrite(typeToCreateStubIn, typeToCreateStubIn.getBodyDeclarationsProperty()).insertAt(newMethod, ASTNodes.getInsertionIndex(newMethod, typeToCreateStubIn.bodyDeclarations()), rewriter.createCategorizedGroupDescription(RefactoringCoreMessages.PullUpRefactoring_add_method_stub, SET_PULL_UP));
}
 
Example 5
Source File: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void addInitializersToConstructors(ASTRewrite rewrite) throws CoreException {
	Assert.isTrue(!isDeclaredInAnonymousClass());
	final AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) getMethodDeclaration().getParent();
	final MethodDeclaration[] constructors = getAllConstructors(declaration);
	if (constructors.length == 0) {
		AST ast = rewrite.getAST();
		MethodDeclaration newConstructor = ast.newMethodDeclaration();
		newConstructor.setConstructor(true);
		newConstructor.modifiers().addAll(ast.newModifiers(declaration.getModifiers() & ModifierRewrite.VISIBILITY_MODIFIERS));
		newConstructor.setName(ast.newSimpleName(declaration.getName().getIdentifier()));
		newConstructor.setBody(ast.newBlock());

		addFieldInitializationToConstructor(rewrite, newConstructor);

		int insertionIndex = computeInsertIndexForNewConstructor(declaration);
		rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertAt(newConstructor, insertionIndex, null);
	} else {
		for (int index = 0; index < constructors.length; index++) {
			if (shouldInsertTempInitialization(constructors[index])) {
				addFieldInitializationToConstructor(rewrite, constructors[index]);
			}
		}
	}
}
 
Example 6
Source File: PrivateConstructorMethodDefinitionCreationFragment.java    From SparkBuilderGenerator with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public MethodDeclaration createPrivateConstructorDefinition(AST ast, TypeDeclaration originalType, TypeDeclaration builderType,
        List<BuilderField> builderFields) {

    MethodDeclaration method = ast.newMethodDeclaration();
    method.setConstructor(true);
    method.setName(ast.newSimpleName(originalType.getName().toString()));
    if (preferencesManager.getPreferenceValue(ADD_GENERATED_ANNOTATION)) {
        generatedAnnotationPopulator.addGeneratedAnnotation(ast, method);
    }
    method.modifiers().add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD));

    SingleVariableDeclaration methodParameterDeclaration = ast.newSingleVariableDeclaration();
    methodParameterDeclaration.setType(ast.newSimpleType(ast.newName(builderType.getName().toString())));
    methodParameterDeclaration.setName(ast.newSimpleName(camelCaseConverter.toLowerCamelCase(builderType.getName().toString())));

    method.parameters().add(methodParameterDeclaration);
    return method;
}
 
Example 7
Source File: PullUpRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private MethodDeclaration createNewMethodDeclarationNode(final CompilationUnitRewrite sourceRewrite, final CompilationUnitRewrite targetRewrite, final IMethod sourceMethod, final MethodDeclaration oldMethod, final TypeVariableMaplet[] mapping, final Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException {
	final ASTRewrite rewrite= targetRewrite.getASTRewrite();
	final AST ast= rewrite.getAST();
	final MethodDeclaration newMethod= ast.newMethodDeclaration();
	if (!getDestinationType().isInterface())
		copyBodyOfPulledUpMethod(sourceRewrite, targetRewrite, sourceMethod, oldMethod, newMethod, mapping, monitor);
	newMethod.setConstructor(oldMethod.isConstructor());
	copyExtraDimensions(oldMethod, newMethod);
	copyJavadocNode(rewrite, oldMethod, newMethod);
	int modifiers= getModifiersWithUpdatedVisibility(sourceMethod, sourceMethod.getFlags(), adjustments, monitor, true, status);
	if (fDeletedMethods.length == 0 || getDestinationType().isInterface()) {
		modifiers&= ~Flags.AccFinal;
	}

	if (oldMethod.isVarargs())
		modifiers&= ~Flags.AccVarargs;
	copyAnnotations(oldMethod, newMethod);
	newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers));
	newMethod.setName(((SimpleName) ASTNode.copySubtree(ast, oldMethod.getName())));
	copyReturnType(rewrite, getDeclaringType().getCompilationUnit(), oldMethod, newMethod, mapping);
	copyParameters(rewrite, getDeclaringType().getCompilationUnit(), oldMethod, newMethod, mapping);
	copyThrownExceptions(oldMethod, newMethod);
	copyTypeParameters(oldMethod, newMethod);
	return newMethod;
}
 
Example 8
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 9
Source File: ClientBundleResource.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public MethodDeclaration createMethodDeclaration(IType clientBundle, ASTRewrite astRewrite,
    ImportRewrite importRewrite, boolean addComments) throws CoreException {
  AST ast = astRewrite.getAST();
  MethodDeclaration methodDecl = ast.newMethodDeclaration();

  // Method is named after the resource it accesses
  methodDecl.setName(ast.newSimpleName(getMethodName()));

  // Method return type is a ResourcePrototype subtype
  ITypeBinding resourceTypeBinding = JavaASTUtils.resolveType(clientBundle.getJavaProject(), getReturnTypeName());
  Type resourceType = importRewrite.addImport(resourceTypeBinding, ast);
  methodDecl.setReturnType2(resourceType);

  // Add @Source annotation if necessary
  String sourceAnnotationValue = getSourceAnnotationValue(clientBundle);
  if (sourceAnnotationValue != null) {
    // Build the annotation
    SingleMemberAnnotation sourceAnnotation = ast.newSingleMemberAnnotation();
    sourceAnnotation.setTypeName(ast.newName("Source"));
    StringLiteral annotationValue = ast.newStringLiteral();
    annotationValue.setLiteralValue(sourceAnnotationValue);
    sourceAnnotation.setValue(annotationValue);

    // Add the annotation to the method
    ChildListPropertyDescriptor modifiers = methodDecl.getModifiersProperty();
    ListRewrite modifiersRewriter = astRewrite.getListRewrite(methodDecl, modifiers);
    modifiersRewriter.insertFirst(sourceAnnotation, null);
  }

  return methodDecl;
}
 
Example 10
Source File: SelfEncapsulateFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private MethodDeclaration createGetterMethod(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(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) {
		body = body.substring(0, body.lastIndexOf(lineDelimiter));
		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 11
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 12
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 13
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 14
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 15
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 16
Source File: AbstractMethodCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private MethodDeclaration getStub(ASTRewrite rewrite, ASTNode targetTypeDecl) throws CoreException {
	AST ast= targetTypeDecl.getAST();
	MethodDeclaration decl= ast.newMethodDeclaration();

	SimpleName newNameNode= getNewName(rewrite);

	decl.setConstructor(isConstructor());

	addNewModifiers(rewrite, targetTypeDecl, decl.modifiers());

	ArrayList<String> takenNames= new ArrayList<String>();
	addNewTypeParameters(rewrite, takenNames, decl.typeParameters());

	decl.setName(newNameNode);

	IVariableBinding[] declaredFields= fSenderBinding.getDeclaredFields();
	for (int i= 0; i < declaredFields.length; i++) { // avoid to take parameter names that are equal to field names
		takenNames.add(declaredFields[i].getName());
	}

	String bodyStatement= ""; //$NON-NLS-1$
	if (!isConstructor()) {
		Type returnType= getNewMethodType(rewrite);
		decl.setReturnType2(returnType);

		boolean isVoid= returnType instanceof PrimitiveType && PrimitiveType.VOID.equals(((PrimitiveType)returnType).getPrimitiveTypeCode());
		if (!fSenderBinding.isInterface() && !isVoid) {
			ReturnStatement returnStatement= ast.newReturnStatement();
			returnStatement.setExpression(ASTNodeFactory.newDefaultExpression(ast, returnType, 0));
			bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true));
		}
	}

	addNewParameters(rewrite, takenNames, decl.parameters());
	addNewExceptions(rewrite, decl.thrownExceptionTypes());

	Block body= null;
	if (!fSenderBinding.isInterface()) {
		body= ast.newBlock();
		String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), fSenderBinding.getName(), newNameNode.getIdentifier(), isConstructor(), bodyStatement, String.valueOf('\n'));
		if (placeHolder != null) {
			ReturnStatement todoNode= (ReturnStatement)rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
			body.statements().add(todoNode);
		}
	}
	decl.setBody(body);

	CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(getCompilationUnit().getJavaProject());
	if (settings.createComments && !fSenderBinding.isAnonymous()) {
		String string= CodeGeneration.getMethodComment(getCompilationUnit(), fSenderBinding.getName(), decl, null, String.valueOf('\n'));
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 17
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, IMethodBinding binding, String type, int modifiers, boolean omitSuperForDefConst, boolean todo, 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(type));
	decl.setConstructor(true);

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

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

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

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

	String delimiter= StubUtility.getLineDelimiterUsed(unit);
	String bodyStatement= ""; //$NON-NLS-1$
	if (!omitSuperForDefConst || !parameters.isEmpty()) {
		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()));
		}
		bodyStatement= ASTNodes.asFormattedString(invocation, 0, delimiter, unit.getJavaProject().getOptions(true));
	}

	if (todo) {
		String placeHolder= CodeGeneration.getMethodBodyContent(unit, type, binding.getName(), true, bodyStatement, delimiter);
		if (placeHolder != null) {
			ReturnStatement todoNode= (ReturnStatement) rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
			body.statements().add(todoNode);
		}
	} else {
		ReturnStatement statementNode= (ReturnStatement) rewrite.createStringPlaceholder(bodyStatement, ASTNode.RETURN_STATEMENT);
		body.statements().add(statementNode);
	}

	if (settings != null && settings.createComments) {
		String string= CodeGeneration.getMethodComment(unit, type, decl, binding, delimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 18
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 19
Source File: SelfEncapsulateFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private MethodDeclaration createSetterMethod(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(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) {
		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 20
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;
		}