Java Code Examples for org.eclipse.jdt.core.dom.SingleVariableDeclaration#setName()

The following examples show how to use org.eclipse.jdt.core.dom.SingleVariableDeclaration#setName() . 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: ConstructorFromSuperclassProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private SuperConstructorInvocation addEnclosingInstanceAccess(ASTRewrite rewrite, ImportRewriteContext importRewriteContext, List<SingleVariableDeclaration> parameters, String[] paramNames, ITypeBinding enclosingInstance) {
	AST ast= rewrite.getAST();
	SuperConstructorInvocation invocation= ast.newSuperConstructorInvocation();

	SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
	var.setType(getImportRewrite().addImport(enclosingInstance, ast, importRewriteContext));
	String[] enclosingArgNames= StubUtility.getArgumentNameSuggestions(getCompilationUnit().getJavaProject(), enclosingInstance.getTypeDeclaration().getName(), 0, paramNames);
	String firstName= enclosingArgNames[0];
	var.setName(ast.newSimpleName(firstName));
	parameters.add(var);

	Name enclosing= ast.newSimpleName(firstName);
	invocation.setExpression(enclosing);

	String key= "arg_name_" + firstName; //$NON-NLS-1$
	addLinkedPosition(rewrite.track(enclosing), false, key);
	for (int i= 0; i < enclosingArgNames.length; i++) {
		addLinkedPositionProposal(key, enclosingArgNames[i], null); // alternative names
	}
	return invocation;
}
 
Example 2
Source File: IntroduceIndirectionRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void copyArguments(MethodDeclaration intermediary, CompilationUnitRewrite rew) throws JavaModelException {
	String[] names= fTargetMethod.getParameterNames();
	ITypeBinding[] types= fTargetMethodBinding.getParameterTypes();
	for (int i= 0; i < names.length; i++) {
		ITypeBinding typeBinding= types[i];
		SingleVariableDeclaration newElement= rew.getAST().newSingleVariableDeclaration();
		newElement.setName(rew.getAST().newSimpleName(names[i]));

		if (i == (names.length - 1) && fTargetMethodBinding.isVarargs()) {
			newElement.setVarargs(true);
			if (typeBinding.isArray())
				typeBinding= typeBinding.getComponentType();
		}

		newElement.setType(rew.getImportRewrite().addImport(typeBinding, rew.getAST()));
		intermediary.parameters().add(newElement);
	}
}
 
Example 3
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 4
Source File: ConstructorFromSuperclassProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private SuperConstructorInvocation addEnclosingInstanceAccess(ASTRewrite rewrite, ImportRewriteContext importRewriteContext, List<SingleVariableDeclaration> parameters, String[] paramNames, ITypeBinding enclosingInstance) {
	AST ast= rewrite.getAST();
	SuperConstructorInvocation invocation= ast.newSuperConstructorInvocation();

	SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
	var.setType(getImportRewrite().addImport(enclosingInstance, ast, importRewriteContext, TypeLocation.PARAMETER));
	String[] enclosingArgNames= StubUtility.getArgumentNameSuggestions(getCompilationUnit().getJavaProject(), enclosingInstance.getTypeDeclaration().getName(), 0, paramNames);
	String firstName= enclosingArgNames[0];
	var.setName(ast.newSimpleName(firstName));
	parameters.add(var);

	Name enclosing= ast.newSimpleName(firstName);
	invocation.setExpression(enclosing);

	String key= "arg_name_" + firstName; //$NON-NLS-1$
	addLinkedPosition(rewrite.track(enclosing), false, key);
	for (int i= 0; i < enclosingArgNames.length; i++) {
		addLinkedPositionProposal(key, enclosingArgNames[i]); // alternative names
	}
	return invocation;
}
 
Example 5
Source File: WithMethodParameterCreatorFragment.java    From SparkBuilderGenerator with MIT License 5 votes vote down vote up
public SingleVariableDeclaration createWithMethodParameter(AST ast, Type type, String fieldName) {
    SingleVariableDeclaration methodParameterDeclaration = ast.newSingleVariableDeclaration();
    methodParameterDeclaration.setType((Type) ASTNode.copySubtree(ast, type));
    methodParameterDeclaration.setName(ast.newSimpleName(fieldName));
    if (preferencesManager.getPreferenceValue(PluginPreferenceList.ADD_NONNULL_ON_PARAMETERS)) {
        markerAnnotationAttacher.attachNonNull(ast, methodParameterDeclaration);
    }
    return methodParameterDeclaration;
}
 
Example 6
Source File: NewDefiningMethodProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params) throws CoreException {
	AST ast= rewrite.getAST();
	ImportRewrite importRewrite= getImportRewrite();
	ITypeBinding[] bindings= fMethod.getParameterTypes();

	IJavaProject project= getCompilationUnit().getJavaProject();
	String[][] paramNames= StubUtility.suggestArgumentNamesWithProposals(project, fParamNames);

	for (int i= 0; i < bindings.length; i++) {
		ITypeBinding curr= bindings[i];

		String[] proposedNames= paramNames[i];

		SingleVariableDeclaration newParam= ast.newSingleVariableDeclaration();

		newParam.setType(importRewrite.addImport(curr, ast));
		newParam.setName(ast.newSimpleName(proposedNames[0]));

		params.add(newParam);

		String groupId= "arg_name_" + i; //$NON-NLS-1$
		addLinkedPosition(rewrite.track(newParam.getName()), false, groupId);

		for (int k= 0; k < proposedNames.length; k++) {
			addLinkedPositionProposal(groupId, proposedNames[k], null);
		}
	}
}
 
Example 7
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private MethodDeclaration createSetter(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 setterName= getSetterName(pi, ast, project);
	String lineDelim= StubUtility.getLineDelimiterUsed(cu);
	String bareFieldname= NamingConventions.getBaseName(NamingConventions.VK_INSTANCE_FIELD, fieldName, project);
	String paramName= StubUtility.suggestArgumentName(project, bareFieldname, null);
	if (createComments(project)) {
		String comment= CodeGeneration.getSetterComment(cu, declaringType, setterName, fieldName, pi.getNewTypeName(), paramName, bareFieldname, lineDelim);
		if (comment != null)
			methodDeclaration.setJavadoc((Javadoc) cuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC));
	}
	methodDeclaration.setName(ast.newSimpleName(setterName));
	methodDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
	SingleVariableDeclaration variable= ast.newSingleVariableDeclaration();
	variable.setType(importBinding(pi.getNewTypeBinding(), cuRewrite));
	variable.setName(ast.newSimpleName(paramName));
	methodDeclaration.parameters().add(variable);
	Block block= ast.newBlock();
	methodDeclaration.setBody(block);
	boolean useThis= StubUtility.useThisForFieldAccess(project);
	if (useThis || fieldName.equals(paramName)) {
		fieldName= "this." + fieldName; //$NON-NLS-1$
	}
	String bodyContent= CodeGeneration.getSetterMethodBodyContent(cu, declaringType, setterName, fieldName, paramName, lineDelim);
	ASTNode setterBody= cuRewrite.getASTRewrite().createStringPlaceholder(bodyContent, ASTNode.EXPRESSION_STATEMENT);
	block.statements().add(setterBody);
	return methodDeclaration;
}
 
Example 8
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates and adds the necessary argument declarations to the given factory method.<br>
 * An argument is needed for each original constructor argument for which the
 * evaluation of the actual arguments across all calls was not able to be
 * pushed inside the factory method (e.g. arguments with side-effects, references
 * to fields if the factory method is to be static or reside in a factory class,
 * or arguments that varied across the set of constructor calls).<br>
 * <code>fArgTypes</code> identifies such arguments by a <code>null</code> value.
 * @param ast utility object used to create AST nodes
 * @param newMethod the <code>MethodDeclaration</code> for the factory method
 */
private void createFactoryMethodSignature(AST ast, MethodDeclaration newMethod) {
	List<SingleVariableDeclaration> argDecls= newMethod.parameters();

	for(int i=0; i < fArgTypes.length; i++) {
		SingleVariableDeclaration argDecl= ast.newSingleVariableDeclaration();
		Type argType;

		if (i == (fArgTypes.length - 1) && fCtorIsVarArgs) {
			// The trailing varargs arg has an extra array dimension, compared to
			// what we need to pass to setType()...
			argType= typeNodeForTypeBinding(fArgTypes[i].getElementType(),
					fArgTypes[i].getDimensions()-1, ast);
			argDecl.setVarargs(true);
		} else
			argType= typeNodeForTypeBinding(fArgTypes[i], 0, ast);

		argDecl.setName(ast.newSimpleName(fFormalArgNames[i]));
		argDecl.setType(argType);
		argDecls.add(argDecl);
	}

	ITypeBinding[] ctorExcepts= fCtorBinding.getExceptionTypes();
	List<Type> exceptions= newMethod.thrownExceptionTypes();

	for(int i=0; i < ctorExcepts.length; i++) {
		exceptions.add(fImportRewriter.addImport(ctorExcepts[i], ast));
	}

       copyTypeParameters(ast, newMethod);
}
 
Example 9
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 10
Source File: NewVariableCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private ASTRewrite doAddParam(CompilationUnit cu) {
	AST ast= cu.getAST();
	SimpleName node= fOriginalNode;

	BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(node);
	if (decl instanceof MethodDeclaration) {
		MethodDeclaration methodDeclaration= (MethodDeclaration) decl;

		ASTRewrite rewrite= ASTRewrite.create(ast);

		ImportRewrite imports= createImportRewrite((CompilationUnit) decl.getRoot());
		ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(decl, imports);

		SingleVariableDeclaration newDecl= ast.newSingleVariableDeclaration();
		newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, methodDeclaration.resolveBinding(), TypeLocation.PARAMETER));
		newDecl.setName(ast.newSimpleName(node.getIdentifier()));

		ListRewrite listRewriter= rewrite.getListRewrite(decl, MethodDeclaration.PARAMETERS_PROPERTY);
		listRewriter.insertLast(newDecl, null);

		// add javadoc tag
		Javadoc javadoc= methodDeclaration.getJavadoc();
		if (javadoc != null) {
			HashSet<String> leadingNames= new HashSet<>();
			for (Iterator<SingleVariableDeclaration> iter= methodDeclaration.parameters().iterator(); iter.hasNext();) {
				SingleVariableDeclaration curr= iter.next();
				leadingNames.add(curr.getName().getIdentifier());
			}
			SimpleName newTagRef= ast.newSimpleName(node.getIdentifier());

			TagElement newTagElement= ast.newTagElement();
			newTagElement.setTagName(TagElement.TAG_PARAM);
			newTagElement.fragments().add(newTagRef);
			TextElement commentStart= ast.newTextElement();
			newTagElement.fragments().add(commentStart);

			ListRewrite tagsRewriter= rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY);
			JavadocTagsSubProcessor.insertTag(tagsRewriter, newTagElement, leadingNames);
		}

		return rewrite;
	}
	return null;
}
 
Example 11
Source File: ConstructorFromSuperclassProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.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));
			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);
			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 12
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 13
Source File: NewVariableCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private ASTRewrite doAddParam(CompilationUnit cu) {
	AST ast= cu.getAST();
	SimpleName node= fOriginalNode;

	BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(node);
	if (decl instanceof MethodDeclaration) {
		MethodDeclaration methodDeclaration= (MethodDeclaration) decl;

		ASTRewrite rewrite= ASTRewrite.create(ast);

		ImportRewrite imports= createImportRewrite((CompilationUnit) decl.getRoot());
		ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(decl, imports);

		SingleVariableDeclaration newDecl= ast.newSingleVariableDeclaration();
		newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, methodDeclaration.resolveBinding()));
		newDecl.setName(ast.newSimpleName(node.getIdentifier()));

		ListRewrite listRewriter= rewrite.getListRewrite(decl, MethodDeclaration.PARAMETERS_PROPERTY);
		listRewriter.insertLast(newDecl, null);

		addLinkedPosition(rewrite.track(node), true, KEY_NAME);

		// add javadoc tag
		Javadoc javadoc= methodDeclaration.getJavadoc();
		if (javadoc != null) {
			HashSet<String> leadingNames= new HashSet<String>();
			for (Iterator<SingleVariableDeclaration> iter= methodDeclaration.parameters().iterator(); iter.hasNext();) {
				SingleVariableDeclaration curr= iter.next();
				leadingNames.add(curr.getName().getIdentifier());
			}
			SimpleName newTagRef= ast.newSimpleName(node.getIdentifier());

			TagElement newTagElement= ast.newTagElement();
			newTagElement.setTagName(TagElement.TAG_PARAM);
			newTagElement.fragments().add(newTagRef);
			TextElement commentStart= ast.newTextElement();
			newTagElement.fragments().add(commentStart);

			addLinkedPosition(rewrite.track(newTagRef), false, KEY_NAME);
			addLinkedPosition(rewrite.track(commentStart), false, "comment_start"); //$NON-NLS-1$

			ListRewrite tagsRewriter= rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY);
			JavadocTagsSubProcessor.insertTag(tagsRewriter, newTagElement, leadingNames);
		}
		
		addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
		addLinkedPosition(rewrite.track(newDecl.getName()), false, KEY_NAME);

		return rewrite;
	}
	return null;
}
 
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: 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 16
Source File: CopyInstanceBuilderMethodDefinitionCreatorFragment.java    From SparkBuilderGenerator with MIT License 4 votes vote down vote up
private SingleVariableDeclaration createParameter(AST ast, TypeDeclaration originalType, String methodParameterName) {
    SingleVariableDeclaration methodParameterDeclaration = ast.newSingleVariableDeclaration();
    methodParameterDeclaration.setType(ast.newSimpleType(ast.newName(originalType.getName().toString())));
    methodParameterDeclaration.setName(ast.newSimpleName(methodParameterName));
    return methodParameterDeclaration;
}
 
Example 17
Source File: RegularBuilderCopyInstanceConstructorAdderFragment.java    From SparkBuilderGenerator with MIT License 4 votes vote down vote up
private SingleVariableDeclaration createParameter(AST ast, TypeDeclaration originalType, String parameterName) {
    SingleVariableDeclaration methodParameterDeclaration = ast.newSingleVariableDeclaration();
    methodParameterDeclaration.setType(ast.newSimpleType(ast.newName(originalType.getName().toString())));
    methodParameterDeclaration.setName(ast.newSimpleName(parameterName));
    return methodParameterDeclaration;
}
 
Example 18
Source File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private SingleVariableDeclaration newParameterDeclaration(AST ast, ImportRewrite importRewrite, String paramName, ITypeBinding paramType) {
  	SingleVariableDeclaration param= ast.newSingleVariableDeclaration();
param.setType(importRewrite.addImport(paramType, ast));
param.setName(ast.newSimpleName(paramName));
return param;
  }
 
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: PublicConstructorWithMandatoryFieldsAdderFragment.java    From SparkBuilderGenerator with MIT License 4 votes vote down vote up
private SingleVariableDeclaration createParameter(AST ast, Type type, String parameterName) {
    SingleVariableDeclaration methodParameterDeclaration = ast.newSingleVariableDeclaration();
    methodParameterDeclaration.setType((Type) ASTNode.copySubtree(ast, type));
    methodParameterDeclaration.setName(ast.newSimpleName(parameterName));
    return methodParameterDeclaration;
}