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

The following examples show how to use org.eclipse.jdt.core.dom.VariableDeclarationStatement#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: ExtractTempRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private VariableDeclarationStatement createTempDeclaration(Expression initializer) throws CoreException {
	AST ast = fCURewrite.getAST();

	VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment();
	vdf.setName(ast.newSimpleName(fTempName));
	vdf.setInitializer(initializer);

	VariableDeclarationStatement vds = ast.newVariableDeclarationStatement(vdf);
	if (fDeclareFinal) {
		vds.modifiers().add(ast.newModifier(ModifierKeyword.FINAL_KEYWORD));
	}
	vds.setType(createTempType());

	if (fLinkedProposalModel != null) {
		ASTRewrite rewrite = fCURewrite.getASTRewrite();
		LinkedProposalPositionGroupCore nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
		nameGroup.addPosition(rewrite.track(vdf.getName()), true);

		String[] nameSuggestions = guessTempNames();
		if (nameSuggestions.length > 0 && !nameSuggestions[0].equals(fTempName)) {
			nameGroup.addProposal(fTempName, nameSuggestions.length + 1);
		}
		for (int i = 0; i < nameSuggestions.length; i++) {
			nameGroup.addProposal(nameSuggestions[i], nameSuggestions.length - i);
		}
	}
	return vds;
}
 
Example 2
Source File: ExtractMethodRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private VariableDeclarationStatement createDeclaration(IVariableBinding binding, Expression intilizer) {
	VariableDeclaration original = ASTNodes.findVariableDeclaration(binding, fAnalyzer.getEnclosingBodyDeclaration());
	VariableDeclarationFragment fragment = fAST.newVariableDeclarationFragment();
	fragment.setName((SimpleName) ASTNode.copySubtree(fAST, original.getName()));
	fragment.setInitializer(intilizer);
	VariableDeclarationStatement result = fAST.newVariableDeclarationStatement(fragment);
	result.modifiers().addAll(ASTNode.copySubtrees(fAST, ASTNodes.getModifiers(original)));
	result.setType(ASTNodeFactory.newType(fAST, original, fImportRewriter, new ContextSensitiveImportRewriteContext(original, fImportRewriter)));
	return result;
}
 
Example 3
Source File: ExtractTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private VariableDeclarationStatement createTempDeclaration(Expression initializer) throws CoreException {
	AST ast= fCURewrite.getAST();

	VariableDeclarationFragment vdf= ast.newVariableDeclarationFragment();
	vdf.setName(ast.newSimpleName(fTempName));
	vdf.setInitializer(initializer);

	VariableDeclarationStatement vds= ast.newVariableDeclarationStatement(vdf);
	if (fDeclareFinal) {
		vds.modifiers().add(ast.newModifier(ModifierKeyword.FINAL_KEYWORD));
	}
	vds.setType(createTempType());

	if (fLinkedProposalModel != null) {
		ASTRewrite rewrite= fCURewrite.getASTRewrite();
		LinkedProposalPositionGroup nameGroup= fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
		nameGroup.addPosition(rewrite.track(vdf.getName()), true);

		String[] nameSuggestions= guessTempNames();
		if (nameSuggestions.length > 0 && !nameSuggestions[0].equals(fTempName)) {
			nameGroup.addProposal(fTempName, null, nameSuggestions.length + 1);
		}
		for (int i= 0; i < nameSuggestions.length; i++) {
			nameGroup.addProposal(nameSuggestions[i], null, nameSuggestions.length - i);
		}
	}
	return vds;
}
 
Example 4
Source File: ExtractMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private VariableDeclarationStatement createDeclaration(IVariableBinding binding, Expression intilizer) {
	VariableDeclaration original= ASTNodes.findVariableDeclaration(binding, fAnalyzer.getEnclosingBodyDeclaration());
	VariableDeclarationFragment fragment= fAST.newVariableDeclarationFragment();
	fragment.setName((SimpleName)ASTNode.copySubtree(fAST, original.getName()));
	fragment.setInitializer(intilizer);
	VariableDeclarationStatement result= fAST.newVariableDeclarationStatement(fragment);
	result.modifiers().addAll(ASTNode.copySubtrees(fAST, ASTNodes.getModifiers(original)));
	result.setType(ASTNodeFactory.newType(fAST, original, fImportRewriter, new ContextSensitiveImportRewriteContext(original, fImportRewriter)));
	return result;
}
 
Example 5
Source File: StringBuilderGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void initialize() {
	super.initialize();
	fBuilderVariableName= createNameSuggestion(getContext().is50orHigher() ? "builder" : "buffer", NamingConventions.VK_LOCAL); //$NON-NLS-1$ //$NON-NLS-2$
	fBuffer= new StringBuffer();
	VariableDeclarationFragment fragment= fAst.newVariableDeclarationFragment();
	fragment.setName(fAst.newSimpleName(fBuilderVariableName));
	ClassInstanceCreation classInstance= fAst.newClassInstanceCreation();
	Name typeName= addImport(getContext().is50orHigher() ? "java.lang.StringBuilder" : "java.lang.StringBuffer"); //$NON-NLS-1$ //$NON-NLS-2$
	classInstance.setType(fAst.newSimpleType(typeName));
	fragment.setInitializer(classInstance);
	VariableDeclarationStatement vStatement= fAst.newVariableDeclarationStatement(fragment);
	vStatement.setType(fAst.newSimpleType((Name)ASTNode.copySubtree(fAst, typeName)));
	toStringMethod.getBody().statements().add(vStatement);
}
 
Example 6
Source File: AbstractToStringGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @return a statement in form of <code>final int maxLen = 10;</code>
 */
protected VariableDeclarationStatement createMaxLenDeclaration() {
	VariableDeclarationFragment fragment= fAst.newVariableDeclarationFragment();
	fragment.setName(fAst.newSimpleName(fMaxLenVariableName));
	fragment.setInitializer(fAst.newNumberLiteral(String.valueOf(fContext.getLimitItemsValue())));
	VariableDeclarationStatement declExpression= fAst.newVariableDeclarationStatement(fragment);
	declExpression.setType(fAst.newPrimitiveType(PrimitiveType.INT));
	declExpression.modifiers().add(fAst.newModifier(ModifierKeyword.FINAL_KEYWORD));
	return declExpression;
}
 
Example 7
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void splitUpDeclarations(ASTRewrite rewrite, TextEditGroup group, VariableDeclarationFragment frag, VariableDeclarationStatement originalStatement, List<Expression> sideEffects) {
	if (sideEffects.size() > 0) {
		ListRewrite statementRewrite= rewrite.getListRewrite(originalStatement.getParent(), (ChildListPropertyDescriptor) originalStatement.getLocationInParent());
		
		Statement previousStatement= originalStatement;
		for (int i= 0; i < sideEffects.size(); i++) {
			Expression sideEffect= sideEffects.get(i);
			Expression movedInit= (Expression) rewrite.createMoveTarget(sideEffect);
			ExpressionStatement wrapped= rewrite.getAST().newExpressionStatement(movedInit);
			statementRewrite.insertAfter(wrapped, previousStatement, group);
			previousStatement= wrapped;
		}

		VariableDeclarationStatement newDeclaration= null;
		List<VariableDeclarationFragment> fragments= originalStatement.fragments();
		int fragIndex= fragments.indexOf(frag);
		ListIterator<VariableDeclarationFragment> fragmentIterator= fragments.listIterator(fragIndex+1);
		while (fragmentIterator.hasNext()) {
			VariableDeclarationFragment currentFragment= fragmentIterator.next();
			VariableDeclarationFragment movedFragment= (VariableDeclarationFragment) rewrite.createMoveTarget(currentFragment);
			if (newDeclaration == null) {
				newDeclaration= rewrite.getAST().newVariableDeclarationStatement(movedFragment);
				Type copiedType= (Type) rewrite.createCopyTarget(originalStatement.getType());
				newDeclaration.setType(copiedType);
			} else {
				newDeclaration.fragments().add(movedFragment);
			}
		}
		if (newDeclaration != null){
			statementRewrite.insertAfter(newDeclaration, previousStatement, group);
			if (originalStatement.fragments().size() == newDeclaration.fragments().size() + 1){
				rewrite.remove(originalStatement, group);
			}
		}
	}
}
 
Example 8
Source File: SurroundWith.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Split the fragments in <code>statement</code> to multiple VariableDeclarationStatements whenever
 * <code>splitOperator.needsSplit</code> returns <code>true</code>.
 * i.e.:
 * int i, j; ---> int i; int j; (if splitOperator.needsSplit(i, j) == true)
 *
 * @param statement The VariableDeclarationStatement to split
 * @param splitOperator The operator to use to split
 * @param rewrite The rewriter to use to generate new VariableDeclarationStatements.
 */
private void splitVariableDeclarationStatement(VariableDeclarationStatement statement, ISplitOperation splitOperator, ASTRewrite rewrite) {

	List<VariableDeclarationFragment> fragments= statement.fragments();
	Iterator<VariableDeclarationFragment> iter= fragments.iterator();
	VariableDeclarationFragment lastFragment= iter.next();
	VariableDeclarationStatement lastStatement= statement;

	splitOperator.initializeStatement(lastStatement, lastFragment);

	ListRewrite fragmentsRewrite= null;
	while (iter.hasNext()) {
		VariableDeclarationFragment currentFragment= iter.next();

		if (splitOperator.needsSplit(lastFragment, currentFragment)) {

			VariableDeclarationStatement newStatement= getAst().newVariableDeclarationStatement((VariableDeclarationFragment)rewrite.createMoveTarget(currentFragment));

			ListRewrite modifierRewrite= rewrite.getListRewrite(newStatement, VariableDeclarationStatement.MODIFIERS2_PROPERTY);
			for (Iterator<IExtendedModifier> iterator= statement.modifiers().iterator(); iterator.hasNext();) {
				modifierRewrite.insertLast(rewrite.createCopyTarget((ASTNode)iterator.next()), null);
			}

			newStatement.setType((Type)rewrite.createCopyTarget(statement.getType()));

			splitOperator.initializeStatement(newStatement, currentFragment);

			fragmentsRewrite= rewrite.getListRewrite(newStatement, VariableDeclarationStatement.FRAGMENTS_PROPERTY);

			lastStatement= newStatement;
		} else if (fragmentsRewrite != null) {
			ASTNode fragment0= rewrite.createMoveTarget(currentFragment);
			fragmentsRewrite.insertLast(fragment0, null);
		}
		lastFragment= currentFragment;
	}
}
 
Example 9
Source File: AssignToVariableAssistProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private ASTRewrite doAddLocal() {
	ASTNode nodeToAssign= fNodesToAssign.get(0);
	Expression expression= ((ExpressionStatement) nodeToAssign).getExpression();
	AST ast= nodeToAssign.getAST();

	ASTRewrite rewrite= ASTRewrite.create(ast);

	createImportRewrite((CompilationUnit) nodeToAssign.getRoot());

	String[] varNames= suggestLocalVariableNames(fTypeBinding, expression);
	for (int i= 0; i < varNames.length; i++) {
		addLinkedPositionProposal(KEY_NAME, varNames[i]);
	}

	VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment();
	newDeclFrag.setName(ast.newSimpleName(varNames[0]));
	newDeclFrag.setInitializer((Expression) rewrite.createCopyTarget(expression));

	Type type= evaluateType(ast, nodeToAssign, fTypeBinding, KEY_TYPE, TypeLocation.LOCAL_VARIABLE);

	if (ASTNodes.isControlStatementBody(nodeToAssign.getLocationInParent())) {
		Block block= ast.newBlock();
		block.statements().add(rewrite.createMoveTarget(nodeToAssign));
		rewrite.replace(nodeToAssign, block, null);
	}

	if (needsSemicolon(expression)) {
		VariableDeclarationStatement varStatement= ast.newVariableDeclarationStatement(newDeclFrag);
		varStatement.setType(type);
		rewrite.replace(expression, varStatement, null);
	} else {
		// trick for bug 43248: use an VariableDeclarationExpression and keep the ExpressionStatement
		VariableDeclarationExpression varExpression= ast.newVariableDeclarationExpression(newDeclFrag);
		varExpression.setType(type);
		rewrite.replace(expression, varExpression, null);
	}

	addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME);
	addLinkedPosition(rewrite.track(type), false, KEY_TYPE);
	setEndPosition(rewrite.track(nodeToAssign)); // set cursor after expression statement

	return rewrite;
}
 
Example 10
Source File: CustomBuilderGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public MethodDeclaration generateToStringMethod() throws CoreException {
	initialize();

	//ToStringBuilder builder= new ToStringBuilder(this);
	String builderVariableName= createNameSuggestion(getContext().getCustomBuilderVariableName(), NamingConventions.VK_LOCAL);
	VariableDeclarationFragment fragment= fAst.newVariableDeclarationFragment();
	fragment.setName(fAst.newSimpleName(builderVariableName));
	ClassInstanceCreation classInstance= fAst.newClassInstanceCreation();
	Name typeName= addImport(getContext().getCustomBuilderClass());
	classInstance.setType(fAst.newSimpleType(typeName));
	classInstance.arguments().add(fAst.newThisExpression());
	fragment.setInitializer(classInstance);
	VariableDeclarationStatement vStatement= fAst.newVariableDeclarationStatement(fragment);
	vStatement.setType(fAst.newSimpleType((Name)ASTNode.copySubtree(fAst, typeName)));
	toStringMethod.getBody().statements().add(vStatement);

	/* expression for accumulating chained calls */
	Expression expression= null;

	for (int i= 0; i < getContext().getSelectedMembers().length; i++) {
		//builder.append("member", member);
		MethodInvocation appendInvocation= createAppendMethodForMember(getContext().getSelectedMembers()[i]);
		if (getContext().isSkipNulls() && !getMemberType(getContext().getSelectedMembers()[i]).isPrimitive()) {
			if (expression != null) {
				toStringMethod.getBody().statements().add(fAst.newExpressionStatement(expression));
				expression= null;
			}
			appendInvocation.setExpression(fAst.newSimpleName(builderVariableName));
			IfStatement ifStatement= fAst.newIfStatement();
			ifStatement.setExpression(createInfixExpression(createMemberAccessExpression(getContext().getSelectedMembers()[i], true, true), Operator.NOT_EQUALS, fAst.newNullLiteral()));
			ifStatement.setThenStatement(createOneStatementBlock(appendInvocation));
			toStringMethod.getBody().statements().add(ifStatement);
		} else {
			if (expression != null) {
				appendInvocation.setExpression(expression);
			} else {
				appendInvocation.setExpression(fAst.newSimpleName(builderVariableName));
			}
			if (getContext().isCustomBuilderChainedCalls() && canChainLastAppendCall) {
				expression= appendInvocation;
			} else {
				expression= null;
				toStringMethod.getBody().statements().add(fAst.newExpressionStatement(appendInvocation));
			}
		}
	}

	if (expression != null) {
		toStringMethod.getBody().statements().add(fAst.newExpressionStatement(expression));
	}
	// return builder.toString();
	ReturnStatement rStatement= fAst.newReturnStatement();
	rStatement.setExpression(createMethodInvocation(builderVariableName, getContext().getCustomBuilderResultMethod(), null));
	toStringMethod.getBody().statements().add(rStatement);

	complete();

	return toStringMethod;
}
 
Example 11
Source File: GenerateHashCodeEqualsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private MethodDeclaration createHashCodeMethod() throws CoreException {

		MethodDeclaration hashCodeMethod= fAst.newMethodDeclaration();
		hashCodeMethod.modifiers().addAll(ASTNodeFactory.newModifiers(fAst, Modifier.PUBLIC));
		hashCodeMethod.setName(fAst.newSimpleName(METHODNAME_HASH_CODE));
		hashCodeMethod.setConstructor(false);
		hashCodeMethod.setReturnType2(fAst.newPrimitiveType(PrimitiveType.INT));

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

		// PRIME NUMBER
		VariableDeclarationFragment frag= fAst.newVariableDeclarationFragment();
		frag.setName(fAst.newSimpleName(VARIABLE_NAME_PRIME));
		frag.setInitializer(fAst.newNumberLiteral(PRIME_NUMBER));

		VariableDeclarationStatement primeNumberDeclaration= fAst.newVariableDeclarationStatement(frag);
		primeNumberDeclaration.modifiers().add(fAst.newModifier(ModifierKeyword.FINAL_KEYWORD));
		primeNumberDeclaration.setType(fAst.newPrimitiveType(PrimitiveType.INT));
		body.statements().add(primeNumberDeclaration);

		// RESULT
		VariableDeclarationFragment fragment= fAst.newVariableDeclarationFragment();
		fragment.setName(fAst.newSimpleName(VARIABLE_NAME_RESULT));

		VariableDeclarationStatement resultDeclaration= fAst.newVariableDeclarationStatement(fragment);
		resultDeclaration.setType(fAst.newPrimitiveType(PrimitiveType.INT));
		body.statements().add(resultDeclaration);

		if (needsNoSuperCall(fType, METHODNAME_HASH_CODE, new ITypeBinding[0])) {
			fragment.setInitializer(fAst.newNumberLiteral(INITIAL_HASHCODE_VALUE));
		} else {
			SuperMethodInvocation invoc= fAst.newSuperMethodInvocation();
			invoc.setName(fAst.newSimpleName(METHODNAME_HASH_CODE));
			fragment.setInitializer(invoc);
		}

		if (isMemberType()) {
			body.statements().add(createAddOuterHashCode());
		}

		for (int i= 0; i < fFields.length; i++) {
			if (fFields[i].getType().isPrimitive()) {
				Statement[] sts= createAddSimpleHashCode(fFields[i].getType(), new IHashCodeAccessProvider() {

					public Expression getThisAccess(String name) {
						return getThisAccessForHashCode(name);
					}

				}, fFields[i].getName(), false);
				for (int j= 0; j < sts.length; j++) {
					body.statements().add(sts[j]);
				}
			} else if (fFields[i].getType().isArray())
				body.statements().add(createAddArrayHashCode(fFields[i]));
			else
				body.statements().add(createAddQualifiedHashCode(fFields[i]));
		}

		// the last return:
		ReturnStatement endReturn= fAst.newReturnStatement();
		endReturn.setExpression(fAst.newSimpleName(VARIABLE_NAME_RESULT));
		body.statements().add(endReturn);

		// method comment
		if (fSettings != null) {
			ITypeBinding object= fAst.resolveWellKnownType(JAVA_LANG_OBJECT);
			IMethodBinding[] objms= object.getDeclaredMethods();
			IMethodBinding objectMethod= null;
			for (int i= 0; i < objms.length; i++) {
				if (objms[i].getName().equals(METHODNAME_HASH_CODE) && objms[i].getParameterTypes().length == 0)
					objectMethod= objms[i];
			}
			createMethodComment(hashCodeMethod, objectMethod);
		}

		return hashCodeMethod;
	}
 
Example 12
Source File: AssignToVariableAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private ASTRewrite doAddLocal() {
	Expression expression= ((ExpressionStatement) fNodeToAssign).getExpression();
	AST ast= fNodeToAssign.getAST();

	ASTRewrite rewrite= ASTRewrite.create(ast);

	createImportRewrite((CompilationUnit) fNodeToAssign.getRoot());

	String[] varNames= suggestLocalVariableNames(fTypeBinding, expression);
	for (int i= 0; i < varNames.length; i++) {
		addLinkedPositionProposal(KEY_NAME, varNames[i], null);
	}

	VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment();
	newDeclFrag.setName(ast.newSimpleName(varNames[0]));
	newDeclFrag.setInitializer((Expression) rewrite.createCopyTarget(expression));

	Type type= evaluateType(ast);

	if (ASTNodes.isControlStatementBody(fNodeToAssign.getLocationInParent())) {
		Block block= ast.newBlock();
		block.statements().add(rewrite.createMoveTarget(fNodeToAssign));
		rewrite.replace(fNodeToAssign, block, null);
	}

	if (needsSemicolon(expression)) {
		VariableDeclarationStatement varStatement= ast.newVariableDeclarationStatement(newDeclFrag);
		varStatement.setType(type);
		rewrite.replace(expression, varStatement, null);
	} else {
		// trick for bug 43248: use an VariableDeclarationExpression and keep the ExpressionStatement
		VariableDeclarationExpression varExpression= ast.newVariableDeclarationExpression(newDeclFrag);
		varExpression.setType(type);
		rewrite.replace(expression, varExpression, null);
	}

	addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME);
	addLinkedPosition(rewrite.track(type), false, KEY_TYPE);
	setEndPosition(rewrite.track(fNodeToAssign)); // set cursor after expression statement

	return rewrite;
}