use of org.eclipse.jdt.core.dom.rewrite.ListRewrite in project che by eclipse.
the class DelegateCreator method createEdit.
/**
* Performs the actual rewriting and adds an edit to the ASTRewrite set with
* {@link #setSourceRewrite(CompilationUnitRewrite)}.
*
* @throws JavaModelException
*/
public void createEdit() throws JavaModelException {
try {
IDocument document = new Document(fDelegateRewrite.getCu().getBuffer().getContents());
TextEdit edit = fDelegateRewrite.getASTRewrite().rewriteAST(document, fDelegateRewrite.getCu().getJavaProject().getOptions(true));
edit.apply(document, TextEdit.UPDATE_REGIONS);
String newSource = Strings.trimIndentation(document.get(fTrackedPosition.getStartPosition(), fTrackedPosition.getLength()), fPreferences.tabWidth, fPreferences.indentWidth, false);
ASTNode placeholder = fOriginalRewrite.getASTRewrite().createStringPlaceholder(newSource, fDeclaration.getNodeType());
CategorizedTextEditGroup groupDescription = fOriginalRewrite.createCategorizedGroupDescription(getTextEditGroupLabel(), CATEGORY_DELEGATE);
ListRewrite bodyDeclarationsListRewrite = fOriginalRewrite.getASTRewrite().getListRewrite(fDeclaration.getParent(), getTypeBodyDeclarationsProperty());
if (fCopy)
if (fInsertBefore)
bodyDeclarationsListRewrite.insertBefore(placeholder, fDeclaration, groupDescription);
else
bodyDeclarationsListRewrite.insertAfter(placeholder, fDeclaration, groupDescription);
else
bodyDeclarationsListRewrite.replace(fDeclaration, placeholder, groupDescription);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
use of org.eclipse.jdt.core.dom.rewrite.ListRewrite 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.ListRewrite in project che by eclipse.
the class QuickAssistProcessor method addExceptionToThrows.
private static void addExceptionToThrows(AST ast, MethodDeclaration methodDeclaration, ASTRewrite rewrite, Type type2) {
ITypeBinding binding = type2.resolveBinding();
if (binding == null || isNotYetThrown(binding, methodDeclaration.thrownExceptionTypes())) {
Type newType = (Type) ASTNode.copySubtree(ast, type2);
ListRewrite listRewriter = rewrite.getListRewrite(methodDeclaration, MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY);
listRewriter.insertLast(newType, null);
}
}
use of org.eclipse.jdt.core.dom.rewrite.ListRewrite 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.ListRewrite in project che by eclipse.
the class LocalCorrectionsSubProcessor method addCasesOmittedProposals.
public static void addCasesOmittedProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
ASTNode selectedNode = problem.getCoveringNode(context.getASTRoot());
if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) {
AST ast = selectedNode.getAST();
SwitchStatement parent = (SwitchStatement) selectedNode.getParent();
for (Statement statement : (List<Statement>) parent.statements()) {
if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) {
// insert //$CASES-OMITTED$:
ASTRewrite rewrite = ASTRewrite.create(ast);
rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
ListRewrite listRewrite = rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY);
ASTNode casesOmittedComment = //$NON-NLS-1$
rewrite.createStringPlaceholder("//$CASES-OMITTED$", ASTNode.EMPTY_STATEMENT);
listRewrite.insertBefore(casesOmittedComment, statement, null);
String label = CorrectionMessages.LocalCorrectionsSubProcessor_insert_cases_omitted;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_CASES_OMITTED, image);
proposals.add(proposal);
break;
}
}
}
}
Aggregations