use of org.eclipse.jdt.internal.corext.refactoring.util.TightSourceRangeComputer in project che by eclipse.
the class AdvancedQuickAssistProcessor method getReplaceIfElseWithConditionalProposals.
private static boolean getReplaceIfElseWithConditionalProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
if (!(node instanceof IfStatement)) {
return false;
}
IfStatement ifStatement = (IfStatement) node;
Statement thenStatement = getSingleStatement(ifStatement.getThenStatement());
Statement elseStatement = getSingleStatement(ifStatement.getElseStatement());
if (thenStatement == null || elseStatement == null) {
return false;
}
Expression assigned = null;
Expression thenExpression = null;
Expression elseExpression = null;
ITypeBinding exprBinding = null;
if (thenStatement instanceof ReturnStatement && elseStatement instanceof ReturnStatement) {
thenExpression = ((ReturnStatement) thenStatement).getExpression();
elseExpression = ((ReturnStatement) elseStatement).getExpression();
MethodDeclaration declaration = ASTResolving.findParentMethodDeclaration(node);
if (declaration == null || declaration.isConstructor()) {
return false;
}
exprBinding = declaration.getReturnType2().resolveBinding();
} else if (thenStatement instanceof ExpressionStatement && elseStatement instanceof ExpressionStatement) {
Expression inner1 = ((ExpressionStatement) thenStatement).getExpression();
Expression inner2 = ((ExpressionStatement) elseStatement).getExpression();
if (inner1 instanceof Assignment && inner2 instanceof Assignment) {
Assignment assign1 = (Assignment) inner1;
Assignment assign2 = (Assignment) inner2;
Expression left1 = assign1.getLeftHandSide();
Expression left2 = assign2.getLeftHandSide();
if (left1 instanceof Name && left2 instanceof Name && assign1.getOperator() == assign2.getOperator()) {
IBinding bind1 = ((Name) left1).resolveBinding();
IBinding bind2 = ((Name) left2).resolveBinding();
if (bind1 == bind2 && bind1 instanceof IVariableBinding) {
assigned = left1;
exprBinding = ((IVariableBinding) bind1).getType();
thenExpression = assign1.getRightHandSide();
elseExpression = assign2.getRightHandSide();
}
}
}
}
if (thenExpression == null || elseExpression == null) {
return false;
}
// we could produce quick assist
if (resultingCollections == null) {
return true;
}
//
AST ast = node.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
TightSourceRangeComputer sourceRangeComputer = new TightSourceRangeComputer();
sourceRangeComputer.addTightSourceNode(ifStatement);
rewrite.setTargetSourceRangeComputer(sourceRangeComputer);
String label = CorrectionMessages.AdvancedQuickAssistProcessor_replaceIfWithConditional;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_IF_ELSE_WITH_CONDITIONAL, image);
// prepare conditional expression
ConditionalExpression conditionalExpression = ast.newConditionalExpression();
Expression conditionCopy = (Expression) rewrite.createCopyTarget(ifStatement.getExpression());
conditionalExpression.setExpression(conditionCopy);
Expression thenCopy = (Expression) rewrite.createCopyTarget(thenExpression);
Expression elseCopy = (Expression) rewrite.createCopyTarget(elseExpression);
IJavaProject project = context.getCompilationUnit().getJavaProject();
if (!JavaModelUtil.is50OrHigher(project)) {
ITypeBinding thenBinding = thenExpression.resolveTypeBinding();
ITypeBinding elseBinding = elseExpression.resolveTypeBinding();
if (thenBinding != null && elseBinding != null && exprBinding != null && !elseBinding.isAssignmentCompatible(thenBinding)) {
CastExpression castException = ast.newCastExpression();
ImportRewrite importRewrite = proposal.createImportRewrite(context.getASTRoot());
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, importRewrite);
castException.setType(importRewrite.addImport(exprBinding, ast, importRewriteContext));
castException.setExpression(elseCopy);
elseCopy = castException;
}
} else if (JavaModelUtil.is17OrHigher(project)) {
addExplicitTypeArgumentsIfNecessary(rewrite, proposal, thenExpression);
addExplicitTypeArgumentsIfNecessary(rewrite, proposal, elseExpression);
}
conditionalExpression.setThenExpression(thenCopy);
conditionalExpression.setElseExpression(elseCopy);
// replace 'if' statement with conditional expression
if (assigned == null) {
ReturnStatement returnStatement = ast.newReturnStatement();
returnStatement.setExpression(conditionalExpression);
rewrite.replace(ifStatement, returnStatement, null);
} else {
Assignment assignment = ast.newAssignment();
assignment.setLeftHandSide((Expression) rewrite.createCopyTarget(assigned));
assignment.setRightHandSide(conditionalExpression);
assignment.setOperator(((Assignment) assigned.getParent()).getOperator());
ExpressionStatement expressionStatement = ast.newExpressionStatement(assignment);
rewrite.replace(ifStatement, expressionStatement, null);
}
// add correction proposal
resultingCollections.add(proposal);
return true;
}
use of org.eclipse.jdt.internal.corext.refactoring.util.TightSourceRangeComputer in project che by eclipse.
the class QuickAssistProcessor method getJoinVariableProposals.
private static boolean getJoinVariableProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
ASTNode parent = node.getParent();
VariableDeclarationFragment fragment = null;
boolean onFirstAccess = false;
if (node instanceof SimpleName && node.getLocationInParent() == Assignment.LEFT_HAND_SIDE_PROPERTY) {
onFirstAccess = true;
SimpleName name = (SimpleName) node;
IBinding binding = name.resolveBinding();
if (!(binding instanceof IVariableBinding)) {
return false;
}
ASTNode declaring = context.getASTRoot().findDeclaringNode(binding);
if (declaring instanceof VariableDeclarationFragment) {
fragment = (VariableDeclarationFragment) declaring;
} else {
return false;
}
} else if (parent instanceof VariableDeclarationFragment) {
fragment = (VariableDeclarationFragment) parent;
} else {
return false;
}
IVariableBinding binding = fragment.resolveBinding();
Expression initializer = fragment.getInitializer();
if ((initializer != null && initializer.getNodeType() != ASTNode.NULL_LITERAL) || binding == null || binding.isField()) {
return false;
}
if (!(fragment.getParent() instanceof VariableDeclarationStatement)) {
return false;
}
VariableDeclarationStatement statement = (VariableDeclarationStatement) fragment.getParent();
SimpleName[] names = LinkedNodeFinder.findByBinding(statement.getParent(), binding);
if (names.length <= 1 || names[0] != fragment.getName()) {
return false;
}
SimpleName firstAccess = names[1];
if (onFirstAccess) {
if (firstAccess != node) {
return false;
}
} else {
if (firstAccess.getLocationInParent() != Assignment.LEFT_HAND_SIDE_PROPERTY) {
return false;
}
}
Assignment assignment = (Assignment) firstAccess.getParent();
if (assignment.getLocationInParent() != ExpressionStatement.EXPRESSION_PROPERTY) {
return false;
}
ExpressionStatement assignParent = (ExpressionStatement) assignment.getParent();
if (resultingCollections == null) {
return true;
}
AST ast = statement.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
TightSourceRangeComputer sourceRangeComputer = new TightSourceRangeComputer();
sourceRangeComputer.addTightSourceNode(assignParent);
rewrite.setTargetSourceRangeComputer(sourceRangeComputer);
String label = CorrectionMessages.QuickAssistProcessor_joindeclaration_description;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.JOIN_VARIABLE_DECLARATION, image);
proposal.setCommandId(SPLIT_JOIN_VARIABLE_DECLARATION_ID);
Expression placeholder = (Expression) rewrite.createMoveTarget(assignment.getRightHandSide());
rewrite.set(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, placeholder, null);
if (onFirstAccess) {
// replace assignment with variable declaration
rewrite.replace(assignParent, rewrite.createMoveTarget(statement), null);
} else {
// different scopes -> remove assignments, set variable initializer
if (ASTNodes.isControlStatementBody(assignParent.getLocationInParent())) {
Block block = ast.newBlock();
rewrite.replace(assignParent, block, null);
} else {
rewrite.remove(assignParent, null);
}
}
proposal.setEndPosition(rewrite.track(fragment.getName()));
resultingCollections.add(proposal);
return true;
}
use of org.eclipse.jdt.internal.corext.refactoring.util.TightSourceRangeComputer in project che by eclipse.
the class ConvertIterableLoopOperation method rewriteAST.
/**
* {@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);
}
use of org.eclipse.jdt.internal.corext.refactoring.util.TightSourceRangeComputer in project che by eclipse.
the class ChangeSignatureProcessor method createChangeManager.
private TextChangeManager createChangeManager(IProgressMonitor pm, RefactoringStatus result) throws CoreException {
pm.beginTask(RefactoringCoreMessages.ChangeSignatureRefactoring_preview, 2);
fChangeManager = new TextChangeManager();
boolean isNoArgConstructor = isNoArgConstructor();
Map<ICompilationUnit, Set<IType>> namedSubclassMapping = null;
if (isNoArgConstructor) {
//create only when needed;
namedSubclassMapping = createNamedSubclassMapping(new SubProgressMonitor(pm, 1));
} else {
pm.worked(1);
}
for (int i = 0; i < fOccurrences.length; i++) {
if (pm.isCanceled())
throw new OperationCanceledException();
SearchResultGroup group = fOccurrences[i];
ICompilationUnit cu = group.getCompilationUnit();
if (cu == null)
continue;
CompilationUnitRewrite cuRewrite;
if (cu.equals(getCu())) {
cuRewrite = fBaseCuRewrite;
} else {
cuRewrite = new CompilationUnitRewrite(cu);
cuRewrite.getASTRewrite().setTargetSourceRangeComputer(new TightSourceRangeComputer());
}
ASTNode[] nodes = ASTNodeSearchUtil.findNodes(group.getSearchResults(), cuRewrite.getRoot());
//IntroduceParameterObjectRefactoring needs to update declarations first:
List<OccurrenceUpdate<? extends ASTNode>> deferredUpdates = new ArrayList<OccurrenceUpdate<? extends ASTNode>>();
for (int j = 0; j < nodes.length; j++) {
OccurrenceUpdate<? extends ASTNode> update = createOccurrenceUpdate(nodes[j], cuRewrite, result);
if (update instanceof DeclarationUpdate) {
update.updateNode();
} else {
deferredUpdates.add(update);
}
}
for (Iterator<OccurrenceUpdate<? extends ASTNode>> iter = deferredUpdates.iterator(); iter.hasNext(); ) {
iter.next().updateNode();
}
if (isNoArgConstructor && namedSubclassMapping.containsKey(cu)) {
//only non-anonymous subclasses may have noArgConstructors to modify - see bug 43444
Set<IType> subtypes = namedSubclassMapping.get(cu);
for (Iterator<IType> iter = subtypes.iterator(); iter.hasNext(); ) {
IType subtype = iter.next();
AbstractTypeDeclaration subtypeNode = ASTNodeSearchUtil.getAbstractTypeDeclarationNode(subtype, cuRewrite.getRoot());
if (subtypeNode != null)
modifyImplicitCallsToNoArgConstructor(subtypeNode, cuRewrite);
}
}
TextChange change = cuRewrite.createChange(true);
if (change != null)
fChangeManager.manage(cu, change);
}
pm.done();
return fChangeManager;
}
use of org.eclipse.jdt.internal.corext.refactoring.util.TightSourceRangeComputer in project che by eclipse.
the class ChangeSignatureProcessor method checkFinalConditions.
/* (non-Javadoc)
* @see org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor#checkFinalConditions(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext)
*/
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm, CheckConditionsContext context) throws CoreException, OperationCanceledException {
try {
pm.beginTask(RefactoringCoreMessages.ChangeSignatureRefactoring_checking_preconditions, 8);
RefactoringStatus result = new RefactoringStatus();
clearManagers();
fBaseCuRewrite.clearASTAndImportRewrites();
fBaseCuRewrite.getASTRewrite().setTargetSourceRangeComputer(new TightSourceRangeComputer());
if (isSignatureSameAsInitial())
return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ChangeSignatureRefactoring_unchanged);
result.merge(checkSignature(true));
if (result.hasFatalError())
return result;
if (fDelegateUpdating && isSignatureClashWithInitial())
result.merge(RefactoringStatus.createErrorStatus(RefactoringCoreMessages.ChangeSignatureRefactoring_old_and_new_signatures_not_sufficiently_different));
String binaryRefsDescription = Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description, BasicElementLabels.getJavaElementName(getMethodName()));
ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription);
fRippleMethods = RippleMethodFinder2.getRelatedMethods(fMethod, binaryRefs, new SubProgressMonitor(pm, 1), null);
result.merge(checkVarargs());
if (result.hasFatalError())
return result;
fOccurrences = findOccurrences(new SubProgressMonitor(pm, 1), binaryRefs, result);
binaryRefs.addErrorIfNecessary(result);
result.merge(checkVisibilityChanges());
result.merge(checkTypeVariables());
if (!isOrderSameAsInitial())
result.merge(checkReorderings(new SubProgressMonitor(pm, 1)));
else
pm.worked(1);
if (!areNamesSameAsInitial())
result.merge(checkRenamings(new SubProgressMonitor(pm, 1)));
else
pm.worked(1);
if (result.hasFatalError())
return result;
// resolveTypesWithoutBindings(new SubProgressMonitor(pm, 1)); // already done in checkSignature(true)
createChangeManager(new SubProgressMonitor(pm, 1), result);
fCachedTypeHierarchy = null;
if (mustAnalyzeAstOfDeclaringCu())
//TODO: should also check in ripple methods (move into createChangeManager)
result.merge(checkCompilationofDeclaringCu());
if (result.hasFatalError())
return result;
Checks.addModifiedFilesToChecker(getAllFilesToModify(), context);
return result;
} finally {
pm.done();
}
}
Aggregations