use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project che by eclipse.
the class SourceProvider method updateStaticReferences.
private void updateStaticReferences(ASTRewrite rewriter, CallContext context) {
ImportRewrite importer = context.importer;
for (Iterator<SimpleName> iter = fAnalyzer.getStaticsToImport().iterator(); iter.hasNext(); ) {
Name element = iter.next();
IBinding binding = element.resolveBinding();
if (binding != null) {
String s = importer.addStaticImport(binding);
if (!ASTNodes.asString(element).equals(s)) {
rewriter.replace(element, rewriter.createStringPlaceholder(s, ASTNode.SIMPLE_NAME), null);
}
}
}
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project che by eclipse.
the class ReplaceInvocationsRefactoring method checkFinalConditions.
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
//$NON-NLS-1$
pm.beginTask("", 20);
fChangeManager = new TextChangeManager();
RefactoringStatus result = new RefactoringStatus();
fSourceProvider = resolveSourceProvider(fMethodBinding, result);
if (result.hasFatalError())
return result;
result.merge(fSourceProvider.checkActivation());
if (result.hasFatalError())
return result;
fSourceProvider.initialize();
fTargetProvider.initialize();
pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_searching);
RefactoringStatus searchStatus = new RefactoringStatus();
String binaryRefsDescription = Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description, BasicElementLabels.getJavaElementName(fSourceProvider.getMethodName()));
ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription);
ICompilationUnit[] units = fTargetProvider.getAffectedCompilationUnits(searchStatus, binaryRefs, new SubProgressMonitor(pm, 1));
binaryRefs.addErrorIfNecessary(searchStatus);
if (searchStatus.hasFatalError()) {
result.merge(searchStatus);
return result;
}
IFile[] filesToBeModified = getFilesToBeModified(units);
result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
if (result.hasFatalError())
return result;
result.merge(ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1)));
checkOverridden(result, new SubProgressMonitor(pm, 4));
IProgressMonitor sub = new SubProgressMonitor(pm, 15);
//$NON-NLS-1$
sub.beginTask("", units.length * 3);
for (int c = 0; c < units.length; c++) {
ICompilationUnit unit = units[c];
sub.subTask(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_processing, BasicElementLabels.getFileName(unit)));
CallInliner inliner = null;
try {
boolean added = false;
MultiTextEdit root = new MultiTextEdit();
CompilationUnitChange change = (CompilationUnitChange) fChangeManager.get(unit);
change.setEdit(root);
BodyDeclaration[] bodies = fTargetProvider.getAffectedBodyDeclarations(unit, new SubProgressMonitor(pm, 1));
if (bodies.length == 0)
continue;
inliner = new CallInliner(unit, (CompilationUnit) bodies[0].getRoot(), fSourceProvider);
for (int b = 0; b < bodies.length; b++) {
BodyDeclaration body = bodies[b];
inliner.initialize(body);
RefactoringStatus nestedInvocations = new RefactoringStatus();
ASTNode[] invocations = removeNestedCalls(nestedInvocations, unit, fTargetProvider.getInvocations(body, new SubProgressMonitor(sub, 2)));
for (int i = 0; i < invocations.length; i++) {
ASTNode invocation = invocations[i];
result.merge(inliner.initialize(invocation, fTargetProvider.getStatusSeverity()));
if (result.hasFatalError())
break;
if (result.getSeverity() < fTargetProvider.getStatusSeverity()) {
added = true;
TextEditGroup group = new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_inline);
change.addTextEditGroup(group);
result.merge(inliner.perform(group));
}
}
// do this after we have inlined the method calls. We still want
// to generate the modifications.
result.merge(nestedInvocations);
}
if (!added) {
fChangeManager.remove(unit);
} else {
root.addChild(inliner.getModifications());
ImportRewrite rewrite = inliner.getImportEdit();
if (rewrite.hasRecordedChanges()) {
TextEdit edit = rewrite.rewriteImports(null);
if (edit instanceof MultiTextEdit ? ((MultiTextEdit) edit).getChildrenSize() > 0 : true) {
root.addChild(edit);
change.addTextEditGroup(new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_import, new TextEdit[] { edit }));
}
}
}
} finally {
if (inliner != null)
inliner.dispose();
}
sub.worked(1);
if (sub.isCanceled())
throw new OperationCanceledException();
}
result.merge(searchStatus);
sub.done();
pm.done();
return result;
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project che by eclipse.
the class QuickAssistProcessor method getConvertEnhancedForLoopProposal.
private static boolean getConvertEnhancedForLoopProposal(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
EnhancedForStatement enhancedForStatement = getEnclosingHeader(node, EnhancedForStatement.class, EnhancedForStatement.PARAMETER_PROPERTY, EnhancedForStatement.EXPRESSION_PROPERTY);
if (enhancedForStatement == null) {
return false;
}
SingleVariableDeclaration parameter = enhancedForStatement.getParameter();
IVariableBinding parameterBinding = parameter.resolveBinding();
if (parameterBinding == null) {
return false;
}
Expression initializer = enhancedForStatement.getExpression();
ITypeBinding initializerTypeBinding = initializer.resolveTypeBinding();
if (initializerTypeBinding == null) {
return false;
}
if (resultingCollections == null) {
return true;
}
Statement topLabelStatement = enhancedForStatement;
while (topLabelStatement.getLocationInParent() == LabeledStatement.BODY_PROPERTY) {
topLabelStatement = (Statement) topLabelStatement.getParent();
}
IJavaProject project = context.getCompilationUnit().getJavaProject();
AST ast = node.getAST();
Statement enhancedForBody = enhancedForStatement.getBody();
Collection<String> usedVarNames = Arrays.asList(ASTResolving.getUsedVariableNames(enhancedForBody));
boolean initializerIsArray = initializerTypeBinding.isArray();
//$NON-NLS-1$
ITypeBinding initializerListType = Bindings.findTypeInHierarchy(initializerTypeBinding, "java.util.List");
//$NON-NLS-1$
ITypeBinding initializerIterableType = Bindings.findTypeInHierarchy(initializerTypeBinding, "java.lang.Iterable");
if (initializerIterableType != null) {
String label = CorrectionMessages.QuickAssistProcessor_convert_to_iterator_for_loop;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
//$NON-NLS-1$
String iterNameKey = "iterName";
ASTRewrite rewrite = ASTRewrite.create(ast);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_TO_ITERATOR_FOR_LOOP, image);
// convert 'for' statement
ForStatement forStatement = ast.newForStatement();
// create initializer
MethodInvocation iterInitializer = ast.newMethodInvocation();
//$NON-NLS-1$
iterInitializer.setName(ast.newSimpleName("iterator"));
ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, imports);
//$NON-NLS-1$
Type iterType = ast.newSimpleType(ast.newName(imports.addImport("java.util.Iterator", importRewriteContext)));
if (initializerIterableType.getTypeArguments().length == 1) {
Type iterTypeArgument = imports.addImport(Bindings.normalizeTypeBinding(initializerIterableType.getTypeArguments()[0]), ast, importRewriteContext);
ParameterizedType parameterizedIterType = ast.newParameterizedType(iterType);
parameterizedIterType.typeArguments().add(iterTypeArgument);
iterType = parameterizedIterType;
}
String[] iterNames = StubUtility.getVariableNameSuggestions(NamingConventions.VK_LOCAL, project, iterType, iterInitializer, usedVarNames);
String iterName = iterNames[0];
SimpleName initializerIterName = ast.newSimpleName(iterName);
VariableDeclarationFragment iterFragment = ast.newVariableDeclarationFragment();
iterFragment.setName(initializerIterName);
proposal.addLinkedPosition(rewrite.track(initializerIterName), 0, iterNameKey);
for (int i = 0; i < iterNames.length; i++) {
proposal.addLinkedPositionProposal(iterNameKey, iterNames[i], null);
}
Expression initializerExpression = (Expression) rewrite.createCopyTarget(initializer);
iterInitializer.setExpression(initializerExpression);
iterFragment.setInitializer(iterInitializer);
VariableDeclarationExpression iterVariable = ast.newVariableDeclarationExpression(iterFragment);
iterVariable.setType(iterType);
forStatement.initializers().add(iterVariable);
// create condition
MethodInvocation condition = ast.newMethodInvocation();
//$NON-NLS-1$
condition.setName(ast.newSimpleName("hasNext"));
SimpleName conditionExpression = ast.newSimpleName(iterName);
proposal.addLinkedPosition(rewrite.track(conditionExpression), LinkedPositionGroup.NO_STOP, iterNameKey);
condition.setExpression(conditionExpression);
forStatement.setExpression(condition);
// create 'for' body element variable
VariableDeclarationFragment elementFragment = ast.newVariableDeclarationFragment();
elementFragment.extraDimensions().addAll(DimensionRewrite.copyDimensions(parameter.extraDimensions(), rewrite));
elementFragment.setName((SimpleName) rewrite.createCopyTarget(parameter.getName()));
SimpleName elementIterName = ast.newSimpleName(iterName);
proposal.addLinkedPosition(rewrite.track(elementIterName), LinkedPositionGroup.NO_STOP, iterNameKey);
MethodInvocation getMethodInvocation = ast.newMethodInvocation();
//$NON-NLS-1$
getMethodInvocation.setName(ast.newSimpleName("next"));
getMethodInvocation.setExpression(elementIterName);
elementFragment.setInitializer(getMethodInvocation);
VariableDeclarationStatement elementVariable = ast.newVariableDeclarationStatement(elementFragment);
ModifierRewrite.create(rewrite, elementVariable).copyAllModifiers(parameter, null);
elementVariable.setType((Type) rewrite.createCopyTarget(parameter.getType()));
Block newBody = ast.newBlock();
List<Statement> statements = newBody.statements();
statements.add(elementVariable);
if (enhancedForBody instanceof Block) {
List<Statement> oldStatements = ((Block) enhancedForBody).statements();
if (oldStatements.size() > 0) {
ListRewrite statementsRewrite = rewrite.getListRewrite(enhancedForBody, Block.STATEMENTS_PROPERTY);
Statement oldStatementsCopy = (Statement) statementsRewrite.createCopyTarget(oldStatements.get(0), oldStatements.get(oldStatements.size() - 1));
statements.add(oldStatementsCopy);
}
} else {
statements.add((Statement) rewrite.createCopyTarget(enhancedForBody));
}
forStatement.setBody(newBody);
rewrite.replace(enhancedForStatement, forStatement, null);
resultingCollections.add(proposal);
}
if (initializerIsArray || initializerListType != null) {
String label = CorrectionMessages.QuickAssistProcessor_convert_to_indexed_for_loop;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
//$NON-NLS-1$
String varNameKey = "varName";
//$NON-NLS-1$
String indexNameKey = "indexName";
ASTRewrite rewrite = ASTRewrite.create(ast);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_TO_INDEXED_FOR_LOOP, image);
// create temp variable from initializer if necessary
String varName;
boolean varNameGenerated;
if (initializer instanceof SimpleName) {
varName = ((SimpleName) initializer).getIdentifier();
varNameGenerated = false;
} else {
VariableDeclarationFragment varFragment = ast.newVariableDeclarationFragment();
String[] varNames = StubUtility.getVariableNameSuggestions(NamingConventions.VK_LOCAL, project, initializerTypeBinding, initializer, usedVarNames);
varName = varNames[0];
usedVarNames = new ArrayList<String>(usedVarNames);
usedVarNames.add(varName);
varNameGenerated = true;
SimpleName varNameNode = ast.newSimpleName(varName);
varFragment.setName(varNameNode);
proposal.addLinkedPosition(rewrite.track(varNameNode), 0, varNameKey);
for (int i = 0; i < varNames.length; i++) {
proposal.addLinkedPositionProposal(varNameKey, varNames[i], null);
}
varFragment.setInitializer((Expression) rewrite.createCopyTarget(initializer));
VariableDeclarationStatement varDeclaration = ast.newVariableDeclarationStatement(varFragment);
Type varType;
if (initializerIsArray) {
Type copiedType = DimensionRewrite.copyTypeAndAddDimensions(parameter.getType(), parameter.extraDimensions(), rewrite);
varType = ASTNodeFactory.newArrayType(copiedType);
} else {
ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, imports);
varType = imports.addImport(Bindings.normalizeForDeclarationUse(initializerTypeBinding, ast), ast, importRewriteContext);
}
varDeclaration.setType(varType);
if (!(topLabelStatement.getParent() instanceof Block)) {
Block block = ast.newBlock();
List<Statement> statements = block.statements();
statements.add(varDeclaration);
statements.add((Statement) rewrite.createCopyTarget(topLabelStatement));
rewrite.replace(topLabelStatement, block, null);
} else {
rewrite.getListRewrite(topLabelStatement.getParent(), Block.STATEMENTS_PROPERTY).insertBefore(varDeclaration, topLabelStatement, null);
}
}
// convert 'for' statement
ForStatement forStatement = ast.newForStatement();
// create initializer
VariableDeclarationFragment indexFragment = ast.newVariableDeclarationFragment();
NumberLiteral indexInitializer = ast.newNumberLiteral();
indexFragment.setInitializer(indexInitializer);
PrimitiveType indexType = ast.newPrimitiveType(PrimitiveType.INT);
String[] indexNames = StubUtility.getVariableNameSuggestions(NamingConventions.VK_LOCAL, project, indexType, indexInitializer, usedVarNames);
String indexName = indexNames[0];
SimpleName initializerIndexName = ast.newSimpleName(indexName);
indexFragment.setName(initializerIndexName);
proposal.addLinkedPosition(rewrite.track(initializerIndexName), 0, indexNameKey);
for (int i = 0; i < indexNames.length; i++) {
proposal.addLinkedPositionProposal(indexNameKey, indexNames[i], null);
}
VariableDeclarationExpression indexVariable = ast.newVariableDeclarationExpression(indexFragment);
indexVariable.setType(indexType);
forStatement.initializers().add(indexVariable);
// create condition
InfixExpression condition = ast.newInfixExpression();
condition.setOperator(InfixExpression.Operator.LESS);
SimpleName conditionLeft = ast.newSimpleName(indexName);
proposal.addLinkedPosition(rewrite.track(conditionLeft), LinkedPositionGroup.NO_STOP, indexNameKey);
condition.setLeftOperand(conditionLeft);
SimpleName conditionRightName = ast.newSimpleName(varName);
if (varNameGenerated) {
proposal.addLinkedPosition(rewrite.track(conditionRightName), LinkedPositionGroup.NO_STOP, varNameKey);
}
Expression conditionRight;
if (initializerIsArray) {
//$NON-NLS-1$
conditionRight = ast.newQualifiedName(conditionRightName, ast.newSimpleName("length"));
} else {
MethodInvocation sizeMethodInvocation = ast.newMethodInvocation();
//$NON-NLS-1$
sizeMethodInvocation.setName(ast.newSimpleName("size"));
sizeMethodInvocation.setExpression(conditionRightName);
conditionRight = sizeMethodInvocation;
}
condition.setRightOperand(conditionRight);
forStatement.setExpression(condition);
// create updater
SimpleName indexUpdaterName = ast.newSimpleName(indexName);
proposal.addLinkedPosition(rewrite.track(indexUpdaterName), LinkedPositionGroup.NO_STOP, indexNameKey);
PostfixExpression indexUpdater = ast.newPostfixExpression();
indexUpdater.setOperator(PostfixExpression.Operator.INCREMENT);
indexUpdater.setOperand(indexUpdaterName);
forStatement.updaters().add(indexUpdater);
// create 'for' body element variable
VariableDeclarationFragment elementFragment = ast.newVariableDeclarationFragment();
elementFragment.extraDimensions().addAll(DimensionRewrite.copyDimensions(parameter.extraDimensions(), rewrite));
elementFragment.setName((SimpleName) rewrite.createCopyTarget(parameter.getName()));
SimpleName elementVarName = ast.newSimpleName(varName);
if (varNameGenerated) {
proposal.addLinkedPosition(rewrite.track(elementVarName), LinkedPositionGroup.NO_STOP, varNameKey);
}
SimpleName elementIndexName = ast.newSimpleName(indexName);
proposal.addLinkedPosition(rewrite.track(elementIndexName), LinkedPositionGroup.NO_STOP, indexNameKey);
Expression elementAccess;
if (initializerIsArray) {
ArrayAccess elementArrayAccess = ast.newArrayAccess();
elementArrayAccess.setArray(elementVarName);
elementArrayAccess.setIndex(elementIndexName);
elementAccess = elementArrayAccess;
} else {
MethodInvocation getMethodInvocation = ast.newMethodInvocation();
//$NON-NLS-1$
getMethodInvocation.setName(ast.newSimpleName("get"));
getMethodInvocation.setExpression(elementVarName);
getMethodInvocation.arguments().add(elementIndexName);
elementAccess = getMethodInvocation;
}
elementFragment.setInitializer(elementAccess);
VariableDeclarationStatement elementVariable = ast.newVariableDeclarationStatement(elementFragment);
ModifierRewrite.create(rewrite, elementVariable).copyAllModifiers(parameter, null);
elementVariable.setType((Type) rewrite.createCopyTarget(parameter.getType()));
Block newBody = ast.newBlock();
List<Statement> statements = newBody.statements();
statements.add(elementVariable);
if (enhancedForBody instanceof Block) {
List<Statement> oldStatements = ((Block) enhancedForBody).statements();
if (oldStatements.size() > 0) {
ListRewrite statementsRewrite = rewrite.getListRewrite(enhancedForBody, Block.STATEMENTS_PROPERTY);
Statement oldStatementsCopy = (Statement) statementsRewrite.createCopyTarget(oldStatements.get(0), oldStatements.get(oldStatements.size() - 1));
statements.add(oldStatementsCopy);
}
} else {
statements.add((Statement) rewrite.createCopyTarget(enhancedForBody));
}
forStatement.setBody(newBody);
rewrite.replace(enhancedForStatement, forStatement, null);
resultingCollections.add(proposal);
}
return true;
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project che by eclipse.
the class LocalCorrectionsSubProcessor method addUncaughtExceptionProposals.
public static void addUncaughtExceptionProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException {
ICompilationUnit cu = context.getCompilationUnit();
CompilationUnit astRoot = context.getASTRoot();
ASTNode selectedNode = problem.getCoveringNode(astRoot);
if (selectedNode == null) {
return;
}
while (selectedNode != null && !(selectedNode instanceof Statement) && !(selectedNode instanceof VariableDeclarationExpression)) {
selectedNode = selectedNode.getParent();
}
if (selectedNode == null) {
return;
}
int offset = selectedNode.getStartPosition();
int length = selectedNode.getLength();
int selectionEnd = context.getSelectionOffset() + context.getSelectionLength();
if (selectionEnd > offset + length) {
// extend the selection if more than one statement is selected (bug 72149)
length = selectionEnd - offset;
}
//Surround with proposals
SurroundWithTryCatchRefactoring refactoring = SurroundWithTryCatchRefactoring.create(cu, offset, length);
if (refactoring == null)
return;
refactoring.setLeaveDirty(true);
if (refactoring.checkActivationBasics(astRoot).isOK()) {
String label = CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_trycatch_description;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, cu, refactoring, IProposalRelevance.SURROUND_WITH_TRY_CATCH, image);
proposal.setLinkedProposalModel(refactoring.getLinkedProposalModel());
proposals.add(proposal);
}
if (JavaModelUtil.is17OrHigher(cu.getJavaProject())) {
refactoring = SurroundWithTryCatchRefactoring.create(cu, offset, length, true);
if (refactoring == null)
return;
refactoring.setLeaveDirty(true);
if (refactoring.checkActivationBasics(astRoot).isOK()) {
String label = CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_trymulticatch_description;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
RefactoringCorrectionProposal proposal = new RefactoringCorrectionProposal(label, cu, refactoring, IProposalRelevance.SURROUND_WITH_TRY_MULTICATCH, image);
proposal.setLinkedProposalModel(refactoring.getLinkedProposalModel());
proposals.add(proposal);
}
}
//Catch exception
BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl == null) {
return;
}
ITypeBinding[] uncaughtExceptions = ExceptionAnalyzer.perform(decl, Selection.createFromStartLength(offset, length));
if (uncaughtExceptions.length == 0) {
return;
}
TryStatement surroundingTry = ASTResolving.findParentTryStatement(selectedNode);
AST ast = astRoot.getAST();
if (surroundingTry != null && (ASTNodes.isParent(selectedNode, surroundingTry.getBody()) || selectedNode.getLocationInParent() == TryStatement.RESOURCES_PROPERTY)) {
{
ASTRewrite rewrite = ASTRewrite.create(surroundingTry.getAST());
String label = CorrectionMessages.LocalCorrectionsSubProcessor_addadditionalcatch_description;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_ADDITIONAL_CATCH, image);
ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
CodeScopeBuilder.Scope scope = CodeScopeBuilder.perform(decl, Selection.createFromStartLength(offset, length)).findScope(offset, length);
scope.setCursor(offset);
ListRewrite clausesRewrite = rewrite.getListRewrite(surroundingTry, TryStatement.CATCH_CLAUSES_PROPERTY);
for (int i = 0; i < uncaughtExceptions.length; i++) {
ITypeBinding excBinding = uncaughtExceptions[i];
String varName = StubUtility.getExceptionVariableName(cu.getJavaProject());
String name = scope.createName(varName, false);
SingleVariableDeclaration var = ast.newSingleVariableDeclaration();
var.setName(ast.newSimpleName(name));
var.setType(imports.addImport(excBinding, ast, importRewriteContext));
CatchClause newClause = ast.newCatchClause();
newClause.setException(var);
String catchBody = StubUtility.getCatchBodyContent(cu, excBinding.getName(), name, selectedNode, String.valueOf('\n'));
if (catchBody != null) {
ASTNode node = rewrite.createStringPlaceholder(catchBody, ASTNode.RETURN_STATEMENT);
newClause.getBody().statements().add(node);
}
clausesRewrite.insertLast(newClause, null);
//$NON-NLS-1$
String typeKey = "type" + i;
//$NON-NLS-1$
String nameKey = "name" + i;
proposal.addLinkedPosition(rewrite.track(var.getType()), false, typeKey);
proposal.addLinkedPosition(rewrite.track(var.getName()), false, nameKey);
addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
}
proposals.add(proposal);
}
if (JavaModelUtil.is17OrHigher(cu.getJavaProject())) {
List<CatchClause> catchClauses = surroundingTry.catchClauses();
if (catchClauses != null && catchClauses.size() == 1) {
List<ITypeBinding> filteredExceptions = filterSubtypeExceptions(uncaughtExceptions);
String label = filteredExceptions.size() > 1 ? CorrectionMessages.LocalCorrectionsSubProcessor_addexceptionstoexistingcatch_description : CorrectionMessages.LocalCorrectionsSubProcessor_addexceptiontoexistingcatch_description;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewrite rewrite = ASTRewrite.create(ast);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_EXCEPTIONS_TO_EXISTING_CATCH, image);
ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
CatchClause catchClause = catchClauses.get(0);
Type type = catchClause.getException().getType();
if (type instanceof UnionType) {
UnionType unionType = (UnionType) type;
ListRewrite listRewrite = rewrite.getListRewrite(unionType, UnionType.TYPES_PROPERTY);
for (int i = 0; i < filteredExceptions.size(); i++) {
ITypeBinding excBinding = filteredExceptions.get(i);
Type type2 = imports.addImport(excBinding, ast, importRewriteContext);
listRewrite.insertLast(type2, null);
//$NON-NLS-1$
String typeKey = "type" + i;
proposal.addLinkedPosition(rewrite.track(type2), false, typeKey);
addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
}
} else {
UnionType newUnionType = ast.newUnionType();
List<Type> types = newUnionType.types();
types.add((Type) rewrite.createCopyTarget(type));
for (int i = 0; i < filteredExceptions.size(); i++) {
ITypeBinding excBinding = filteredExceptions.get(i);
Type type2 = imports.addImport(excBinding, ast, importRewriteContext);
types.add(type2);
//$NON-NLS-1$
String typeKey = "type" + i;
proposal.addLinkedPosition(rewrite.track(type2), false, typeKey);
addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
}
rewrite.replace(type, newUnionType, null);
}
proposals.add(proposal);
} else if (catchClauses != null && catchClauses.size() == 0 && uncaughtExceptions.length > 1) {
String label = CorrectionMessages.LocalCorrectionsSubProcessor_addadditionalmulticatch_description;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewrite rewrite = ASTRewrite.create(ast);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_ADDITIONAL_MULTI_CATCH, image);
ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(decl, imports);
CodeScopeBuilder.Scope scope = CodeScopeBuilder.perform(decl, Selection.createFromStartLength(offset, length)).findScope(offset, length);
scope.setCursor(offset);
CatchClause newCatchClause = ast.newCatchClause();
String varName = StubUtility.getExceptionVariableName(cu.getJavaProject());
String name = scope.createName(varName, false);
SingleVariableDeclaration var = ast.newSingleVariableDeclaration();
var.setName(ast.newSimpleName(name));
UnionType newUnionType = ast.newUnionType();
List<Type> types = newUnionType.types();
for (int i = 0; i < uncaughtExceptions.length; i++) {
ITypeBinding excBinding = uncaughtExceptions[i];
Type type2 = imports.addImport(excBinding, ast, importRewriteContext);
types.add(type2);
//$NON-NLS-1$
String typeKey = "type" + i;
proposal.addLinkedPosition(rewrite.track(type2), false, typeKey);
addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
}
//$NON-NLS-1$
String nameKey = "name";
proposal.addLinkedPosition(rewrite.track(var.getName()), false, nameKey);
var.setType(newUnionType);
newCatchClause.setException(var);
//$NON-NLS-1$
String catchBody = StubUtility.getCatchBodyContent(cu, "Exception", name, selectedNode, String.valueOf('\n'));
if (catchBody != null) {
ASTNode node = rewrite.createStringPlaceholder(catchBody, ASTNode.RETURN_STATEMENT);
newCatchClause.getBody().statements().add(node);
}
ListRewrite listRewrite = rewrite.getListRewrite(surroundingTry, TryStatement.CATCH_CLAUSES_PROPERTY);
listRewrite.insertFirst(newCatchClause, null);
proposals.add(proposal);
}
}
}
//Add throws declaration
if (decl instanceof MethodDeclaration) {
MethodDeclaration methodDecl = (MethodDeclaration) decl;
IMethodBinding binding = methodDecl.resolveBinding();
boolean isApplicable = (binding != null);
if (isApplicable) {
IMethodBinding overriddenMethod = Bindings.findOverriddenMethod(binding, true);
if (overriddenMethod != null) {
isApplicable = overriddenMethod.getDeclaringClass().isFromSource();
if (!isApplicable) {
// bug 349051
ITypeBinding[] exceptionTypes = overriddenMethod.getExceptionTypes();
ArrayList<ITypeBinding> unhandledExceptions = new ArrayList<ITypeBinding>(uncaughtExceptions.length);
for (int i = 0; i < uncaughtExceptions.length; i++) {
ITypeBinding curr = uncaughtExceptions[i];
if (isSubtype(curr, exceptionTypes)) {
unhandledExceptions.add(curr);
}
}
uncaughtExceptions = unhandledExceptions.toArray(new ITypeBinding[unhandledExceptions.size()]);
isApplicable |= uncaughtExceptions.length > 0;
}
}
}
if (isApplicable) {
ITypeBinding[] methodExceptions = binding.getExceptionTypes();
ArrayList<ITypeBinding> unhandledExceptions = new ArrayList<ITypeBinding>(uncaughtExceptions.length);
for (int i = 0; i < uncaughtExceptions.length; i++) {
ITypeBinding curr = uncaughtExceptions[i];
if (!isSubtype(curr, methodExceptions)) {
unhandledExceptions.add(curr);
}
}
uncaughtExceptions = unhandledExceptions.toArray(new ITypeBinding[unhandledExceptions.size()]);
List<Type> exceptions = methodDecl.thrownExceptionTypes();
int nExistingExceptions = exceptions.size();
ChangeDescription[] desc = new ChangeDescription[nExistingExceptions + uncaughtExceptions.length];
for (int i = 0; i < exceptions.size(); i++) {
Type elem = exceptions.get(i);
if (isSubtype(elem.resolveBinding(), uncaughtExceptions)) {
desc[i] = new RemoveDescription();
}
}
for (int i = 0; i < uncaughtExceptions.length; i++) {
//$NON-NLS-1$
desc[i + nExistingExceptions] = new InsertDescription(uncaughtExceptions[i], "");
}
String label = CorrectionMessages.LocalCorrectionsSubProcessor_addthrows_description;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ChangeMethodSignatureProposal proposal = new ChangeMethodSignatureProposal(label, cu, astRoot, binding, null, desc, IProposalRelevance.ADD_THROWS_DECLARATION, image);
for (int i = 0; i < uncaughtExceptions.length; i++) {
addExceptionTypeLinkProposals(proposal, uncaughtExceptions[i], proposal.getExceptionTypeGroupId(i + nExistingExceptions));
}
proposal.setCommandId(ADD_EXCEPTION_TO_THROWS_ID);
proposals.add(proposal);
}
}
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite 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;
}
Aggregations