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

The following examples show how to use org.eclipse.jdt.core.dom.rewrite.ASTRewrite#replace() . 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: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static ASTRewriteCorrectionProposal createNoSideEffectProposal(IInvocationContext context, SimpleName nodeToQualify, IVariableBinding fieldBinding, String label, int relevance) {
	AST ast= nodeToQualify.getAST();

	Expression qualifier;
	if (Modifier.isStatic(fieldBinding.getModifiers())) {
		ITypeBinding declaringClass= fieldBinding.getDeclaringClass();
		qualifier= ast.newSimpleName(declaringClass.getTypeDeclaration().getName());
	} else {
		qualifier= ast.newThisExpression();
	}

	ASTRewrite rewrite= ASTRewrite.create(ast);
	FieldAccess access= ast.newFieldAccess();
	access.setName((SimpleName) rewrite.createCopyTarget(nodeToQualify));
	access.setExpression(qualifier);
	rewrite.replace(nodeToQualify, access, null);


	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
	return new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, relevance, image);
}
 
Example 2
Source File: CorrectOddnessCheckResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug) throws BugResolutionException {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(workingUnit);
    Assert.isNotNull(bug);

    InfixExpression oddnessCheck = findOddnessCheck(getASTNode(workingUnit, bug.getPrimarySourceLineAnnotation()));
    if (oddnessCheck == null) {
        throw new BugResolutionException("No matching oddness check found at the specified source line.");
    }
    Expression numberExpression = findNumberExpression(oddnessCheck);
    if (numberExpression == null) {
        throw new BugResolutionException();
    }
    InfixExpression correctOddnessCheck = createCorrectOddnessCheck(rewrite, numberExpression);
    rewrite.replace(oddnessCheck, correctOddnessCheck, null);
}
 
Example 3
Source File: ConvertIterableLoopOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException {
	final TextEditGroup group= createTextEditGroup(FixMessages.Java50Fix_ConvertToEnhancedForLoop_description, cuRewrite);

	final ASTRewrite astRewrite= cuRewrite.getASTRewrite();

	TightSourceRangeComputer rangeComputer;
	if (astRewrite.getExtendedSourceRangeComputer() instanceof TightSourceRangeComputer) {
		rangeComputer= (TightSourceRangeComputer)astRewrite.getExtendedSourceRangeComputer();
	} else {
		rangeComputer= new TightSourceRangeComputer();
	}
	rangeComputer.addTightSourceNode(getForStatement());
	astRewrite.setTargetSourceRangeComputer(rangeComputer);

	Statement statement= convert(cuRewrite, group, positionGroups);
	astRewrite.replace(getForStatement(), statement, group);
}
 
Example 4
Source File: UseEqualsResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug) throws BugResolutionException {
    Assert.isNotNull(rewrite);
    Assert.isNotNull(workingUnit);
    Assert.isNotNull(bug);

    InfixExpression[] stringEqualityChecks = findStringEqualityChecks(getASTNode(workingUnit, bug.getPrimarySourceLineAnnotation()));
    for (InfixExpression stringEqualityCheck : stringEqualityChecks) {
        Operator operator = stringEqualityCheck.getOperator();
        Expression replaceExpression;
        if (EQUALS.equals(operator)) {
            replaceExpression = createEqualsExpression(rewrite, stringEqualityCheck);
        } else if (NOT_EQUALS.equals(operator)) {
            replaceExpression = createNotEqualsExpression(rewrite, stringEqualityCheck);
        } else {
            throw new BugResolutionException("Illegal operator '" + operator + "' found.");
        }
        rewrite.replace(stringEqualityCheck, replaceExpression, null);
    }
}
 
Example 5
Source File: TypeArgumentMismatchSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static void removeMismatchedArguments(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals){
	ICompilationUnit cu= context.getCompilationUnit();
	ASTNode selectedNode= problem.getCoveredNode(context.getASTRoot());
	if (!(selectedNode instanceof SimpleName)) {
		return;
	}

	ASTNode normalizedNode=ASTNodes.getNormalizedNode(selectedNode);
	if (normalizedNode instanceof ParameterizedType) {
		ASTRewrite rewrite = ASTRewrite.create(normalizedNode.getAST());
		ParameterizedType pt = (ParameterizedType) normalizedNode;
		ASTNode mt = rewrite.createMoveTarget(pt.getType());
		rewrite.replace(pt, mt, null);
		String label= CorrectionMessages.TypeArgumentMismatchSubProcessor_removeTypeArguments;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.REMOVE_TYPE_ARGUMENTS, image);
		proposals.add(proposal);
	}
}
 
Example 6
Source File: SimpleFragment.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void replace(ASTRewrite rewrite, ASTNode replacement, TextEditGroup textEditGroup) {
	if (replacement instanceof Name && fNode.getParent() instanceof ParenthesizedExpression) {
		// replace including the parenthesized expression around it
		rewrite.replace(fNode.getParent(), replacement, textEditGroup);
	} else {
		rewrite.replace(fNode, replacement, textEditGroup);
	}
}
 
Example 7
Source File: ExtractSupertypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a new type signature of a subtype.
 *
 * @param subRewrite
 *            the compilation unit rewrite of a subtype
 * @param declaration
 *            the type declaration of a subtype
 * @param extractedType
 *            the extracted super type
 * @param extractedBinding
 *            the binding of the extracted super type
 * @param monitor
 *            the progress monitor to use
 * @throws JavaModelException
 *             if the type parameters cannot be retrieved
 */
protected final void createTypeSignature(final CompilationUnitRewrite subRewrite, final AbstractTypeDeclaration declaration, final IType extractedType, final ITypeBinding extractedBinding, final IProgressMonitor monitor) throws JavaModelException {
	Assert.isNotNull(subRewrite);
	Assert.isNotNull(declaration);
	Assert.isNotNull(extractedType);
	Assert.isNotNull(monitor);
	try {
		monitor.beginTask(RefactoringCoreMessages.ExtractSupertypeProcessor_preparing, 10);
		final AST ast= subRewrite.getAST();
		Type type= null;
		if (extractedBinding != null) {
			type= subRewrite.getImportRewrite().addImport(extractedBinding, ast);
		} else {
			subRewrite.getImportRewrite().addImport(extractedType.getFullyQualifiedName('.'));
			type= ast.newSimpleType(ast.newSimpleName(extractedType.getElementName()));
		}
		subRewrite.getImportRemover().registerAddedImport(extractedType.getFullyQualifiedName('.'));
		if (type != null) {
			final ITypeParameter[] parameters= extractedType.getTypeParameters();
			if (parameters.length > 0) {
				final ParameterizedType parameterized= ast.newParameterizedType(type);
				for (int index= 0; index < parameters.length; index++)
					parameterized.typeArguments().add(ast.newSimpleType(ast.newSimpleName(parameters[index].getElementName())));
				type= parameterized;
			}
		}
		final ASTRewrite rewriter= subRewrite.getASTRewrite();
		if (type != null && declaration instanceof TypeDeclaration) {
			final TypeDeclaration extended= (TypeDeclaration) declaration;
			final Type superClass= extended.getSuperclassType();
			if (superClass != null) {
				rewriter.replace(superClass, type, subRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractSupertypeProcessor_add_supertype, SET_EXTRACT_SUPERTYPE));
				subRewrite.getImportRemover().registerRemovedNode(superClass);
			} else
				rewriter.set(extended, TypeDeclaration.SUPERCLASS_TYPE_PROPERTY, type, subRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractSupertypeProcessor_add_supertype, SET_EXTRACT_SUPERTYPE));
		}
	} finally {
		monitor.done();
	}
}
 
Example 8
Source File: SourceProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void rewriteReferences(ASTRewrite rewriter, ITypeBinding[] typeArguments, List<NameData> typeParameterReferences) {
	if (typeArguments.length == 0)
		return;
	Assert.isTrue(typeArguments.length == typeParameterReferences.size());
	for (int i= 0; i < typeArguments.length; i++) {
		SourceAnalyzer.NameData refData= typeParameterReferences.get(i);
		List<SimpleName> references= refData.references();
		String newName= typeArguments[i].getName();
		for (Iterator<SimpleName> iter= references.iterator(); iter.hasNext();) {
			SimpleName name= iter.next();
			rewriter.replace(name, rewriter.createStringPlaceholder(newName, ASTNode.SIMPLE_NAME), null);
		}
	}
}
 
Example 9
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Helper to generate an iterator based <code>for</code> loop to iterate over an
 * {@link Iterable}.
 * 
 * @param ast the {@link AST} instance to rewrite the loop to
 * @return the complete {@link ASTRewrite} object
 */
private ASTRewrite generateIteratorBasedForRewrite(AST ast) {
	ASTRewrite rewrite= ASTRewrite.create(ast);
	ForStatement loopStatement= ast.newForStatement();

	ITypeBinding loopOverType= extractElementType(ast);

	SimpleName loopVariableName= resolveLinkedVariableNameWithProposals(rewrite, "iterator", null, true); //$NON-NLS-1$
	loopStatement.initializers().add(getIteratorBasedForInitializer(rewrite, loopVariableName));

	MethodInvocation loopExpression= ast.newMethodInvocation();
	loopExpression.setName(ast.newSimpleName("hasNext")); //$NON-NLS-1$
	SimpleName expressionName= ast.newSimpleName(loopVariableName.getIdentifier());
	addLinkedPosition(rewrite.track(expressionName), LinkedPositionGroup.NO_STOP, expressionName.getIdentifier());
	loopExpression.setExpression(expressionName);

	loopStatement.setExpression(loopExpression);

	Block forLoopBody= ast.newBlock();
	Assignment assignResolvedVariable= getIteratorBasedForBodyAssignment(rewrite, loopOverType, loopVariableName);
	forLoopBody.statements().add(ast.newExpressionStatement(assignResolvedVariable));
	forLoopBody.statements().add(createBlankLineStatementWithCursorPosition(rewrite));

	loopStatement.setBody(forLoopBody);

	rewrite.replace(fCurrentNode, loopStatement, null);

	return rewrite;
}
 
Example 10
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 11
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
static CUCorrectionProposal createTypeRefChangeFullProposal(ICompilationUnit cu, ITypeBinding binding, ASTNode node, int relevance) {
	ASTRewrite rewrite= ASTRewrite.create(node.getAST());
	String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_change_full_type_description, BindingLabelProviderCore.getBindingLabel(binding, JavaElementLabels.ALL_DEFAULT));

	ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, cu, rewrite, relevance);

	ImportRewrite imports= proposal.createImportRewrite((CompilationUnit) node.getRoot());
	Type type= imports.addImport(binding, node.getAST());

	rewrite.replace(node, type, null);
	return proposal;
}
 
Example 12
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void updateType(CompilationUnit cu, Type oldType, CompilationUnitChange unitChange,
						ASTRewrite unitRewriter, String typeName) {

	String oldName= fSelectionTypeBinding.getName();
	String[] keys= { BasicElementLabels.getJavaElementName(oldName), BasicElementLabels.getJavaElementName(typeName)};
	String description= Messages.format(RefactoringCoreMessages.ChangeTypeRefactoring_typeChange, keys);
	TextEditGroup gd= new TextEditGroup(description);
	AST	ast= cu.getAST();

	ASTNode nodeToReplace= oldType;
	if (fSelectionTypeBinding.isParameterizedType() && !fSelectionTypeBinding.isRawType()){
		if (oldType.isSimpleType()){
			nodeToReplace= oldType.getParent();
		}
	}

    //TODO handle types other than simple & parameterized (e.g., arrays)
	Assert.isTrue(fSelectedType.isClass() || fSelectedType.isInterface());

	Type newType= null;
	if (!fSelectedType.isParameterizedType()){
		newType= ast.newSimpleType(ASTNodeFactory.newName(ast, typeName));
	} else {
		newType= createParameterizedType(ast, fSelectedType);
	}

	unitRewriter.replace(nodeToReplace, newType, gd);
	unitChange.addTextEditGroup(gd);
}
 
Example 13
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean useExistingParentCastProposal(ICompilationUnit cu, CastExpression expression, Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes, Collection<ICommandAccess> proposals) {
	ITypeBinding castType= expression.getType().resolveBinding();
	if (castType == null) {
		return false;
	}
	if (paramTypes != null) {
		if (Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes) == null) {
			return false;
		}
	} else if (Bindings.findFieldInHierarchy(castType, accessSelector.getIdentifier()) == null) {
		return false;
	}
	ITypeBinding bindingToCast= accessExpression.resolveTypeBinding();
	if (bindingToCast != null && !bindingToCast.isCastCompatible(castType)) {
		return false;
	}

	IMethodBinding res= Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes);
	if (res != null) {
		AST ast= expression.getAST();
		ASTRewrite rewrite= ASTRewrite.create(ast);
		CastExpression newCast= ast.newCastExpression();
		newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType()));
		newCast.setExpression((Expression) rewrite.createCopyTarget(accessExpression));
		ParenthesizedExpression parents= ast.newParenthesizedExpression();
		parents.setExpression(newCast);

		ASTNode node= rewrite.createCopyTarget(expression.getExpression());
		rewrite.replace(expression, node, null);
		rewrite.replace(accessExpression, parents, null);

		String label= CorrectionMessages.UnresolvedElementsSubProcessor_missingcastbrackets_description;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CAST);
		ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_PARENTHESES_AROUND_CAST, image);
		proposals.add(proposal);
		return true;
	}
	return false;
}
 
Example 14
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void addUnnecessaryInstanceofProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());

	ASTNode curr= selectedNode;
	while (curr instanceof ParenthesizedExpression) {
		curr= ((ParenthesizedExpression) curr).getExpression();
	}

	if (curr instanceof InstanceofExpression) {
		AST ast= curr.getAST();

		ASTRewrite rewrite= ASTRewrite.create(ast);

		InstanceofExpression inst= (InstanceofExpression) curr;

		InfixExpression expression= ast.newInfixExpression();
		expression.setLeftOperand((Expression) rewrite.createCopyTarget(inst.getLeftOperand()));
		expression.setOperator(InfixExpression.Operator.NOT_EQUALS);
		expression.setRightOperand(ast.newNullLiteral());

		rewrite.replace(inst, expression, null);

		String label= CorrectionMessages.LocalCorrectionsSubProcessor_unnecessaryinstanceof_description;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.UNNECESSARY_INSTANCEOF, image);
		proposals.add(proposal);
	}

}
 
Example 15
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static boolean useExistingParentCastProposal(ICompilationUnit cu, CastExpression expression,
		Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes,
		Collection<ChangeCorrectionProposal> proposals) {
	ITypeBinding castType= expression.getType().resolveBinding();
	if (castType == null) {
		return false;
	}
	if (paramTypes != null) {
		if (Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes) == null) {
			return false;
		}
	} else if (Bindings.findFieldInHierarchy(castType, accessSelector.getIdentifier()) == null) {
		return false;
	}
	ITypeBinding bindingToCast= accessExpression.resolveTypeBinding();
	if (bindingToCast != null && !bindingToCast.isCastCompatible(castType)) {
		return false;
	}

	IMethodBinding res= Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes);
	if (res != null) {
		AST ast= expression.getAST();
		ASTRewrite rewrite= ASTRewrite.create(ast);
		CastExpression newCast= ast.newCastExpression();
		newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType()));
		newCast.setExpression((Expression) rewrite.createCopyTarget(accessExpression));
		ParenthesizedExpression parents= ast.newParenthesizedExpression();
		parents.setExpression(newCast);

		ASTNode node= rewrite.createCopyTarget(expression.getExpression());
		rewrite.replace(expression, node, null);
		rewrite.replace(accessExpression, parents, null);

		String label= CorrectionMessages.UnresolvedElementsSubProcessor_missingcastbrackets_description;
		ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, cu, rewrite,
				IProposalRelevance.ADD_PARENTHESES_AROUND_CAST);
		proposals.add(proposal);
		return true;
	}
	return false;
}
 
Example 16
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static void addDeprecatedFieldsToMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
	if (selectedNode instanceof Name) {
		IBinding binding= ((Name) selectedNode).resolveBinding();
		if (binding instanceof IVariableBinding) {
			IVariableBinding variableBinding= (IVariableBinding) binding;
			if (variableBinding.isField()) {
				String qualifiedName= variableBinding.getDeclaringClass().getTypeDeclaration().getQualifiedName();
				String fieldName= variableBinding.getName();
				String[] methodName= getMethod(JavaModelUtil.concatenateName(qualifiedName, fieldName));
				if (methodName != null) {
					AST ast= selectedNode.getAST();
					ASTRewrite astRewrite= ASTRewrite.create(ast);
					ImportRewrite importRewrite= StubUtility.createImportRewrite(context.getASTRoot(), true);

					MethodInvocation method= ast.newMethodInvocation();
					String qfn= importRewrite.addImport(methodName[0]);
					method.setExpression(ast.newName(qfn));
					method.setName(ast.newSimpleName(methodName[1]));
					ASTNode parent= selectedNode.getParent();
					ICompilationUnit cu= context.getCompilationUnit();
					// add explicit type arguments if necessary (for 1.8 and later, we're optimistic that inference just works):
					if (Invocations.isInvocationWithArguments(parent) && !JavaModelUtil.is18OrHigher(cu.getJavaProject())) {
						IMethodBinding methodBinding= Invocations.resolveBinding(parent);
						if (methodBinding != null) {
							ITypeBinding[] parameterTypes= methodBinding.getParameterTypes();
							int i= Invocations.getArguments(parent).indexOf(selectedNode);
							if (parameterTypes.length >= i && parameterTypes[i].isParameterizedType()) {
								ITypeBinding[] typeArguments= parameterTypes[i].getTypeArguments();
								for (int j= 0; j < typeArguments.length; j++) {
									ITypeBinding typeArgument= typeArguments[j];
									typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast);
									if (! TypeRules.isJavaLangObject(typeArgument)) {
										// add all type arguments if at least one is found to be necessary:
										List<Type> typeArgumentsList= method.typeArguments();
										for (int k= 0; k < typeArguments.length; k++) {
											typeArgument= typeArguments[k];
											typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast);
											typeArgumentsList.add(importRewrite.addImport(typeArgument, ast));
										}
										break;
									}
								}
							}
						}
					}
					
					astRewrite.replace(selectedNode, method, null);

					String label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_replacefieldaccesswithmethod_description, BasicElementLabels.getJavaElementName(ASTNodes.asString(method)));
					Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
					ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, astRewrite, IProposalRelevance.REPLACE_FIELD_ACCESS_WITH_METHOD, image);
					proposal.setImportRewrite(importRewrite);
					proposals.add(proposal);
				}
			}
		}
	}
}
 
Example 17
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 18
Source File: AssignToVariableAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private ASTRewrite doAddLocal() {
	Expression expression= ((ExpressionStatement) fNodeToAssign).getExpression();
	AST ast= fNodeToAssign.getAST();

	ASTRewrite rewrite= ASTRewrite.create(ast);

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

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

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

	Type type= evaluateType(ast);

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

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

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

	return rewrite;
}
 
Example 19
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);
}
 
Example 20
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Helper to generate a <code>foreach</code> loop to iterate over an {@link Iterable}.
 * 
 * @param ast the {@link AST} instance to rewrite the loop to
 * @return the complete {@link ASTRewrite} object
 */
private ASTRewrite generateForEachRewrite(AST ast) {

	EnhancedForStatement loopStatement= ast.newEnhancedForStatement();

	ASTRewrite rewrite= ASTRewrite.create(ast);
	ITypeBinding loopOverType= extractElementType(ast);

	// generate name proposals and add them to the variable declaration
	SimpleName forDeclarationName= resolveLinkedVariableNameWithProposals(rewrite, loopOverType.getName(), null, true);

	SingleVariableDeclaration forLoopInitializer= ast.newSingleVariableDeclaration();
	forLoopInitializer.setType(getImportRewrite().addImport(loopOverType, ast, new ContextSensitiveImportRewriteContext(fCurrentNode, getImportRewrite())));
	forLoopInitializer.setName(forDeclarationName);

	loopStatement.setParameter(forLoopInitializer);
	loopStatement.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression));

	Block forLoopBody= ast.newBlock();
	forLoopBody.statements().add(createBlankLineStatementWithCursorPosition(rewrite));

	loopStatement.setBody(forLoopBody);

	rewrite.replace(fCurrentNode, loopStatement, null);

	return rewrite;
}