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

The following examples show how to use org.eclipse.jdt.core.dom.AST#newSingleVariableDeclaration() . 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: MoveMethodRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
private SimpleName addSourceClassParameterToMovedMethod(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter) {
	AST ast = newMethodDeclaration.getAST();
	SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration();
	SimpleName typeName = ast.newSimpleName(sourceTypeDeclaration.getName().getIdentifier());
	Type parameterType = ast.newSimpleType(typeName);
	targetRewriter.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, parameterType, null);
	String sourceTypeName = sourceTypeDeclaration.getName().getIdentifier();
	SimpleName parameterName = ast.newSimpleName(sourceTypeName.replaceFirst(Character.toString(sourceTypeName.charAt(0)), Character.toString(Character.toLowerCase(sourceTypeName.charAt(0)))));
	targetRewriter.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, parameterName, null);
	ListRewrite parametersRewrite = targetRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.PARAMETERS_PROPERTY);
	parametersRewrite.insertLast(parameter, null);
	this.additionalArgumentsAddedToMovedMethod.add("this");
	this.additionalTypeBindingsToBeImportedInTargetClass.add(sourceTypeDeclaration.resolveBinding());
	addParamTagElementToJavadoc(newMethodDeclaration, targetRewriter, parameterName.getIdentifier());
	setPublicModifierToSourceTypeDeclaration();
	return parameterName;
}
 
Example 3
Source File: NewMethodCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params, ImportRewriteContext context) throws CoreException {
	AST ast= rewrite.getAST();

	List<Expression> arguments= fArguments;

	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);
	}
}
 
Example 4
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
private void addParameterToMovedMethod(MethodDeclaration newMethodDeclaration, SimpleName fieldName, ASTRewrite targetRewriter) {
	AST ast = newMethodDeclaration.getAST();
	SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration();
	Type fieldType = null;
	FieldDeclaration[] fields = sourceTypeDeclaration.getFields();
	for(FieldDeclaration field : fields) {
		List<VariableDeclarationFragment> fragments = field.fragments();
		for(VariableDeclarationFragment fragment : fragments) {
			if(fragment.getName().getIdentifier().equals(fieldName.getIdentifier())) {
				fieldType = field.getType();
				break;
			}
		}
	}
	targetRewriter.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, fieldType, null);
	targetRewriter.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, ast.newSimpleName(fieldName.getIdentifier()), null);
	ListRewrite parametersRewrite = targetRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.PARAMETERS_PROPERTY);
	parametersRewrite.insertLast(parameter, null);
	this.additionalArgumentsAddedToMovedMethod.add(fieldName.getIdentifier());
	this.additionalTypeBindingsToBeImportedInTargetClass.add(fieldType.resolveBinding());
	addParamTagElementToJavadoc(newMethodDeclaration, targetRewriter, fieldName.getIdentifier());
}
 
Example 5
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 5 votes vote down vote up
private void addParameterToMovedMethod(MethodDeclaration newMethodDeclaration, IVariableBinding variableBinding, ASTRewrite targetRewriter) {
	AST ast = newMethodDeclaration.getAST();
	SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration();
	ITypeBinding typeBinding = variableBinding.getType();
	Type fieldType = RefactoringUtility.generateTypeFromTypeBinding(typeBinding, ast, targetRewriter);
	targetRewriter.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, fieldType, null);
	targetRewriter.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, ast.newSimpleName(variableBinding.getName()), null);
	ListRewrite parametersRewrite = targetRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.PARAMETERS_PROPERTY);
	parametersRewrite.insertLast(parameter, null);
	this.additionalArgumentsAddedToMovedMethod.add(variableBinding.getName());
	this.additionalTypeBindingsToBeImportedInTargetClass.add(variableBinding.getType());
	addParamTagElementToJavadoc(newMethodDeclaration, targetRewriter, variableBinding.getName());
}
 
Example 6
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 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: 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 9
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 10
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 11
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 12
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 13
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 14
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 15
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 16
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 17
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 18
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 19
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 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;
}