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

The following examples show how to use org.eclipse.jdt.core.dom.AST#newFieldDeclaration() . 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: 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 2
Source File: ReplaceTypeCodeWithStateStrategy.java    From JDeodorant with MIT License 6 votes vote down vote up
private void createStateField() {
	ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST());
	AST contextAST = sourceTypeDeclaration.getAST();
	ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
	VariableDeclarationFragment typeFragment = createStateFieldVariableDeclarationFragment(sourceRewriter, contextAST);
	
	FieldDeclaration typeFieldDeclaration = contextAST.newFieldDeclaration(typeFragment);
	sourceRewriter.set(typeFieldDeclaration, FieldDeclaration.TYPE_PROPERTY, contextAST.newSimpleName(abstractClassName), null);
	ListRewrite typeFieldDeclarationModifiersRewrite = sourceRewriter.getListRewrite(typeFieldDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY);
	typeFieldDeclarationModifiersRewrite.insertLast(contextAST.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD), null);
	contextBodyRewrite.insertBefore(typeFieldDeclaration, typeCheckElimination.getTypeField().getParent(), null);
	
	try {
		TextEdit sourceEdit = sourceRewriter.rewriteAST();
		ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
		CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit);
		change.getEdit().addChild(sourceEdit);
		change.addTextEditGroup(new TextEditGroup("Create field holding the current state", new TextEdit[] {sourceEdit}));
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
}
 
Example 3
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 4
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 5
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addEnclosingInstanceDeclaration(final AbstractTypeDeclaration declaration, final ASTRewrite rewrite) throws CoreException {
	Assert.isNotNull(declaration);
	Assert.isNotNull(rewrite);
	final AST ast= declaration.getAST();
	final VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment();
	fragment.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
	final FieldDeclaration newField= ast.newFieldDeclaration(fragment);
	newField.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getEnclosingInstanceAccessModifiers()));
	newField.setType(createEnclosingType(ast));
	final String comment= CodeGeneration.getFieldComment(fType.getCompilationUnit(), declaration.getName().getIdentifier(), fEnclosingInstanceFieldName, StubUtility.getLineDelimiterUsed(fType.getJavaProject()));
	if (comment != null && comment.length() > 0) {
		final Javadoc doc= (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC);
		newField.setJavadoc(doc);
	}
	rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertFirst(newField, null);
}
 
Example 6
Source File: ExtractFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private FieldDeclaration createNewFieldDeclaration(ASTRewrite rewrite) throws CoreException {
	AST ast = fCURewrite.getAST();
	VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment();
	SimpleName variableName = ast.newSimpleName(fFieldName);
	fragment.setName(variableName);
	if (fLinkedProposalModel != null) {
		fLinkedProposalModel.getPositionGroup(KEY_NAME, true).addPosition(rewrite.track(variableName), false);
	}

	if (fInitializeIn == INITIALIZE_IN_FIELD) {
		Expression initializer = getSelectedExpression().createCopyTarget(fCURewrite.getASTRewrite(), true);
		fragment.setInitializer(initializer);
	}
	FieldDeclaration fieldDeclaration = ast.newFieldDeclaration(fragment);
	fieldDeclaration.setType(createFieldType());
	fieldDeclaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getModifiers()));
	return fieldDeclaration;
}
 
Example 7
Source File: AssignToVariableAssistProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private VariableDeclarationFragment addFieldDeclaration(ASTRewrite rewrite, ASTNode newTypeDecl, int modifiers, Expression expression, ASTNode nodeToAssign, ITypeBinding typeBinding,
		int index) {
	if (fExistingFragment != null) {
		return fExistingFragment;
	}

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

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

	FieldDeclaration newDecl= ast.newFieldDeclaration(newDeclFrag);

	Type type= evaluateType(ast, nodeToAssign, typeBinding, KEY_TYPE + index, TypeLocation.FIELD);
	newDecl.setType(type);
	newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifiers));

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

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

	return newDeclFrag;
}
 
Example 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
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 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: BuilderFieldAdderFragment.java    From SparkBuilderGenerator with MIT License 4 votes vote down vote up
public void addFieldToBuilder(AST ast, TypeDeclaration builderType, BuilderField builderField) {
    FieldDeclaration fieldDeclaration = ast.newFieldDeclaration(createFieldDeclarationFragment(ast, builderField));
    fieldDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD));
    fieldDeclaration.setType((Type) ASTNode.copySubtree(ast, builderField.getFieldType()));
    builderType.bodyDeclarations().add(findLastFieldIndex(builderType), fieldDeclaration);
}
 
Example 18
Source File: EnsuresPredicateFix.java    From CogniCrypt with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * This method builds a {@link FieldDeclaration} object (i.e. "public iv = ")
 * 
 * @param ast - current ast
 * @param fragment
 * @param type - i.e. PrimitiveType.BOOLEAN
 * @param modifier - i.e. Modifier.PRIVATE
 * @return
 */
private FieldDeclaration createEnsurerFieldDeclaration(final AST ast, final VariableDeclarationFragment varDeclarationFrag, final int modifier) {
	final FieldDeclaration declaration = ast.newFieldDeclaration(varDeclarationFrag);
	declaration.setType(createAstType(INJAR_CLASS_NAME, ast));
	declaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, modifier));
	return declaration;
}