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

The following examples show how to use org.eclipse.jdt.core.dom.VariableDeclarationFragment#setInitializer() . 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: PromoteTempToFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private FieldDeclaration createNewFieldDeclaration(ASTRewrite rewrite) {
AST ast= getAST();
VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
SimpleName variableName= ast.newSimpleName(fFieldName);
fragment.setName(variableName);
addLinkedName(rewrite, variableName, false);
List<Dimension> extraDimensions= DimensionRewrite.copyDimensions(fTempDeclarationNode.extraDimensions(), rewrite);
fragment.extraDimensions().addAll(extraDimensions);
if (fInitializeIn == INITIALIZE_IN_FIELD && tempHasInitializer()){
    Expression initializer= (Expression)rewrite.createCopyTarget(getTempInitializer());
    fragment.setInitializer(initializer);
}
FieldDeclaration fieldDeclaration= ast.newFieldDeclaration(fragment);

VariableDeclarationStatement vds= getTempDeclarationStatement();
Type type= (Type)rewrite.createCopyTarget(vds.getType());
fieldDeclaration.setType(type);
fieldDeclaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getModifiers()));
return fieldDeclaration;
  }
 
Example 2
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 3
Source File: HierarchyProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected static FieldDeclaration createNewFieldDeclarationNode(final ASTRewrite rewrite, final CompilationUnit unit, final IField field, final VariableDeclarationFragment oldFieldFragment, final TypeVariableMaplet[] mapping, final IProgressMonitor monitor, final RefactoringStatus status, final int modifiers) throws JavaModelException {
	final VariableDeclarationFragment newFragment= rewrite.getAST().newVariableDeclarationFragment();
	copyExtraDimensions(oldFieldFragment, newFragment);
	if (oldFieldFragment.getInitializer() != null) {
		Expression newInitializer= null;
		if (mapping.length > 0)
			newInitializer= createPlaceholderForExpression(oldFieldFragment.getInitializer(), field.getCompilationUnit(), mapping, rewrite);
		else
			newInitializer= createPlaceholderForExpression(oldFieldFragment.getInitializer(), field.getCompilationUnit(), rewrite);
		newFragment.setInitializer(newInitializer);
	}
	newFragment.setName(((SimpleName) ASTNode.copySubtree(rewrite.getAST(), oldFieldFragment.getName())));
	final FieldDeclaration newField= rewrite.getAST().newFieldDeclaration(newFragment);
	final FieldDeclaration oldField= ASTNodeSearchUtil.getFieldDeclarationNode(field, unit);
	copyJavadocNode(rewrite, oldField, newField);
	copyAnnotations(oldField, newField);
	newField.modifiers().addAll(ASTNodeFactory.newModifiers(rewrite.getAST(), modifiers));
	final Type oldType= oldField.getType();
	Type newType= null;
	if (mapping.length > 0) {
		newType= createPlaceholderForType(oldType, field.getCompilationUnit(), mapping, rewrite);
	} else
		newType= createPlaceholderForType(oldType, field.getCompilationUnit(), rewrite);
	newField.setType(newType);
	return newField;
}
 
Example 4
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 5
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Generates a {@link VariableDeclarationExpression}, which initializes the loop variable to
 * iterate over an array.
 * 
 * @param ast the current {@link AST} instance
 * @param loopVariableName the name of the variable which should be initialized
 * @return a filled {@link VariableDeclarationExpression}, declaring a int variable, which is
 *         initializes with 0
 */
private VariableDeclarationExpression getForInitializer(AST ast, SimpleName loopVariableName) {
	// initializing fragment
	VariableDeclarationFragment firstDeclarationFragment= ast.newVariableDeclarationFragment();
	firstDeclarationFragment.setName(loopVariableName);
	NumberLiteral startIndex= ast.newNumberLiteral();
	firstDeclarationFragment.setInitializer(startIndex);

	// declaration
	VariableDeclarationExpression variableDeclaration= ast.newVariableDeclarationExpression(firstDeclarationFragment);
	PrimitiveType variableType= ast.newPrimitiveType(PrimitiveType.INT);
	variableDeclaration.setType(variableType);

	return variableDeclaration;
}
 
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: 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 8
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ExpressionStatement createInitializer(ParameterInfo pi, String paramName, CompilationUnitRewrite cuRewrite) {
	AST ast= cuRewrite.getAST();

	VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
	fragment.setName(ast.newSimpleName(pi.getOldName()));
	fragment.setInitializer(createFieldReadAccess(pi, paramName, ast, cuRewrite.getCu().getJavaProject(), false, null));
	VariableDeclarationExpression declaration= ast.newVariableDeclarationExpression(fragment);
	IVariableBinding variable= pi.getOldBinding();
	declaration.setType(importBinding(pi.getNewTypeBinding(), cuRewrite));
	int modifiers= variable.getModifiers();
	List<Modifier> newModifiers= ast.newModifiers(modifiers);
	declaration.modifiers().addAll(newModifiers);
	return ast.newExpressionStatement(declaration);
}
 
Example 9
Source File: JavaStatementPostfixContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private VariableDeclarationFragment addFieldDeclaration(ASTRewrite rewrite, org.eclipse.jdt.core.dom.ASTNode newTypeDecl, int modifiers, String varName, String qualifiedName, String value) {

		ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
		List<BodyDeclaration> decls = ASTNodes.getBodyDeclarations(newTypeDecl);
		AST ast = newTypeDecl.getAST();
		
		VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
		newDeclFrag.setName(ast.newSimpleName(varName));
		
		Type type = createType(Signature.createTypeSignature(qualifiedName, true), ast);
		
		if (value != null && value.trim().length() > 0) {
			Expression e = createExpression(value);
			Expression ne = (Expression) org.eclipse.jdt.core.dom.ASTNode.copySubtree(ast, e);
			newDeclFrag.setInitializer(ne);
			
		} else {
			if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)) {
				newDeclFrag.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0));
			}
		}

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

		int insertIndex = findFieldInsertIndex(decls, getCompletionOffset(), modifiers);
		rewrite.getListRewrite(newTypeDecl, property).insertAt(newDecl, insertIndex, null);
		
		return newDeclFrag;
	}
 
Example 10
Source File: PotentialProgrammingProblemsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected boolean addInitializer(VariableDeclarationFragment fragment, ASTNode declarationNode) {
	ITypeBinding typeBinding= getTypeBinding(declarationNode);
	if (typeBinding == null)
		return false;

	Long id= fContext.getSerialVersionId(typeBinding);
	if (id == null)
		return false;

	fragment.setInitializer(fragment.getAST().newNumberLiteral(id.toString() + LONG_SUFFIX));
	return true;
}
 
Example 11
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 12
Source File: SerialVersionDefaultOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected boolean addInitializer(final VariableDeclarationFragment fragment, final ASTNode declarationNode) {
	Assert.isNotNull(fragment);

	final Expression expression= fragment.getAST().newNumberLiteral(DEFAULT_EXPRESSION);
	if (expression != null)
		fragment.setInitializer(expression);
	return true;
}
 
Example 13
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 14
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 15
Source File: ExtractClassRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private FieldDeclaration createParameterObjectField(ParameterObjectFactory pof, TypeDeclaration typeNode, int modifier) {
	AST ast= fBaseCURewrite.getAST();
	ClassInstanceCreation creation= ast.newClassInstanceCreation();
	creation.setType(pof.createType(fDescriptor.isCreateTopLevel(), fBaseCURewrite, typeNode.getStartPosition()));
	ListRewrite listRewrite= fBaseCURewrite.getASTRewrite().getListRewrite(creation, ClassInstanceCreation.ARGUMENTS_PROPERTY);
	for (Iterator<FieldInfo> iter= fVariables.values().iterator(); iter.hasNext();) {
		FieldInfo fi= iter.next();
		if (isCreateField(fi)) {
			Expression expression= fi.initializer;
			if (expression != null && !fi.hasFieldReference()) {
				importNodeTypes(expression, fBaseCURewrite);
				ASTNode createMoveTarget= fBaseCURewrite.getASTRewrite().createMoveTarget(expression);
				if (expression instanceof ArrayInitializer) {
					ArrayInitializer ai= (ArrayInitializer) expression;
					ITypeBinding type= ai.resolveTypeBinding();
					Type addImport= fBaseCURewrite.getImportRewrite().addImport(type, ast);
					fBaseCURewrite.getImportRemover().registerAddedImports(addImport);
					ArrayCreation arrayCreation= ast.newArrayCreation();
					arrayCreation.setType((ArrayType) addImport);
					arrayCreation.setInitializer((ArrayInitializer) createMoveTarget);
					listRewrite.insertLast(arrayCreation, null);
				} else {
					listRewrite.insertLast(createMoveTarget, null);
				}
			}
		}
	}

	VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
	fragment.setName(ast.newSimpleName(fDescriptor.getFieldName()));
	fragment.setInitializer(creation);

	ModifierKeyword acc= null;
	if (Modifier.isPublic(modifier)) {
		acc= ModifierKeyword.PUBLIC_KEYWORD;
	} else if (Modifier.isProtected(modifier)) {
		acc= ModifierKeyword.PROTECTED_KEYWORD;
	} else if (Modifier.isPrivate(modifier)) {
		acc= ModifierKeyword.PRIVATE_KEYWORD;
	}

	FieldDeclaration fieldDeclaration= ast.newFieldDeclaration(fragment);
	fieldDeclaration.setType(pof.createType(fDescriptor.isCreateTopLevel(), fBaseCURewrite, typeNode.getStartPosition()));
	if (acc != null)
		fieldDeclaration.modifiers().add(ast.newModifier(acc));
	return fieldDeclaration;
}
 
Example 16
Source File: NewVariableCorrectionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.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, TypeLocation.FIELD);

		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);

		return rewrite;
	}
	return null;
}
 
Example 17
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 18
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 19
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 20
Source File: FieldDeclarationPostProcessor.java    From SparkBuilderGenerator with MIT License 4 votes vote down vote up
private void postProcessUsingChainItem(AST ast, FieldDeclarationPostProcessorChainItem chainItemToUse, VariableDeclarationFragment variableDeclarationFragment,
        String fullyQualifiedName) {
    Expression expression = chainItemToUse.createExpression(ast, fullyQualifiedName);
    variableDeclarationFragment.setInitializer(expression);
    importRepository.addImports(chainItemToUse.getImport(fullyQualifiedName));
}