Java Code Examples for org.eclipse.jdt.core.dom.rewrite.ASTRewrite#remove()

The following examples show how to use org.eclipse.jdt.core.dom.rewrite.ASTRewrite#remove() . 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: AssociativeInfixExpressionFragment.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void replace(ASTRewrite rewrite, ASTNode replacement, TextEditGroup textEditGroup) {
	ASTNode groupNode = getGroupRoot();

	List<Expression> allOperands = findGroupMembersInOrderFor(getGroupRoot());
	if (allOperands.size() == fOperands.size()) {
		if (replacement instanceof Name && groupNode.getParent() instanceof ParenthesizedExpression) {
			// replace including the parenthesized expression around it
			rewrite.replace(groupNode.getParent(), replacement, textEditGroup);
		} else {
			rewrite.replace(groupNode, replacement, textEditGroup);
		}
		return;
	}

	rewrite.replace(fOperands.get(0), replacement, textEditGroup);
	int first = allOperands.indexOf(fOperands.get(0));
	int after = first + fOperands.size();
	for (int i = first + 1; i < after; i++) {
		rewrite.remove(allOperands.get(i), textEditGroup);
	}
}
 
Example 2
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel linkedModel) throws CoreException {
	ASTRewrite rewrite= cuRewrite.getASTRewrite();
	IBinding binding= fUnusedName.resolveBinding();
	CompilationUnit root= (CompilationUnit) fUnusedName.getRoot();
	String displayString= FixMessages.UnusedCodeFix_RemoveUnusedTypeParameter_description;
	TextEditGroup group= createTextEditGroup(displayString, cuRewrite);

	if (binding.getKind() == IBinding.TYPE) {
		ITypeBinding decl= ((ITypeBinding) binding).getTypeDeclaration();
		ASTNode declaration= root.findDeclaringNode(decl);
		if (declaration.getParent() instanceof TypeDeclarationStatement) {
			declaration= declaration.getParent();
		}
		rewrite.remove(declaration, group);
	}
}
 
Example 3
Source File: AssociativeInfixExpressionFragment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void replace(ASTRewrite rewrite, ASTNode replacement, TextEditGroup textEditGroup) {
	ASTNode groupNode= getGroupRoot();

	List<Expression> allOperands= findGroupMembersInOrderFor(getGroupRoot());
	if (allOperands.size() == fOperands.size()) {
		if (replacement instanceof Name && groupNode.getParent() instanceof ParenthesizedExpression) {
			// replace including the parenthesized expression around it
			rewrite.replace(groupNode.getParent(), replacement, textEditGroup);
		} else {
			rewrite.replace(groupNode, replacement, textEditGroup);
		}
		return;
	}

	rewrite.replace(fOperands.get(0), replacement, textEditGroup);
	int first= allOperands.indexOf(fOperands.get(0));
	int after= first + fOperands.size();
	for (int i= first + 1; i < after; i++) {
		rewrite.remove(allOperands.get(i), textEditGroup);
	}
}
 
Example 4
Source File: HierarchyProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected static void deleteDeclarationNodes(final CompilationUnitRewrite sourceRewriter, final boolean sameCu, final CompilationUnitRewrite unitRewriter, final List<IMember> members, final GroupCategorySet set) throws JavaModelException {
	final List<ASTNode> declarationNodes= getDeclarationNodes(unitRewriter.getRoot(), members);
	for (final Iterator<ASTNode> iterator= declarationNodes.iterator(); iterator.hasNext();) {
		final ASTNode node= iterator.next();
		final ASTRewrite rewriter= unitRewriter.getASTRewrite();
		final ImportRemover remover= unitRewriter.getImportRemover();
		if (node instanceof VariableDeclarationFragment) {
			if (node.getParent() instanceof FieldDeclaration) {
				final FieldDeclaration declaration= (FieldDeclaration) node.getParent();
				if (areAllFragmentsDeleted(declaration, declarationNodes)) {
					rewriter.remove(declaration, unitRewriter.createCategorizedGroupDescription(RefactoringCoreMessages.HierarchyRefactoring_remove_member, set));
					if (!sameCu)
						remover.registerRemovedNode(declaration);
				} else {
					rewriter.remove(node, unitRewriter.createCategorizedGroupDescription(RefactoringCoreMessages.HierarchyRefactoring_remove_member, set));
					if (!sameCu)
						remover.registerRemovedNode(node);
				}
			}
		} else {
			rewriter.remove(node, unitRewriter.createCategorizedGroupDescription(RefactoringCoreMessages.HierarchyRefactoring_remove_member, set));
			if (!sameCu)
				remover.registerRemovedNode(node);
		}
	}
}
 
Example 5
Source File: DeleteMethodProposal.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected ASTRewrite getRewrite() throws CoreException {
  CompilationUnit targetAstRoot = ASTResolving.createQuickFixAST(
      getCompilationUnit(), null);
  createImportRewrite(targetAstRoot);

  ASTRewrite rewrite = ASTRewrite.create(targetAstRoot.getAST());

  // Find the method declaration in the AST we just generated (the one that
  // the AST rewriter is hooked up to).
  MethodDeclaration rewriterAstMethodDecl = JavaASTUtils.findMethodDeclaration(
      targetAstRoot, methodDecl.resolveBinding().getKey());
  if (rewriterAstMethodDecl == null) {
    return null;
  }

  // Remove the extra method declaration
  rewrite.remove(rewriterAstMethodDecl, null);

  return rewrite;
}
 
Example 6
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void addRedundantSuperInterfaceProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (!(selectedNode instanceof Name)) {
		return;
	}
	ASTNode node= ASTNodes.getNormalizedNode(selectedNode);

	ASTRewrite rewrite= ASTRewrite.create(node.getAST());
	rewrite.remove(node, null);

	String label= CorrectionMessages.LocalCorrectionsSubProcessor_remove_redundant_superinterface;
	Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);

	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_REDUNDANT_SUPER_INTERFACE, image);
	proposals.add(proposal);

}
 
Example 7
Source File: RemoveDeclarationCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void removeVariableWithInitializer(ASTRewrite rewrite, ASTNode initializerNode, ASTNode statementNode) {
	ArrayList<Expression> sideEffectNodes= new ArrayList<Expression>();
	initializerNode.accept(new SideEffectFinder(sideEffectNodes));
	int nSideEffects= sideEffectNodes.size();
	if (nSideEffects == 0) {
		if (ASTNodes.isControlStatementBody(statementNode.getLocationInParent())) {
			rewrite.replace(statementNode, rewrite.getAST().newBlock(), null);
		} else {
			rewrite.remove(statementNode, null);
		}
	} else {
		// do nothing yet
	}
}
 
Example 8
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void removeParamTag(ASTRewrite rewrite, SingleVariableDeclaration varDecl, TextEditGroup group) {
	if (varDecl.getParent() instanceof MethodDeclaration) {
		Javadoc javadoc= ((MethodDeclaration) varDecl.getParent()).getJavadoc();
		if (javadoc != null) {
			TagElement tagElement= JavadocTagsSubProcessor.findParamTag(javadoc, varDecl.getName().getIdentifier());
			if (tagElement != null) {
				rewrite.remove(tagElement, group);
			}
		}
	}
}
 
Example 9
Source File: LocalCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static void addRedundantSuperInterfaceProposal(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) {
	ASTNode selectedNode = problem.getCoveringNode(context.getASTRoot());
	if (!(selectedNode instanceof Name)) {
		return;
	}
	ASTNode node = ASTNodes.getNormalizedNode(selectedNode);
	ASTRewrite rewrite = ASTRewrite.create(node.getAST());
	rewrite.remove(node, null);
	String label = CorrectionMessages.LocalCorrectionsSubProcessor_remove_redundant_superinterface;
	ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_REDUNDANT_SUPER_INTERFACE);
	proposals.add(proposal);
}
 
Example 10
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void removeStatement(ASTRewrite rewrite, ASTNode statementNode, TextEditGroup group) {
	if (ASTNodes.isControlStatementBody(statementNode.getLocationInParent())) {
		rewrite.replace(statementNode, rewrite.getAST().newBlock(), group);
	} else {
		rewrite.remove(statementNode, group);
	}
}
 
Example 11
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void updateConstructorReference(final ClassInstanceCreation creation, final CompilationUnitRewrite targetRewrite, final ICompilationUnit unit, TextEditGroup group) throws JavaModelException {
	Assert.isNotNull(creation);
	Assert.isNotNull(targetRewrite);
	Assert.isNotNull(unit);
	final ASTRewrite rewrite= targetRewrite.getASTRewrite();
	if (fCreateInstanceField)
		insertExpressionAsParameter(creation, rewrite, unit, group);
	final Expression expression= creation.getExpression();
	if (expression != null) {
		rewrite.remove(expression, null);
		targetRewrite.getImportRemover().registerRemovedNode(expression);
	}
}
 
Example 12
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void updateConstructorReference(final SuperConstructorInvocation invocation, final CompilationUnitRewrite targetRewrite, final ICompilationUnit unit, TextEditGroup group) throws CoreException {
	Assert.isNotNull(invocation);
	Assert.isNotNull(targetRewrite);
	Assert.isNotNull(unit);
	final ASTRewrite rewrite= targetRewrite.getASTRewrite();
	if (fCreateInstanceField)
		insertExpressionAsParameter(invocation, rewrite, unit, group);
	final Expression expression= invocation.getExpression();
	if (expression != null) {
		rewrite.remove(expression, null);
		targetRewrite.getImportRemover().registerRemovedNode(expression);
	}
}
 
Example 13
Source File: InlineTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void removeTemp(CompilationUnitRewrite cuRewrite) {
	VariableDeclaration variableDeclaration= getVariableDeclaration();
	TextEditGroup groupDesc= cuRewrite.createGroupDescription(RefactoringCoreMessages.InlineTempRefactoring_remove_edit_name);
	ASTNode parent= variableDeclaration.getParent();
	ASTRewrite rewrite= cuRewrite.getASTRewrite();
	TightSourceRangeComputer sourceRangeComputer= new TightSourceRangeComputer();
	rewrite.setTargetSourceRangeComputer(sourceRangeComputer);
	if (parent instanceof VariableDeclarationStatement && ((VariableDeclarationStatement) parent).fragments().size() == 1) {
		sourceRangeComputer.addTightSourceNode(parent);
		rewrite.remove(parent, groupDesc);
	} else {
		sourceRangeComputer.addTightSourceNode(variableDeclaration);
		rewrite.remove(variableDeclaration, groupDesc);
	}
}
 
Example 14
Source File: LocalCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static void addRemoveProposal(IInvocationContext context, ASTNode selectedNode, Collection<ChangeCorrectionProposal> proposals) {
	ASTRewrite rewrite = ASTRewrite.create(selectedNode.getAST());
	rewrite.remove(selectedNode, null);

	String label = CorrectionMessages.LocalCorrectionsSubProcessor_removeunreachablecode_description;
	addRemoveProposal(context, rewrite, label, proposals);
}
 
Example 15
Source File: MoveInnerToTopRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void createCompilationUnitRewrite(final ITypeBinding[] parameters, final CompilationUnitRewrite targetRewrite, final Map<ICompilationUnit, SearchMatch[]> typeReferences, final Map<ICompilationUnit, SearchMatch[]> constructorReferences, boolean visibilityWasAdjusted, final ICompilationUnit sourceUnit, final ICompilationUnit targetUnit, final boolean remove, final RefactoringStatus status, final IProgressMonitor monitor) throws CoreException {
	Assert.isNotNull(parameters);
	Assert.isNotNull(targetRewrite);
	Assert.isNotNull(typeReferences);
	Assert.isNotNull(constructorReferences);
	Assert.isNotNull(sourceUnit);
	Assert.isNotNull(targetUnit);
	final CompilationUnit root= targetRewrite.getRoot();
	final ASTRewrite rewrite= targetRewrite.getASTRewrite();
	if (targetUnit.equals(sourceUnit)) {
		final AbstractTypeDeclaration declaration= findTypeDeclaration(fType, root);
		final TextEditGroup qualifierGroup= fSourceRewrite.createGroupDescription(RefactoringCoreMessages.MoveInnerToTopRefactoring_change_qualifier);
		ITypeBinding binding= declaration.resolveBinding();
		if (!remove) {
			if (!JdtFlags.isStatic(fType) && fCreateInstanceField) {
				if (JavaElementUtil.getAllConstructors(fType).length == 0)
					createConstructor(declaration, rewrite);
				else
					modifyConstructors(declaration, rewrite);
				addInheritedTypeQualifications(declaration, targetRewrite, qualifierGroup);
				addEnclosingInstanceDeclaration(declaration, rewrite);
			}
			fTypeImports= new HashSet<ITypeBinding>();
			fStaticImports= new HashSet<IBinding>();
			ImportRewriteUtil.collectImports(fType.getJavaProject(), declaration, fTypeImports, fStaticImports, false);
			if (binding != null)
				fTypeImports.remove(binding);
		}
		addEnclosingInstanceTypeParameters(parameters, declaration, rewrite);
		modifyAccessToEnclosingInstance(targetRewrite, declaration, monitor);
		if (binding != null) {
			modifyInterfaceMemberModifiers(binding);
			final ITypeBinding declaring= binding.getDeclaringClass();
			if (declaring != null)
				declaration.accept(new TypeReferenceQualifier(binding, null));
		}
		final TextEditGroup groupMove= targetRewrite.createGroupDescription(RefactoringCoreMessages.MoveInnerToTopRefactoring_change_label);
		if (remove) {
			rewrite.remove(declaration, groupMove);
			targetRewrite.getImportRemover().registerRemovedNode(declaration);
		} else {
			// Bug 101017/96308: Rewrite the visibility of the element to be
			// moved and add a warning.

			// Note that this cannot be done in the MemberVisibilityAdjustor, as the private and
			// static flags must always be cleared when moving to new type.
			int newFlags= JdtFlags.clearFlag(Modifier.STATIC, declaration.getModifiers());

			if (!visibilityWasAdjusted) {
				if (Modifier.isPrivate(declaration.getModifiers()) || Modifier.isProtected(declaration.getModifiers())) {
					newFlags= JdtFlags.clearFlag(Modifier.PROTECTED | Modifier.PRIVATE, newFlags);
					final RefactoringStatusEntry entry= new RefactoringStatusEntry(RefactoringStatus.WARNING, Messages.format(RefactoringCoreMessages.MoveInnerToTopRefactoring_change_visibility_type_warning, new String[] { BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_FULLY_QUALIFIED)}), JavaStatusContext.create(fSourceRewrite.getCu()));
					if (!containsStatusEntry(status, entry))
						status.addEntry(entry);
				}
			}

			ModifierRewrite.create(rewrite, declaration).setModifiers(newFlags, groupMove);
		}
	}
	ASTNode[] references= getReferenceNodesIn(root, typeReferences, targetUnit);
	for (int index= 0; index < references.length; index++)
		updateTypeReference(parameters, references[index], targetRewrite, targetUnit);
	references= getReferenceNodesIn(root, constructorReferences, targetUnit);
	for (int index= 0; index < references.length; index++)
		updateConstructorReference(parameters, references[index], targetRewrite, targetUnit);
}
 
Example 16
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public final boolean visit(final MethodInvocation node) {
	Assert.isNotNull(node);
	final Expression expression= node.getExpression();
	final IMethodBinding method= node.resolveMethodBinding();
	if (method != null) {
		final ASTRewrite rewrite= fRewrite;
		if (expression == null) {
			final AST ast= node.getAST();
			if (!JdtFlags.isStatic(method))
				rewrite.set(node, MethodInvocation.EXPRESSION_PROPERTY, ast.newSimpleName(fTargetName), null);
			else if (!fStaticImports.contains(method)) {
				ITypeBinding declaring= method.getDeclaringClass();
				if (declaring != null) {
					IType type= (IType) declaring.getJavaElement();
					if (type != null) {
						rewrite.set(node, MethodInvocation.EXPRESSION_PROPERTY, ast.newName(type.getTypeQualifiedName('.')), null);
					}
				}
			}
			return true;
		} else {
			if (expression instanceof FieldAccess) {
				final FieldAccess access= (FieldAccess) expression;
				if (Bindings.equals(fTarget, access.resolveFieldBinding())) {
					rewrite.remove(expression, null);
					visit(node.arguments());
					return false;
				}
			} else if (expression instanceof Name) {
				final Name name= (Name) expression;
				if (Bindings.equals(fTarget, name.resolveBinding())) {
					rewrite.remove(expression, null);
					visit(node.arguments());
					return false;
				}
			}
		}
	}
	return true;
}
 
Example 17
Source File: MoveInstanceMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates the necessary changes to create the delegate method with the
 * original method body.
 *
 * @param document
 *            the buffer containing the source of the source compilation
 *            unit
 * @param declaration
 *            the method declaration to use as source
 * @param rewrite
 *            the ast rewrite to use for the copy of the method body
 * @param rewrites
 *            the compilation unit rewrites
 * @param adjustments
 *            the map of elements to visibility adjustments
 * @param status
 *            the refactoring status
 * @param monitor
 *            the progress monitor to display progress
 * @throws CoreException
 *             if an error occurs
 */
protected void createMethodCopy(IDocument document, MethodDeclaration declaration, ASTRewrite rewrite, Map<ICompilationUnit, CompilationUnitRewrite> rewrites, Map<IMember, IncomingMemberVisibilityAdjustment> adjustments, RefactoringStatus status, IProgressMonitor monitor) throws CoreException {
	Assert.isNotNull(document);
	Assert.isNotNull(declaration);
	Assert.isNotNull(rewrite);
	Assert.isNotNull(rewrites);
	Assert.isNotNull(adjustments);
	Assert.isNotNull(status);
	Assert.isNotNull(monitor);
	final CompilationUnitRewrite rewriter= getCompilationUnitRewrite(rewrites, getTargetType().getCompilationUnit());
	try {
		rewrite.set(declaration, MethodDeclaration.NAME_PROPERTY, rewrite.getAST().newSimpleName(fMethodName), null);
		boolean same= false;
		final IMethodBinding binding= declaration.resolveBinding();
		if (binding != null) {
			final ITypeBinding declaring= binding.getDeclaringClass();
			if (declaring != null && Bindings.equals(declaring.getPackage(), fTarget.getType().getPackage()))
				same= true;
			final Modifier.ModifierKeyword keyword= same ? null : Modifier.ModifierKeyword.PUBLIC_KEYWORD;
			ModifierRewrite modifierRewrite= ModifierRewrite.create(rewrite, declaration);
			if (JdtFlags.isDefaultMethod(binding) && getTargetType().isClass()) {
				// Remove 'default' modifier and add 'public' visibility
				modifierRewrite.setVisibility(Modifier.PUBLIC, null);
				modifierRewrite.setModifiers(Modifier.NONE, Modifier.DEFAULT, null);
			} else if (!JdtFlags.isDefaultMethod(binding) && getTargetType().isInterface()) {
				// Remove visibility modifiers and add 'default'
				modifierRewrite.setModifiers(Modifier.DEFAULT, Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE, null);
			} else if (MemberVisibilityAdjustor.hasLowerVisibility(binding.getModifiers(), same ? Modifier.NONE : keyword == null ? Modifier.NONE : keyword.toFlagValue())
					&& MemberVisibilityAdjustor.needsVisibilityAdjustments(fMethod, keyword, adjustments)) {
				final MemberVisibilityAdjustor.IncomingMemberVisibilityAdjustment adjustment= new MemberVisibilityAdjustor.IncomingMemberVisibilityAdjustment(fMethod, keyword, RefactoringStatus.createStatus(RefactoringStatus.WARNING, Messages.format(RefactoringCoreMessages.MemberVisibilityAdjustor_change_visibility_method_warning, new String[] { MemberVisibilityAdjustor.getLabel(fMethod), MemberVisibilityAdjustor.getLabel(keyword) }), JavaStatusContext.create(fMethod), null, RefactoringStatusEntry.NO_CODE, null));
				modifierRewrite.setVisibility(keyword == null ? Modifier.NONE : keyword.toFlagValue(), null);
				adjustment.setNeedsRewriting(false);
				adjustments.put(fMethod, adjustment);
			}
		}
		for (IExtendedModifier modifier : (List<IExtendedModifier>) declaration.modifiers()) {
			if (modifier.isAnnotation()) {
				Annotation annotation= (Annotation) modifier;
				ITypeBinding typeBinding= annotation.resolveTypeBinding();
				if (typeBinding != null && typeBinding.getQualifiedName().equals("java.lang.Override")) { //$NON-NLS-1$
					rewrite.remove(annotation, null);
				}
			}
		}
		createMethodArguments(rewrites, rewrite, declaration, adjustments, status);
		createMethodTypeParameters(rewrite, declaration, status);
		createMethodComment(rewrite, declaration);
		createMethodBody(rewriter, rewrite, declaration);
	} finally {
		if (fMethod.getCompilationUnit().equals(getTargetType().getCompilationUnit()))
			rewriter.clearImportRewrites();
	}
}
 
Example 18
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Remove the field or variable declaration including the initializer.
 * @param rewrite the AST rewriter to use
 * @param reference a reference to the variable to remove
 * @param group the text edit group to use
 */
private void removeVariableReferences(ASTRewrite rewrite, SimpleName reference, TextEditGroup group) {
	ASTNode parent= reference.getParent();
	while (parent instanceof QualifiedName) {
		parent= parent.getParent();
	}
	if (parent instanceof FieldAccess) {
		parent= parent.getParent();
	}

	int nameParentType= parent.getNodeType();
	if (nameParentType == ASTNode.ASSIGNMENT) {
		Assignment assignment= (Assignment) parent;
		Expression rightHand= assignment.getRightHandSide();

		ASTNode assignParent= assignment.getParent();
		if (assignParent.getNodeType() == ASTNode.EXPRESSION_STATEMENT && rightHand.getNodeType() != ASTNode.ASSIGNMENT) {
			removeVariableWithInitializer(rewrite, rightHand, assignParent, group);
		}	else {
			rewrite.replace(assignment, rewrite.createCopyTarget(rightHand), group);
		}
	} else if (nameParentType == ASTNode.SINGLE_VARIABLE_DECLARATION) {
		rewrite.remove(parent, group);
	} else if (nameParentType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
		VariableDeclarationFragment frag= (VariableDeclarationFragment) parent;
		ASTNode varDecl= frag.getParent();
		List<VariableDeclarationFragment> fragments;
		if (varDecl instanceof VariableDeclarationExpression) {
			fragments= ((VariableDeclarationExpression) varDecl).fragments();
		} else if (varDecl instanceof FieldDeclaration) {
			fragments= ((FieldDeclaration) varDecl).fragments();
		} else {
			fragments= ((VariableDeclarationStatement) varDecl).fragments();
		}
		Expression initializer = frag.getInitializer();
		ArrayList<Expression> sideEffects= new ArrayList<Expression>();
		if (initializer != null) {
			initializer.accept(new SideEffectFinder(sideEffects));
		}
		boolean sideEffectInitializer= sideEffects.size() > 0;
		if (fragments.size() == fUnusedNames.length) {
			if (fForceRemove) {
				rewrite.remove(varDecl, group);
				return;
			}
			if (parent.getParent() instanceof FieldDeclaration) {
				rewrite.remove(varDecl, group);
				return;
			}
			if (sideEffectInitializer) {
				Statement[] wrapped= new Statement[sideEffects.size()];
				for (int i= 0; i < wrapped.length; i++) {
					Expression sideEffect= sideEffects.get(i);
					Expression movedInit= (Expression) rewrite.createMoveTarget(sideEffect);
					wrapped[i]= rewrite.getAST().newExpressionStatement(movedInit);
				}
				StatementRewrite statementRewrite= new StatementRewrite(rewrite, new ASTNode[] { varDecl });
				statementRewrite.replace(wrapped, group);
			} else {
				rewrite.remove(varDecl, group);
			}
		} else {
			if (fForceRemove) {
				rewrite.remove(frag, group);
				return;
			}
			//multiple declarations in one line
			ASTNode declaration = parent.getParent();
			if (declaration instanceof FieldDeclaration) {
				rewrite.remove(frag, group);
				return;
			}
			if (declaration instanceof VariableDeclarationStatement) {
				splitUpDeclarations(rewrite, group, frag, (VariableDeclarationStatement) declaration, sideEffects);
				rewrite.remove(frag, group);
				return;
			}
			if (declaration instanceof VariableDeclarationExpression) {
				//keep constructors and method invocations
				if (!sideEffectInitializer){
					rewrite.remove(frag, group);
				}
			}
		}
	} else if (nameParentType == ASTNode.POSTFIX_EXPRESSION || nameParentType == ASTNode.PREFIX_EXPRESSION) {
		Expression expression= (Expression)parent;
		ASTNode expressionParent= expression.getParent();
		if (expressionParent.getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
			removeStatement(rewrite, expressionParent, group);
		} else {
			rewrite.remove(expression, group);
		}
	}
}
 
Example 19
Source File: SourceProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public TextEdit getDeleteEdit() {
	final ASTRewrite rewriter= ASTRewrite.create(fDeclaration.getAST());
	rewriter.remove(fDeclaration, null);
	return rewriter.rewriteAST(fDocument, fTypeRoot.getJavaProject().getOptions(true));
}
 
Example 20
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static void addRemoveIncludingConditionProposal(IInvocationContext context, ASTNode toRemove, ASTNode replacement, Collection<ICommandAccess> proposals) {
	Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
	String label= CorrectionMessages.LocalCorrectionsSubProcessor_removeunreachablecode_including_condition_description;
	AST ast= toRemove.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_UNREACHABLE_CODE_INCLUDING_CONDITION, image);
	
	if (replacement == null
			|| replacement instanceof EmptyStatement
			|| replacement instanceof Block && ((Block)replacement).statements().size() == 0) {
		if (ASTNodes.isControlStatementBody(toRemove.getLocationInParent())) {
			rewrite.replace(toRemove, toRemove.getAST().newBlock(), null);
		} else {
			rewrite.remove(toRemove, null);
		}
		
	} else if (toRemove instanceof Expression && replacement instanceof Expression) {
		Expression moved= (Expression) rewrite.createMoveTarget(replacement);
		Expression toRemoveExpression= (Expression) toRemove;
		Expression replacementExpression= (Expression) replacement;
		ITypeBinding explicitCast= ASTNodes.getExplicitCast(replacementExpression, toRemoveExpression);
		if (explicitCast != null) {
			CastExpression cast= ast.newCastExpression();
			if (NecessaryParenthesesChecker.needsParentheses(replacementExpression, cast, CastExpression.EXPRESSION_PROPERTY)) {
				ParenthesizedExpression parenthesized= ast.newParenthesizedExpression();
				parenthesized.setExpression(moved);
				moved= parenthesized;
			}
			cast.setExpression(moved);
			ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot());
			ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(toRemove, imports);
			cast.setType(imports.addImport(explicitCast, ast, importRewriteContext));
			moved= cast;
		}
		rewrite.replace(toRemove, moved, null);
		
	} else {
		ASTNode parent= toRemove.getParent();
		ASTNode moveTarget;
		if ((parent instanceof Block || parent instanceof SwitchStatement) && replacement instanceof Block) {
			ListRewrite listRewrite= rewrite.getListRewrite(replacement, Block.STATEMENTS_PROPERTY);
			List<Statement> list= ((Block)replacement).statements();
			int lastIndex= list.size() - 1;
			moveTarget= listRewrite.createMoveTarget(list.get(0), list.get(lastIndex));
		} else {
			moveTarget= rewrite.createMoveTarget(replacement);
		}

		rewrite.replace(toRemove, moveTarget, null);
	}
	
	proposals.add(proposal);
}