use of org.eclipse.jdt.core.dom.rewrite.ASTRewrite 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.ASTRewrite in project che by eclipse.
the class QuickAssistProcessor method getCatchClauseToThrowsProposals.
public static boolean getCatchClauseToThrowsProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
CatchClause catchClause = (CatchClause) ASTResolving.findAncestor(node, ASTNode.CATCH_CLAUSE);
if (catchClause == null) {
return false;
}
Statement statement = ASTResolving.findParentStatement(node);
if (statement != catchClause.getParent() && statement != catchClause.getBody()) {
// selection is in a statement inside the body
return false;
}
Type type = catchClause.getException().getType();
if (!type.isSimpleType() && !type.isUnionType() && !type.isNameQualifiedType()) {
return false;
}
BodyDeclaration bodyDeclaration = ASTResolving.findParentBodyDeclaration(catchClause);
if (!(bodyDeclaration instanceof MethodDeclaration) && !(bodyDeclaration instanceof Initializer)) {
return false;
}
if (resultingCollections == null) {
return true;
}
AST ast = bodyDeclaration.getAST();
Image image = JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
Type selectedMultiCatchType = null;
if (type.isUnionType() && node instanceof Name) {
Name topMostName = ASTNodes.getTopMostName((Name) node);
ASTNode parent = topMostName.getParent();
if (parent instanceof SimpleType) {
selectedMultiCatchType = (SimpleType) parent;
} else if (parent instanceof NameQualifiedType) {
selectedMultiCatchType = (NameQualifiedType) parent;
}
}
if (bodyDeclaration instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration;
ASTRewrite rewrite = ASTRewrite.create(ast);
if (selectedMultiCatchType != null) {
removeException(rewrite, (UnionType) type, selectedMultiCatchType);
addExceptionToThrows(ast, methodDeclaration, rewrite, selectedMultiCatchType);
String label = CorrectionMessages.QuickAssistProcessor_exceptiontothrows_description;
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_EXCEPTION_WITH_THROWS, image);
resultingCollections.add(proposal);
} else {
removeCatchBlock(rewrite, catchClause);
if (type.isUnionType()) {
UnionType unionType = (UnionType) type;
List<Type> types = unionType.types();
for (Type elementType : types) {
if (!(elementType instanceof SimpleType || elementType instanceof NameQualifiedType))
return false;
addExceptionToThrows(ast, methodDeclaration, rewrite, elementType);
}
} else {
addExceptionToThrows(ast, methodDeclaration, rewrite, type);
}
String label = CorrectionMessages.QuickAssistProcessor_catchclausetothrows_description;
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_CATCH_CLAUSE_WITH_THROWS, image);
resultingCollections.add(proposal);
}
}
{
// for initializers or method declarations
ASTRewrite rewrite = ASTRewrite.create(ast);
if (selectedMultiCatchType != null) {
removeException(rewrite, (UnionType) type, selectedMultiCatchType);
String label = CorrectionMessages.QuickAssistProcessor_removeexception_description;
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_EXCEPTION, image);
resultingCollections.add(proposal);
} else {
removeCatchBlock(rewrite, catchClause);
String label = CorrectionMessages.QuickAssistProcessor_removecatchclause_description;
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_CATCH_CLAUSE, image);
resultingCollections.add(proposal);
}
}
return true;
}
use of org.eclipse.jdt.core.dom.rewrite.ASTRewrite in project che by eclipse.
the class QuickAssistProcessor method getAddBlockProposals.
private static boolean getAddBlockProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
if (!(node instanceof Statement)) {
return false;
}
/*
* only show the quick assist when the selection is of the control statement keywords (if, else, while,...)
* but not inside the statement or the if expression.
*/
if (!isControlStatementWithBlock(node) && isControlStatementWithBlock(node.getParent())) {
int statementStart = node.getStartPosition();
int statementEnd = statementStart + node.getLength();
int offset = context.getSelectionOffset();
int length = context.getSelectionLength();
if (length == 0) {
if (offset != statementEnd) {
// cursor at end
return false;
}
} else {
if (offset > statementStart || offset + length < statementEnd) {
// statement selected
return false;
}
}
node = node.getParent();
}
StructuralPropertyDescriptor childProperty = null;
ASTNode child = null;
switch(node.getNodeType()) {
case ASTNode.IF_STATEMENT:
ASTNode then = ((IfStatement) node).getThenStatement();
ASTNode elseStatement = ((IfStatement) node).getElseStatement();
if ((then instanceof Block) && (elseStatement instanceof Block || elseStatement == null)) {
break;
}
int thenEnd = then.getStartPosition() + then.getLength();
int selectionEnd = context.getSelectionOffset() + context.getSelectionLength();
if (!(then instanceof Block)) {
if (selectionEnd <= thenEnd) {
childProperty = IfStatement.THEN_STATEMENT_PROPERTY;
child = then;
break;
} else if (elseStatement != null && selectionEnd < elseStatement.getStartPosition()) {
// find out if we are before or after the 'else' keyword
try {
TokenScanner scanner = new TokenScanner(context.getCompilationUnit());
int elseTokenStart = scanner.getNextStartOffset(thenEnd, true);
if (selectionEnd < elseTokenStart) {
childProperty = IfStatement.THEN_STATEMENT_PROPERTY;
child = then;
break;
}
} catch (CoreException e) {
// ignore
}
}
}
if (elseStatement != null && !(elseStatement instanceof Block) && context.getSelectionOffset() >= thenEnd) {
childProperty = IfStatement.ELSE_STATEMENT_PROPERTY;
child = elseStatement;
}
break;
case ASTNode.WHILE_STATEMENT:
ASTNode whileBody = ((WhileStatement) node).getBody();
if (!(whileBody instanceof Block)) {
childProperty = WhileStatement.BODY_PROPERTY;
child = whileBody;
}
break;
case ASTNode.FOR_STATEMENT:
ASTNode forBody = ((ForStatement) node).getBody();
if (!(forBody instanceof Block)) {
childProperty = ForStatement.BODY_PROPERTY;
child = forBody;
}
break;
case ASTNode.ENHANCED_FOR_STATEMENT:
ASTNode enhancedForBody = ((EnhancedForStatement) node).getBody();
if (!(enhancedForBody instanceof Block)) {
childProperty = EnhancedForStatement.BODY_PROPERTY;
child = enhancedForBody;
}
break;
case ASTNode.DO_STATEMENT:
ASTNode doBody = ((DoStatement) node).getBody();
if (!(doBody instanceof Block)) {
childProperty = DoStatement.BODY_PROPERTY;
child = doBody;
}
break;
default:
}
if (child == null) {
return false;
}
if (resultingCollections == null) {
return true;
}
AST ast = node.getAST();
{
ASTRewrite rewrite = ASTRewrite.create(ast);
ASTNode childPlaceholder = rewrite.createMoveTarget(child);
Block replacingBody = ast.newBlock();
replacingBody.statements().add(childPlaceholder);
rewrite.set(node, childProperty, replacingBody, null);
String label;
if (childProperty == IfStatement.THEN_STATEMENT_PROPERTY) {
label = CorrectionMessages.QuickAssistProcessor_replacethenwithblock_description;
} else if (childProperty == IfStatement.ELSE_STATEMENT_PROPERTY) {
label = CorrectionMessages.QuickAssistProcessor_replaceelsewithblock_description;
} else {
label = CorrectionMessages.QuickAssistProcessor_replacebodywithblock_description;
}
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_BLOCK, image);
proposal.setCommandId(ADD_BLOCK_ID);
proposal.setEndPosition(rewrite.track(child));
resultingCollections.add(proposal);
}
if (node.getNodeType() == ASTNode.IF_STATEMENT) {
ASTRewrite rewrite = ASTRewrite.create(ast);
while (node.getLocationInParent() == IfStatement.ELSE_STATEMENT_PROPERTY) {
node = node.getParent();
}
boolean missingBlockFound = false;
boolean foundElse = false;
IfStatement ifStatement;
Statement thenStatment;
Statement elseStatment;
do {
ifStatement = (IfStatement) node;
thenStatment = ifStatement.getThenStatement();
elseStatment = ifStatement.getElseStatement();
if (!(thenStatment instanceof Block)) {
ASTNode childPlaceholder1 = rewrite.createMoveTarget(thenStatment);
Block replacingBody1 = ast.newBlock();
replacingBody1.statements().add(childPlaceholder1);
rewrite.set(ifStatement, IfStatement.THEN_STATEMENT_PROPERTY, replacingBody1, null);
if (thenStatment != child) {
missingBlockFound = true;
}
}
if (elseStatment != null) {
foundElse = true;
}
node = elseStatment;
} while (elseStatment instanceof IfStatement);
if (elseStatment != null && !(elseStatment instanceof Block)) {
ASTNode childPlaceholder2 = rewrite.createMoveTarget(elseStatment);
Block replacingBody2 = ast.newBlock();
replacingBody2.statements().add(childPlaceholder2);
rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, replacingBody2, null);
if (elseStatment != child) {
missingBlockFound = true;
}
}
if (missingBlockFound && foundElse) {
String label = CorrectionMessages.QuickAssistProcessor_replacethenelsewithblock_description;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CHANGE_IF_ELSE_TO_BLOCK, image);
resultingCollections.add(proposal);
}
}
return true;
}
use of org.eclipse.jdt.core.dom.rewrite.ASTRewrite 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.ASTRewrite 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