use of org.eclipse.jdt.core.dom.rewrite.ASTRewrite in project che by eclipse.
the class SourceProvider method getCodeBlocks.
public String[] getCodeBlocks(CallContext context, ImportRewrite importRewrite) throws CoreException {
final ASTRewrite rewriter = ASTRewrite.create(fDeclaration.getAST());
replaceParameterWithExpression(rewriter, context, importRewrite);
updateImplicitReceivers(rewriter, context);
makeNamesUnique(rewriter, context.scope);
updateTypeReferences(rewriter, context);
updateStaticReferences(rewriter, context);
updateTypeVariables(rewriter, context);
updateMethodTypeVariable(rewriter, context);
List<IRegion> ranges = null;
if (hasReturnValue()) {
if (context.callMode == ASTNode.RETURN_STATEMENT) {
ranges = getStatementRanges();
} else {
ranges = getExpressionRanges();
}
} else {
ASTNode last = getLastStatement();
if (last != null && last.getNodeType() == ASTNode.RETURN_STATEMENT) {
ranges = getReturnStatementRanges();
} else {
ranges = getStatementRanges();
}
}
final TextEdit dummy = rewriter.rewriteAST(fDocument, fTypeRoot.getJavaProject().getOptions(true));
int size = ranges.size();
RangeMarker[] markers = new RangeMarker[size];
for (int i = 0; i < markers.length; i++) {
IRegion range = ranges.get(i);
markers[i] = new RangeMarker(range.getOffset(), range.getLength());
}
int split;
if (size <= 1) {
split = Integer.MAX_VALUE;
} else {
IRegion region = ranges.get(0);
split = region.getOffset() + region.getLength();
}
TextEdit[] edits = dummy.removeChildren();
for (int i = 0; i < edits.length; i++) {
TextEdit edit = edits[i];
int pos = edit.getOffset() >= split ? 1 : 0;
markers[pos].addChild(edit);
}
MultiTextEdit root = new MultiTextEdit(0, fDocument.getLength());
root.addChildren(markers);
try {
TextEditProcessor processor = new TextEditProcessor(fDocument, root, TextEdit.CREATE_UNDO | TextEdit.UPDATE_REGIONS);
UndoEdit undo = processor.performEdits();
String[] result = getBlocks(markers);
// It is faster to undo the changes than coping the buffer over and over again.
processor = new TextEditProcessor(fDocument, undo, TextEdit.UPDATE_REGIONS);
processor.performEdits();
return result;
} catch (MalformedTreeException exception) {
JavaPlugin.log(exception);
} catch (BadLocationException exception) {
JavaPlugin.log(exception);
}
return new String[] {};
}
use of org.eclipse.jdt.core.dom.rewrite.ASTRewrite in project che by eclipse.
the class PromoteTempToFieldRefactoring method createChange.
/*
* @see org.eclipse.jdt.internal.corext.refactoring.base.IRefactoring#createChange(org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
//$NON-NLS-1$
pm.beginTask("", 1);
try {
if (fFieldName.length() == 0) {
fFieldName = getInitialFieldName();
}
ASTRewrite rewrite = ASTRewrite.create(fCompilationUnitNode.getAST());
if (fInitializeIn == INITIALIZE_IN_METHOD && tempHasInitializer())
addLocalDeclarationSplit(rewrite);
else
addLocalDeclarationRemoval(rewrite);
if (fInitializeIn == INITIALIZE_IN_CONSTRUCTOR)
addInitializersToConstructors(rewrite);
addTempRenames(rewrite);
addFieldDeclaration(rewrite);
CompilationUnitChange result = new CompilationUnitChange(RefactoringCoreMessages.PromoteTempToFieldRefactoring_name, fCu);
result.setDescriptor(new RefactoringChangeDescriptor(getRefactoringDescriptor()));
TextEdit resultingEdits = rewrite.rewriteAST();
TextChangeCompatibility.addTextEdit(result, RefactoringCoreMessages.PromoteTempToFieldRefactoring_editName, resultingEdits);
return result;
} finally {
pm.done();
}
}
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;
}
Aggregations