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

The following examples show how to use org.eclipse.jdt.core.dom.VariableDeclarationFragment#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: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void createFieldsForAccessedLocals(CompilationUnitRewrite rewrite, IVariableBinding[] varBindings, String[] fieldNames, List<BodyDeclaration> newBodyDeclarations) throws CoreException {
	final ImportRewrite importRewrite= rewrite.getImportRewrite();
	final ASTRewrite astRewrite= rewrite.getASTRewrite();
	final AST ast= astRewrite.getAST();

	for (int i= 0; i < varBindings.length; i++) {
		VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
		fragment.setInitializer(null);
		fragment.setName(ast.newSimpleName(fieldNames[i]));
		FieldDeclaration field= ast.newFieldDeclaration(fragment);
		ITypeBinding varType= varBindings[i].getType();
		field.setType(importRewrite.addImport(varType, ast));
		field.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.FINAL));
		if (doAddComments()) {
			String string= CodeGeneration.getFieldComment(rewrite.getCu(), varType.getName(), fieldNames[i], StubUtility.getLineDelimiterUsed(fCu));
			if (string != null) {
				Javadoc javadoc= (Javadoc) astRewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
				field.setJavadoc(javadoc);
			}
		}

		newBodyDeclarations.add(field);

		addLinkedPosition(KEY_FIELD_NAME_EXT + i, fragment.getName(), astRewrite, false);
	}
}
 
Example 2
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private FieldDeclaration createField(ParameterInfo pi, CompilationUnitRewrite cuRewrite) throws CoreException {
	AST ast= cuRewrite.getAST();
	ICompilationUnit unit= cuRewrite.getCu();

	VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
	String lineDelim= StubUtility.getLineDelimiterUsed(unit);
	SimpleName fieldName= ast.newSimpleName(pi.getNewName());
	fragment.setName(fieldName);
	FieldDeclaration declaration= ast.newFieldDeclaration(fragment);
	if (createComments(unit.getJavaProject())) {
		String comment= StubUtility.getFieldComment(unit, pi.getNewTypeName(), pi.getNewName(), lineDelim);
		if (comment != null) {
			Javadoc doc= (Javadoc) cuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC);
			declaration.setJavadoc(doc);
		}
	}
	List<Modifier> modifiers= new ArrayList<Modifier>();
	if (fCreateGetter) {
		modifiers.add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD));
	} else {
		modifiers.add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
	}
	declaration.modifiers().addAll(modifiers);
	declaration.setType(importBinding(pi.getNewTypeBinding(), cuRewrite));
	return declaration;
}
 
Example 3
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Generates the initializer for an iterator based <code>for</code> loop, which declares and
 * initializes the variable to loop over.
 * 
 * @param rewrite the instance of {@link ASTRewrite}
 * @param loopVariableName the proposed name of the loop variable
 * @return a {@link VariableDeclarationExpression} to use as initializer
 */
private VariableDeclarationExpression getIteratorBasedForInitializer(ASTRewrite rewrite, SimpleName loopVariableName) {
	AST ast= rewrite.getAST();
	IMethodBinding iteratorMethodBinding= Bindings.findMethodInHierarchy(fExpressionType, "iterator", new ITypeBinding[] {}); //$NON-NLS-1$
	// initializing fragment
	VariableDeclarationFragment varDeclarationFragment= ast.newVariableDeclarationFragment();
	varDeclarationFragment.setName(loopVariableName);
	MethodInvocation iteratorExpression= ast.newMethodInvocation();
	iteratorExpression.setName(ast.newSimpleName(iteratorMethodBinding.getName()));
	iteratorExpression.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression));
	varDeclarationFragment.setInitializer(iteratorExpression);

	// declaration
	VariableDeclarationExpression varDeclarationExpression= ast.newVariableDeclarationExpression(varDeclarationFragment);
	varDeclarationExpression.setType(getImportRewrite().addImport(iteratorMethodBinding.getReturnType(), ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite())));

	return varDeclarationExpression;
}
 
Example 4
Source File: AssignToVariableAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private VariableDeclarationFragment addFieldDeclaration(ASTRewrite rewrite, ASTNode newTypeDecl, int modifiers, Expression expression) {
	if (fExistingFragment != null) {
		return fExistingFragment;
	}

	ChildListPropertyDescriptor property= ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
	List<BodyDeclaration> decls= ASTNodes.getBodyDeclarations(newTypeDecl);
	AST ast= newTypeDecl.getAST();
	String[] varNames= suggestFieldNames(fTypeBinding, expression, modifiers);
	for (int i= 0; i < varNames.length; i++) {
		addLinkedPositionProposal(KEY_NAME, varNames[i], null);
	}
	String varName= varNames[0];

	VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment();
	newDeclFrag.setName(ast.newSimpleName(varName));

	FieldDeclaration newDecl= ast.newFieldDeclaration(newDeclFrag);

	Type type= evaluateType(ast);
	newDecl.setType(type);
	newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers));

	ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(getLinkedProposalModel(), rewrite, newDecl.modifiers(), false);

	int insertIndex= findFieldInsertIndex(decls, fNodeToAssign.getStartPosition());
	rewrite.getListRewrite(newTypeDecl, property).insertAt(newDecl, insertIndex, null);

	return newDeclFrag;
}
 
Example 5
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 6
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 7
Source File: ChangeSignatureProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected VariableDeclaration createNewParamgument(ParameterInfo info, List<ParameterInfo> parameterInfos, List<VariableDeclaration> nodes) {
	List<VariableDeclaration> parameters= fLambdaDecl.parameters();
	if (!parameters.isEmpty() && parameters.get(0) instanceof SingleVariableDeclaration) {
		return createNewSingleVariableDeclaration(info);
	}
	VariableDeclarationFragment newP= getASTRewrite().getAST().newVariableDeclarationFragment();
	newP.setName(getASTRewrite().getAST().newSimpleName(info.getNewName()));
	return newP;
}
 
Example 8
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 9
Source File: PushDownRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private FieldDeclaration createNewFieldDeclarationNode(MemberActionInfo info, CompilationUnit declaringCuNode, TypeVariableMaplet[] mapping, ASTRewrite rewrite, VariableDeclarationFragment oldFieldFragment) throws JavaModelException {
	Assert.isTrue(info.isFieldInfo());
	IField field= (IField) info.getMember();
	AST ast= rewrite.getAST();
	VariableDeclarationFragment newFragment= ast.newVariableDeclarationFragment();
	copyExtraDimensions(oldFieldFragment, newFragment);
	Expression initializer= oldFieldFragment.getInitializer();
	if (initializer != null) {
		Expression newInitializer= null;
		if (mapping.length > 0)
			newInitializer= createPlaceholderForExpression(initializer, field.getCompilationUnit(), mapping, rewrite);
		else
			newInitializer= createPlaceholderForExpression(initializer, field.getCompilationUnit(), rewrite);
		newFragment.setInitializer(newInitializer);
	}
	newFragment.setName(ast.newSimpleName(oldFieldFragment.getName().getIdentifier()));
	FieldDeclaration newField= ast.newFieldDeclaration(newFragment);
	FieldDeclaration oldField= ASTNodeSearchUtil.getFieldDeclarationNode(field, declaringCuNode);
	if (info.copyJavadocToCopiesInSubclasses())
		copyJavadocNode(rewrite, oldField, newField);
	copyAnnotations(oldField, newField);
	newField.modifiers().addAll(ASTNodeFactory.newModifiers(ast, info.getNewModifiersForCopyInSubclass(oldField.getModifiers())));
	Type oldType= oldField.getType();
	ICompilationUnit cu= field.getCompilationUnit();
	Type newType= null;
	if (mapping.length > 0) {
		newType= createPlaceholderForType(oldType, cu, mapping, rewrite);
	} else
		newType= createPlaceholderForType(oldType, cu, rewrite);
	newField.setType(newType);
	return newField;
}
 
Example 10
Source File: AccessorClassModifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private FieldDeclaration getNewFinalStringFieldDeclaration(String name) {
	VariableDeclarationFragment variableDeclarationFragment= fAst.newVariableDeclarationFragment();
	variableDeclarationFragment.setName(fAst.newSimpleName(name));

	FieldDeclaration fieldDeclaration= fAst.newFieldDeclaration(variableDeclarationFragment);
	fieldDeclaration.setType(fAst.newSimpleType(fAst.newSimpleName("String"))); //$NON-NLS-1$
	fieldDeclaration.modifiers().add(fAst.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
	fieldDeclaration.modifiers().add(fAst.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));

	return fieldDeclaration;
}
 
Example 11
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 12
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public boolean visit(final PostfixExpression node) {
  final AST dummyAST = AST.newAST(node.getAST().apiLevel());
  final PostfixExpression.Operator pfOperator = node.getOperator();
  Expression _operand = node.getOperand();
  if ((_operand instanceof ArrayAccess)) {
    Expression _operand_1 = node.getOperand();
    final ArrayAccess pfOperand = ((ArrayAccess) _operand_1);
    if ((Objects.equal(pfOperator, PostfixExpression.Operator.INCREMENT) || 
      Objects.equal(pfOperator, PostfixExpression.Operator.DECREMENT))) {
      final String arrayName = this.computeArrayName(pfOperand);
      StringConcatenation _builder = new StringConcatenation();
      _builder.append("_postIndx_");
      _builder.append(arrayName);
      final String idxName = _builder.toString();
      StringConcatenation _builder_1 = new StringConcatenation();
      _builder_1.append("_postVal_");
      _builder_1.append(arrayName);
      final String tempVarName = _builder_1.toString();
      StringConcatenation _builder_2 = new StringConcatenation();
      _builder_2.append("{ var ");
      _builder_2.append(idxName);
      _builder_2.append("=");
      this.appendToBuffer(_builder_2.toString());
      pfOperand.getIndex().accept(this);
      StringConcatenation _builder_3 = new StringConcatenation();
      _builder_3.append(" ");
      _builder_3.append("var  ");
      this.appendToBuffer(_builder_3.toString());
      final VariableDeclarationFragment varDeclaration = dummyAST.newVariableDeclarationFragment();
      varDeclaration.setName(dummyAST.newSimpleName(tempVarName));
      ASTNode _copySubtree = ASTNode.copySubtree(dummyAST, pfOperand);
      final ArrayAccess arrayAccess = ((ArrayAccess) _copySubtree);
      arrayAccess.setIndex(dummyAST.newSimpleName(idxName));
      varDeclaration.setInitializer(arrayAccess);
      varDeclaration.accept(this);
      final InfixExpression infixOp = dummyAST.newInfixExpression();
      infixOp.setLeftOperand(dummyAST.newSimpleName(tempVarName));
      PostfixExpression.Operator _operator = node.getOperator();
      boolean _equals = Objects.equal(_operator, PostfixExpression.Operator.DECREMENT);
      if (_equals) {
        infixOp.setOperator(InfixExpression.Operator.MINUS);
      } else {
        infixOp.setOperator(InfixExpression.Operator.PLUS);
      }
      infixOp.setRightOperand(dummyAST.newNumberLiteral("1"));
      final Assignment assigment = dummyAST.newAssignment();
      ASTNode _copySubtree_1 = ASTNode.copySubtree(dummyAST, pfOperand);
      final ArrayAccess writeArray = ((ArrayAccess) _copySubtree_1);
      writeArray.setIndex(dummyAST.newSimpleName(idxName));
      assigment.setLeftHandSide(writeArray);
      ASTNode _copySubtree_2 = ASTNode.copySubtree(dummyAST, infixOp);
      assigment.setRightHandSide(((Expression) _copySubtree_2));
      assigment.accept(this);
      StringConcatenation _builder_4 = new StringConcatenation();
      String _xifexpression = null;
      boolean _needsReturnValue = this._aSTFlattenerUtils.needsReturnValue(node);
      if (_needsReturnValue) {
        _xifexpression = tempVarName;
      }
      _builder_4.append(_xifexpression);
      _builder_4.append(" }");
      this.appendToBuffer(_builder_4.toString());
      return false;
    }
  }
  node.getOperand().accept(this);
  this.appendToBuffer(pfOperator.toString());
  return false;
}
 
Example 13
Source File: ExtractConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void createConstantDeclaration() throws CoreException {
	Type type= getConstantType();

	IExpressionFragment fragment= getSelectedExpression();
	Expression initializer= getSelectedExpression().createCopyTarget(fCuRewrite.getASTRewrite(), true);

	AST ast= fCuRewrite.getAST();
	VariableDeclarationFragment variableDeclarationFragment= ast.newVariableDeclarationFragment();
	variableDeclarationFragment.setName(ast.newSimpleName(fConstantName));
	variableDeclarationFragment.setInitializer(initializer);

	FieldDeclaration fieldDeclaration= ast.newFieldDeclaration(variableDeclarationFragment);
	fieldDeclaration.setType(type);
	Modifier.ModifierKeyword accessModifier= Modifier.ModifierKeyword.toKeyword(fVisibility);
	if (accessModifier != null)
		fieldDeclaration.modifiers().add(ast.newModifier(accessModifier));
	fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));
	fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD));

	boolean createComments= JavaPreferencesSettings.getCodeGenerationSettings(fCu.getJavaProject()).createComments;
	if (createComments) {
		String comment= CodeGeneration.getFieldComment(fCu, getConstantTypeName(), fConstantName, StubUtility.getLineDelimiterUsed(fCu));
		if (comment != null && comment.length() > 0) {
			Javadoc doc= (Javadoc) fCuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC);
			fieldDeclaration.setJavadoc(doc);
		}
	}

	AbstractTypeDeclaration parent= getContainingTypeDeclarationNode();
	ListRewrite listRewrite= fCuRewrite.getASTRewrite().getListRewrite(parent, parent.getBodyDeclarationsProperty());
	TextEditGroup msg= fCuRewrite.createGroupDescription(RefactoringCoreMessages.ExtractConstantRefactoring_declare_constant);
	if (insertFirst()) {
		listRewrite.insertFirst(fieldDeclaration, msg);
	} else {
		listRewrite.insertAfter(fieldDeclaration, getNodeToInsertConstantDeclarationAfter(), msg);
	}

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

		String[] nameSuggestions= guessConstantNames();
		if (nameSuggestions.length > 0 && !nameSuggestions[0].equals(fConstantName)) {
			nameGroup.addProposal(fConstantName, null, nameSuggestions.length + 1);
		}
		for (int i= 0; i < nameSuggestions.length; i++) {
			nameGroup.addProposal(nameSuggestions[i], null, nameSuggestions.length - i);
		}

		LinkedProposalPositionGroup typeGroup= fLinkedProposalModel.getPositionGroup(KEY_TYPE, true);
		typeGroup.addPosition(rewrite.track(type), true);

		ITypeBinding typeBinding= guessBindingForReference(fragment.getAssociatedExpression());
		if (typeBinding != null) {
			ITypeBinding[] relaxingTypes= ASTResolving.getNarrowingTypes(ast, typeBinding);
			for (int i= 0; i < relaxingTypes.length; i++) {
				typeGroup.addProposal(relaxingTypes[i], fCuRewrite.getCu(), relaxingTypes.length - i);
			}
		}
		boolean isInterface= parent.resolveBinding() != null && parent.resolveBinding().isInterface();
		ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(fLinkedProposalModel, rewrite, fieldDeclaration.modifiers(), isInterface);
	}
}
 
Example 14
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 15
Source File: ExtractConstantRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private void createConstantDeclaration() throws CoreException {
	Type type = getConstantType();

	IExpressionFragment fragment = getSelectedExpression();
	Expression initializer = getSelectedExpression().createCopyTarget(fCuRewrite.getASTRewrite(), true);

	AST ast = fCuRewrite.getAST();
	VariableDeclarationFragment variableDeclarationFragment = ast.newVariableDeclarationFragment();
	variableDeclarationFragment.setName(ast.newSimpleName(fConstantName));
	variableDeclarationFragment.setInitializer(initializer);

	FieldDeclaration fieldDeclaration = ast.newFieldDeclaration(variableDeclarationFragment);
	fieldDeclaration.setType(type);
	Modifier.ModifierKeyword accessModifier = Modifier.ModifierKeyword.toKeyword(fVisibility);
	if (accessModifier != null) {
		fieldDeclaration.modifiers().add(ast.newModifier(accessModifier));
	}
	fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.STATIC_KEYWORD));
	fieldDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD));

	//		boolean createComments = JavaPreferencesSettings.getCodeGenerationSettings(fCu.getJavaProject()).createComments;
	//		if (createComments) {
	String comment = CodeGeneration.getFieldComment(fCu, getConstantTypeName(), fConstantName, StubUtility.getLineDelimiterUsed(fCu));
	if (comment != null && comment.length() > 0 && !"/**\n *\n */".equals(comment)) {
		Javadoc doc = (Javadoc) fCuRewrite.getASTRewrite().createStringPlaceholder(comment, ASTNode.JAVADOC);
		fieldDeclaration.setJavadoc(doc);
	}
	//		}

	AbstractTypeDeclaration parent = getContainingTypeDeclarationNode();
	ListRewrite listRewrite = fCuRewrite.getASTRewrite().getListRewrite(parent, parent.getBodyDeclarationsProperty());
	TextEditGroup msg = fCuRewrite.createGroupDescription(RefactoringCoreMessages.ExtractConstantRefactoring_declare_constant);
	if (insertFirst()) {
		listRewrite.insertFirst(fieldDeclaration, msg);
	} else {
		listRewrite.insertAfter(fieldDeclaration, getNodeToInsertConstantDeclarationAfter(), msg);
	}

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

		String[] nameSuggestions = guessConstantNames();
		if (nameSuggestions.length > 0 && !nameSuggestions[0].equals(fConstantName)) {
			nameGroup.addProposal(fConstantName, nameSuggestions.length + 1);
		}
		for (int i = 0; i < nameSuggestions.length; i++) {
			nameGroup.addProposal(nameSuggestions[i], nameSuggestions.length - i);
		}

		LinkedProposalPositionGroupCore typeGroup = fLinkedProposalModel.getPositionGroup(KEY_TYPE, true);
		typeGroup.addPosition(rewrite.track(type), true);

		ITypeBinding typeBinding = guessBindingForReference(fragment.getAssociatedExpression());
		if (typeBinding != null) {
			ITypeBinding[] relaxingTypes = ASTResolving.getNarrowingTypes(ast, typeBinding);
			for (int i = 0; i < relaxingTypes.length; i++) {
				typeGroup.addProposal(relaxingTypes[i], fCuRewrite.getCu(), relaxingTypes.length - i);
			}
		}
		boolean isInterface = parent.resolveBinding() != null && parent.resolveBinding().isInterface();
		ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(fLinkedProposalModel, rewrite, fieldDeclaration.modifiers(), isInterface);
	}
}
 
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 doAddField(CompilationUnit astRoot) {
	SimpleName node= fOriginalNode;
	boolean isInDifferentCU= false;

	ASTNode newTypeDecl= astRoot.findDeclaringNode(fSenderBinding);
	if (newTypeDecl == null) {
		astRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
		newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
		isInDifferentCU= true;
	}
	ImportRewrite imports= createImportRewrite(astRoot);
	ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(node), imports);

	if (newTypeDecl != null) {
		AST ast= newTypeDecl.getAST();

		ASTRewrite rewrite= ASTRewrite.create(ast);

		VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
		fragment.setName(ast.newSimpleName(node.getIdentifier()));

		Type type= evaluateVariableType(ast, imports, importRewriteContext, fSenderBinding);

		FieldDeclaration newDecl= ast.newFieldDeclaration(fragment);
		newDecl.setType(type);
		newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, evaluateFieldModifiers(newTypeDecl)));

		if (fSenderBinding.isInterface() || fVariableKind == CONST_FIELD) {
			fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0));
		}

		ChildListPropertyDescriptor property= ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
		List<BodyDeclaration> decls= ASTNodes.<BodyDeclaration>getChildListProperty(newTypeDecl, property);

		int maxOffset= isInDifferentCU ? -1 : node.getStartPosition();

		int insertIndex= findFieldInsertIndex(decls, newDecl, maxOffset);

		ListRewrite listRewriter= rewrite.getListRewrite(newTypeDecl, property);
		listRewriter.insertAt(newDecl, insertIndex, null);

		ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(getLinkedProposalModel(), rewrite, newDecl.modifiers(), fSenderBinding.isInterface());

		addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
		if (!isInDifferentCU) {
			addLinkedPosition(rewrite.track(node), true, KEY_NAME);
		}
		addLinkedPosition(rewrite.track(fragment.getName()), false, KEY_NAME);

		if (fragment.getInitializer() != null) {
			addLinkedPosition(rewrite.track(fragment.getInitializer()), false, KEY_INITIALIZER);
		}
		return rewrite;
	}
	return null;
}
 
Example 17
Source File: AbstractSerialVersionOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException {
	final ASTRewrite rewrite= cuRewrite.getASTRewrite();
	VariableDeclarationFragment fragment= null;
	for (int i= 0; i < fNodes.length; i++) {
		final ASTNode node= fNodes[i];

		final AST ast= node.getAST();

		fragment= ast.newVariableDeclarationFragment();
		fragment.setName(ast.newSimpleName(NAME_FIELD));

		final FieldDeclaration declaration= ast.newFieldDeclaration(fragment);
		declaration.setType(ast.newPrimitiveType(PrimitiveType.LONG));
		declaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL));

		if (!addInitializer(fragment, node))
			continue;

		if (fragment.getInitializer() != null) {

			final TextEditGroup editGroup= createTextEditGroup(FixMessages.SerialVersion_group_description, cuRewrite);
			if (node instanceof AbstractTypeDeclaration)
				rewrite.getListRewrite(node, ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty()).insertAt(declaration, 0, editGroup);
			else if (node instanceof AnonymousClassDeclaration)
				rewrite.getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup);
			else if (node instanceof ParameterizedType) {
				final ParameterizedType type= (ParameterizedType) node;
				final ASTNode parent= type.getParent();
				if (parent instanceof ClassInstanceCreation) {
					final ClassInstanceCreation creation= (ClassInstanceCreation) parent;
					final AnonymousClassDeclaration anonymous= creation.getAnonymousClassDeclaration();
					if (anonymous != null)
						rewrite.getListRewrite(anonymous, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup);
				}
			} else
				Assert.isTrue(false);

			addLinkedPositions(rewrite, fragment, positionGroups);
		}

		final String comment= CodeGeneration.getFieldComment(fUnit, declaration.getType().toString(), NAME_FIELD, StubUtility.getLineDelimiterUsed(fUnit));
		if (comment != null && comment.length() > 0) {
			final Javadoc doc= (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC);
			declaration.setJavadoc(doc);
		}
	}
	if (fragment == null)
		return;

	positionGroups.setEndPosition(rewrite.track(fragment));
}
 
Example 18
Source File: CreateFieldOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
protected SimpleName rename(ASTNode node, SimpleName newName) {
	VariableDeclarationFragment fragment = getFragment(node);
	SimpleName oldName = fragment.getName();
	fragment.setName(newName);
	return oldName;
}
 
Example 19
Source File: BuilderFieldAdderFragment.java    From SparkBuilderGenerator with MIT License 4 votes vote down vote up
private VariableDeclarationFragment createFieldDeclarationFragment(AST ast, BuilderField builderField) {
    VariableDeclarationFragment variableDeclarationFragment = ast.newVariableDeclarationFragment();
    variableDeclarationFragment.setName(ast.newSimpleName(builderField.getOriginalFieldName()));
    return fieldDeclarationPostProcessor.postProcessFragment(ast, builderField, variableDeclarationFragment);
}
 
Example 20
Source File: EnsuresPredicateFix.java    From CogniCrypt with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * This method builds a {@link VariableDeclarationFragment} object (i.e. "iv = ...")
 * 
 * @param ast - current ast
 * @param variableName - declaration variable
 * @param initializer - initializer for the variable
 * @return VariableDeclarationFragment obj
 */
private VariableDeclarationFragment createEnsurerVariableDeclarationFragment(final AST ast, final String variableName, final Expression initializer) {
	final VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment();
	fragment.setName(ast.newSimpleName(variableName));
	fragment.setInitializer(initializer);
	return fragment;
}