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

The following examples show how to use org.eclipse.jdt.core.dom.SingleVariableDeclaration#setType() . 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: 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 2
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 3
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 4
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 5
Source File: ChangeSignatureProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected SingleVariableDeclaration createNewSingleVariableDeclaration(ParameterInfo info) {
	SingleVariableDeclaration newP= getASTRewrite().getAST().newSingleVariableDeclaration();
	newP.setName(getASTRewrite().getAST().newSimpleName(info.getNewName()));
	newP.setType(createNewTypeNode(ParameterInfo.stripEllipsis(info.getNewTypeName()), info.getNewTypeBinding()));
	newP.setVarargs(info.isNewVarargs());
	return newP;
}
 
Example 6
Source File: NewMethodCorrectionProposal.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();

	List<Expression> arguments= fArguments;
	ImportRewriteContext context= new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(getInvocationNode()), getImportRewrite());

	for (int i= 0; i < arguments.size(); i++) {
		Expression elem= arguments.get(i);
		SingleVariableDeclaration param= ast.newSingleVariableDeclaration();

		// argument type
		String argTypeKey= "arg_type_" + i; //$NON-NLS-1$
		Type type= evaluateParameterType(ast, elem, argTypeKey, context);
		param.setType(type);

		// argument name
		String argNameKey= "arg_name_" + i; //$NON-NLS-1$
		String name= evaluateParameterName(takenNames, elem, type, argNameKey);
		param.setName(ast.newSimpleName(name));

		params.add(param);

		addLinkedPosition(rewrite.track(param.getType()), false, argTypeKey);
		addLinkedPosition(rewrite.track(param.getName()), false, argNameKey);
	}
}
 
Example 7
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void createConstructor(final AbstractTypeDeclaration declaration, final ASTRewrite rewrite) throws CoreException {
	Assert.isNotNull(declaration);
	Assert.isNotNull(rewrite);
	final AST ast= declaration.getAST();
	final MethodDeclaration constructor= ast.newMethodDeclaration();
	constructor.setConstructor(true);
	constructor.setName(ast.newSimpleName(declaration.getName().getIdentifier()));
	final String comment= CodeGeneration.getMethodComment(fType.getCompilationUnit(), fType.getElementName(), fType.getElementName(), getNewConstructorParameterNames(), new String[0], null, null, StubUtility.getLineDelimiterUsed(fType.getJavaProject()));
	if (comment != null && comment.length() > 0) {
		final Javadoc doc= (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC);
		constructor.setJavadoc(doc);
	}
	if (fCreateInstanceField) {
		final SingleVariableDeclaration variable= ast.newSingleVariableDeclaration();
		final String name= getNameForEnclosingInstanceConstructorParameter();
		variable.setName(ast.newSimpleName(name));
		variable.setType(createEnclosingType(ast));
		constructor.parameters().add(variable);
		final Block body= ast.newBlock();
		final Assignment assignment= ast.newAssignment();
		if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
			final FieldAccess access= ast.newFieldAccess();
			access.setExpression(ast.newThisExpression());
			access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
			assignment.setLeftHandSide(access);
		} else
			assignment.setLeftHandSide(ast.newSimpleName(fEnclosingInstanceFieldName));
		assignment.setRightHandSide(ast.newSimpleName(name));
		final Statement statement= ast.newExpressionStatement(assignment);
		body.statements().add(statement);
		constructor.setBody(body);
	} else
		constructor.setBody(ast.newBlock());
	rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertFirst(constructor, null);
}
 
Example 8
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addParameterToConstructor(final ASTRewrite rewrite, final MethodDeclaration declaration) throws JavaModelException {
	Assert.isNotNull(rewrite);
	Assert.isNotNull(declaration);
	final AST ast= declaration.getAST();
	final String name= getNameForEnclosingInstanceConstructorParameter();
	final SingleVariableDeclaration variable= ast.newSingleVariableDeclaration();
	variable.setType(createEnclosingType(ast));
	variable.setName(ast.newSimpleName(name));
	rewrite.getListRewrite(declaration, MethodDeclaration.PARAMETERS_PROPERTY).insertFirst(variable, null);
	JavadocUtil.addParamJavadoc(name, declaration, rewrite, fType.getJavaProject(), null);
}
 
Example 9
Source File: Util.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a GWT RPC async callback parameter declaration based on the sync
 * method return type.
 *
 * @param ast {@link AST} associated with the destination compilation unit
 * @param syncReturnType the sync method return type
 * @param callbackParameterName name of the callback parameter
 * @param imports {@link ImportsRewrite} for the destination compilation unit
 * @return callback paramter declaration
 */
@SuppressWarnings("unchecked")
public static SingleVariableDeclaration createAsyncCallbackParameter(AST ast,
    Type syncReturnType, String callbackParameterName, ImportRewrite imports) {
  ITypeBinding syncReturnTypeBinding = syncReturnType.resolveBinding();

  SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration();

  String gwtCallbackTypeSig = Signature.createTypeSignature(
      RemoteServiceUtilities.ASYNCCALLBACK_QUALIFIED_NAME, true);
  Type gwtCallbackType = imports.addImportFromSignature(gwtCallbackTypeSig,
      ast);

  if (syncReturnTypeBinding.isPrimitive()) {
    String wrapperName = JavaASTUtils.getWrapperTypeName(syncReturnTypeBinding.getName());
    String wrapperTypeSig = Signature.createTypeSignature(wrapperName, true);
    syncReturnType = imports.addImportFromSignature(wrapperTypeSig, ast);
  } else {
    syncReturnType = JavaASTUtils.normalizeTypeAndAddImport(ast,
        syncReturnType, imports);
  }

  ParameterizedType type = ast.newParameterizedType(gwtCallbackType);
  List<Type> typeArgs = type.typeArguments();
  typeArgs.add(syncReturnType);

  parameter.setType(type);
  parameter.setName(ast.newSimpleName(callbackParameterName));

  return parameter;
}
 
Example 10
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 11
Source File: TryPurifyByException.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
private ASTNode tryCatchStmt(AST ast, ASTNode node){
	Block block = ast.newBlock();
	block.statements().add(ASTNode.copySubtree(ast, node));
	TryStatement tryStatement = ast.newTryStatement();
	tryStatement.setBody(block);
	CatchClause catchClause = ast.newCatchClause();
	SingleVariableDeclaration svd = ast.newSingleVariableDeclaration();
	svd.setType(ast.newSimpleType(ast.newSimpleName("Exception")));
	svd.setName(ast.newSimpleName("mException"));
	catchClause.setException(svd);
	tryStatement.catchClauses().add(catchClause);
	return tryStatement;
}
 
Example 12
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 13
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 14
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 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: 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 17
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;
}
 
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: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Helper to generate a <code>foreach</code> loop to iterate over an {@link Iterable}.
 * 
 * @param ast the {@link AST} instance to rewrite the loop to
 * @return the complete {@link ASTRewrite} object
 */
private ASTRewrite generateForEachRewrite(AST ast) {

	EnhancedForStatement loopStatement= ast.newEnhancedForStatement();

	ASTRewrite rewrite= ASTRewrite.create(ast);
	ITypeBinding loopOverType= extractElementType(ast);

	// generate name proposals and add them to the variable declaration
	SimpleName forDeclarationName= resolveLinkedVariableNameWithProposals(rewrite, loopOverType.getName(), null, true);

	SingleVariableDeclaration forLoopInitializer= ast.newSingleVariableDeclaration();
	forLoopInitializer.setType(getImportRewrite().addImport(loopOverType, ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite())));
	forLoopInitializer.setName(forDeclarationName);

	loopStatement.setParameter(forLoopInitializer);
	loopStatement.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression));

	Block forLoopBody= ast.newBlock();
	forLoopBody.statements().add(createBlankLineStatementWithCursorPosition(rewrite));

	loopStatement.setBody(forLoopBody);

	rewrite.replace(fCurrentNode, loopStatement, null);

	return rewrite;
}