use of org.eclipse.jdt.core.dom.rewrite.ListRewrite in project che by eclipse.
the class AdvancedQuickAssistProcessor method getCastAndAssignIfStatementProposals.
private static boolean getCastAndAssignIfStatementProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
if (node instanceof IfStatement) {
node = ((IfStatement) node).getExpression();
} else if (node instanceof WhileStatement) {
node = ((WhileStatement) node).getExpression();
} else if (node instanceof Block) {
List<Statement> statements = ((Block) node).statements();
if (statements.size() > 0) {
if (context.getSelectionOffset() > statements.get(0).getStartPosition()) {
return false;
}
}
ASTNode parent = node.getParent();
Expression expression = null;
if (parent instanceof IfStatement) {
expression = ((IfStatement) parent).getExpression();
} else if (parent instanceof WhileStatement) {
expression = ((WhileStatement) parent).getExpression();
} else {
return false;
}
if (expression instanceof InstanceofExpression) {
node = expression;
} else {
final ArrayList<InstanceofExpression> nodes = new ArrayList<InstanceofExpression>();
expression.accept(new ASTVisitor() {
@Override
public boolean visit(InstanceofExpression instanceofExpression) {
nodes.add(instanceofExpression);
return false;
}
});
if (nodes.size() != 1) {
return false;
}
node = nodes.get(0);
}
} else {
while (node != null && !(node instanceof InstanceofExpression) && !(node instanceof Statement)) {
node = node.getParent();
}
}
if (!(node instanceof InstanceofExpression)) {
return false;
}
InstanceofExpression expression = (InstanceofExpression) node;
// test that we are the expression of a 'while' or 'if'
while (node.getParent() instanceof Expression) {
node = node.getParent();
}
StructuralPropertyDescriptor locationInParent = node.getLocationInParent();
boolean negated = isNegated(expression);
Statement body = null;
ASTNode insertionPosition = null;
if (negated) {
insertionPosition = node.getParent();
if (locationInParent == IfStatement.EXPRESSION_PROPERTY) {
body = ((IfStatement) node.getParent()).getElseStatement();
if (body != null) {
negated = false;
}
}
if (body == null && insertionPosition.getParent() instanceof Block) {
body = (Statement) insertionPosition.getParent();
}
} else {
if (locationInParent == IfStatement.EXPRESSION_PROPERTY) {
body = ((IfStatement) node.getParent()).getThenStatement();
} else if (locationInParent == WhileStatement.EXPRESSION_PROPERTY) {
body = ((WhileStatement) node.getParent()).getBody();
}
}
if (body == null) {
return false;
}
Type originalType = expression.getRightOperand();
if (originalType.resolveBinding() == null) {
return false;
}
// we could produce quick assist
if (resultingCollections == null) {
return true;
}
//$NON-NLS-1$
final String KEY_NAME = "name";
//$NON-NLS-1$
final String KEY_TYPE = "type";
//
AST ast = expression.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
ICompilationUnit cu = context.getCompilationUnit();
// prepare correction proposal
String label = CorrectionMessages.AdvancedQuickAssistProcessor_castAndAssign;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.CAST_AND_ASSIGN, image);
// prepare possible variable names
List<String> excludedNames = Arrays.asList(ASTResolving.getUsedVariableNames(body));
String[] varNames = suggestLocalVariableNames(cu, originalType.resolveBinding(), excludedNames);
for (int i = 0; i < varNames.length; i++) {
proposal.addLinkedPositionProposal(KEY_NAME, varNames[i], null);
}
CastExpression castExpression = ast.newCastExpression();
castExpression.setExpression((Expression) rewrite.createCopyTarget(expression.getLeftOperand()));
castExpression.setType((Type) ASTNode.copySubtree(ast, originalType));
// prepare new variable declaration
VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment();
vdf.setName(ast.newSimpleName(varNames[0]));
vdf.setInitializer(castExpression);
// prepare new variable declaration statement
VariableDeclarationStatement vds = ast.newVariableDeclarationStatement(vdf);
vds.setType((Type) ASTNode.copySubtree(ast, originalType));
// add new variable declaration statement
if (negated) {
ListRewrite listRewriter = rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY);
listRewriter.insertAfter(vds, insertionPosition, null);
} else {
if (body instanceof Block) {
ListRewrite listRewriter = rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY);
listRewriter.insertAt(vds, 0, null);
} else {
Block newBlock = ast.newBlock();
List<Statement> statements = newBlock.statements();
statements.add(vds);
statements.add((Statement) rewrite.createMoveTarget(body));
rewrite.replace(body, newBlock, null);
}
}
// setup linked positions
proposal.addLinkedPosition(rewrite.track(vdf.getName()), true, KEY_NAME);
proposal.addLinkedPosition(rewrite.track(vds.getType()), false, KEY_TYPE);
proposal.addLinkedPosition(rewrite.track(castExpression.getType()), false, KEY_TYPE);
// set cursor after expression statement
proposal.setEndPosition(rewrite.track(vds));
// add correction proposal
resultingCollections.add(proposal);
return true;
}
use of org.eclipse.jdt.core.dom.rewrite.ListRewrite in project che by eclipse.
the class AdvancedQuickAssistProcessor method getInverseIfIntoContinueInLoopsProposals.
private static boolean getInverseIfIntoContinueInLoopsProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
if (!(covering instanceof IfStatement)) {
return false;
}
IfStatement ifStatement = (IfStatement) covering;
if (ifStatement.getElseStatement() != null) {
return false;
}
// prepare outer control structure and block that contains 'if' statement
ASTNode ifParent = ifStatement.getParent();
Block ifParentBlock = null;
ASTNode ifParentStructure = ifParent;
if (ifParentStructure instanceof Block) {
ifParentBlock = (Block) ifParent;
ifParentStructure = ifParentStructure.getParent();
}
// check that control structure is loop and 'if' statement if last statement
if (!(ifParentStructure instanceof ForStatement) && !(ifParentStructure instanceof WhileStatement)) {
return false;
}
if (ifParentBlock != null && ifParentBlock.statements().indexOf(ifStatement) != ifParentBlock.statements().size() - 1) {
return false;
}
// we could produce quick assist
if (resultingCollections == null) {
return true;
}
//
AST ast = covering.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
// create inverted 'if' statement
Expression inversedExpression = getInversedExpression(rewrite, ifStatement.getExpression());
IfStatement newIf = ast.newIfStatement();
newIf.setExpression(inversedExpression);
newIf.setThenStatement(ast.newContinueStatement());
//
if (ifParentBlock == null) {
// if there is no block, create it
ifParentBlock = ast.newBlock();
ifParentBlock.statements().add(newIf);
for (Iterator<Statement> iter = getUnwrappedStatements(ifStatement.getThenStatement()).iterator(); iter.hasNext(); ) {
Statement statement = iter.next();
ifParentBlock.statements().add(rewrite.createMoveTarget(statement));
}
// replace 'if' statement as body with new block
if (ifParentStructure instanceof ForStatement) {
rewrite.set(ifParentStructure, ForStatement.BODY_PROPERTY, ifParentBlock, null);
} else if (ifParentStructure instanceof WhileStatement) {
rewrite.set(ifParentStructure, WhileStatement.BODY_PROPERTY, ifParentBlock, null);
}
} else {
// if there was block, replace
ListRewrite listRewriter = rewrite.getListRewrite(ifParentBlock, (ChildListPropertyDescriptor) ifStatement.getLocationInParent());
listRewriter.replace(ifStatement, newIf, null);
// add statements from 'then' to the end of block
for (Iterator<Statement> iter = getUnwrappedStatements(ifStatement.getThenStatement()).iterator(); iter.hasNext(); ) {
Statement statement = iter.next();
listRewriter.insertLast(rewrite.createMoveTarget(statement), null);
}
}
// add correction proposal
String label = CorrectionMessages.AdvancedQuickAssistProcessor_inverseIfToContinue_description;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERT_IF_TO_CONTINUE, image);
resultingCollections.add(proposal);
return true;
}
use of org.eclipse.jdt.core.dom.rewrite.ListRewrite in project che by eclipse.
the class AdvancedQuickAssistProcessor method addExplicitTypeArgumentsIfNecessary.
private static void addExplicitTypeArgumentsIfNecessary(ASTRewrite rewrite, ASTRewriteCorrectionProposal proposal, Expression invocation) {
if (Invocations.isResolvedTypeInferredFromExpectedType(invocation)) {
ITypeBinding[] typeArguments = Invocations.getInferredTypeArguments(invocation);
if (typeArguments == null)
return;
ImportRewrite importRewrite = proposal.getImportRewrite();
if (importRewrite == null) {
importRewrite = proposal.createImportRewrite((CompilationUnit) invocation.getRoot());
}
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(invocation, importRewrite);
AST ast = invocation.getAST();
ListRewrite typeArgsRewrite = Invocations.getInferredTypeArgumentsRewrite(rewrite, invocation);
for (int i = 0; i < typeArguments.length; i++) {
Type typeArgumentNode = importRewrite.addImport(typeArguments[i], ast, importRewriteContext);
typeArgsRewrite.insertLast(typeArgumentNode, null);
}
if (invocation instanceof MethodInvocation) {
MethodInvocation methodInvocation = (MethodInvocation) invocation;
Expression expression = methodInvocation.getExpression();
if (expression == null) {
IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
if (methodBinding != null && Modifier.isStatic(methodBinding.getModifiers())) {
expression = ast.newName(importRewrite.addImport(methodBinding.getDeclaringClass().getTypeDeclaration(), importRewriteContext));
} else {
expression = ast.newThisExpression();
}
rewrite.set(invocation, MethodInvocation.EXPRESSION_PROPERTY, expression, null);
}
}
}
}
use of org.eclipse.jdt.core.dom.rewrite.ListRewrite in project che by eclipse.
the class QuickAssistProcessor method getSplitVariableProposals.
private static boolean getSplitVariableProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
VariableDeclarationFragment fragment;
if (node instanceof VariableDeclarationFragment) {
fragment = (VariableDeclarationFragment) node;
} else if (node.getLocationInParent() == VariableDeclarationFragment.NAME_PROPERTY) {
fragment = (VariableDeclarationFragment) node.getParent();
} else {
return false;
}
if (fragment.getInitializer() == null) {
return false;
}
Statement statement;
ASTNode fragParent = fragment.getParent();
if (fragParent instanceof VariableDeclarationStatement) {
statement = (VariableDeclarationStatement) fragParent;
} else if (fragParent instanceof VariableDeclarationExpression) {
if (fragParent.getLocationInParent() == TryStatement.RESOURCES_PROPERTY) {
return false;
}
statement = (Statement) fragParent.getParent();
} else {
return false;
}
// statement is ForStatement or VariableDeclarationStatement
ASTNode statementParent = statement.getParent();
StructuralPropertyDescriptor property = statement.getLocationInParent();
if (!property.isChildListProperty()) {
return false;
}
List<? extends ASTNode> list = ASTNodes.getChildListProperty(statementParent, (ChildListPropertyDescriptor) property);
if (resultingCollections == null) {
return true;
}
AST ast = statement.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
String label = CorrectionMessages.QuickAssistProcessor_splitdeclaration_description;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.SPLIT_VARIABLE_DECLARATION, image);
boolean commandConflict = false;
for (Iterator<ICommandAccess> iterator = resultingCollections.iterator(); iterator.hasNext(); ) {
Object completionProposal = iterator.next();
if (completionProposal instanceof ChangeCorrectionProposal) {
if (SPLIT_JOIN_VARIABLE_DECLARATION_ID.equals(((ChangeCorrectionProposal) completionProposal).getCommandId())) {
commandConflict = true;
}
}
}
if (!commandConflict) {
proposal.setCommandId(SPLIT_JOIN_VARIABLE_DECLARATION_ID);
}
Statement newStatement;
int insertIndex = list.indexOf(statement);
Expression placeholder = (Expression) rewrite.createMoveTarget(fragment.getInitializer());
ITypeBinding binding = fragment.getInitializer().resolveTypeBinding();
if (placeholder instanceof ArrayInitializer && binding != null && binding.isArray()) {
ArrayCreation creation = ast.newArrayCreation();
creation.setInitializer((ArrayInitializer) placeholder);
final ITypeBinding componentType = binding.getElementType();
Type type = null;
if (componentType.isPrimitive())
type = ast.newPrimitiveType(PrimitiveType.toCode(componentType.getName()));
else
type = ast.newSimpleType(ast.newSimpleName(componentType.getName()));
creation.setType(ast.newArrayType(type, binding.getDimensions()));
placeholder = creation;
}
Assignment assignment = ast.newAssignment();
assignment.setRightHandSide(placeholder);
assignment.setLeftHandSide(ast.newSimpleName(fragment.getName().getIdentifier()));
if (statement instanceof VariableDeclarationStatement) {
newStatement = ast.newExpressionStatement(assignment);
// add after declaration
insertIndex += 1;
} else {
rewrite.replace(fragment.getParent(), assignment, null);
VariableDeclarationFragment newFrag = ast.newVariableDeclarationFragment();
newFrag.setName(ast.newSimpleName(fragment.getName().getIdentifier()));
newFrag.extraDimensions().addAll(DimensionRewrite.copyDimensions(fragment.extraDimensions(), rewrite));
VariableDeclarationExpression oldVarDecl = (VariableDeclarationExpression) fragParent;
VariableDeclarationStatement newVarDec = ast.newVariableDeclarationStatement(newFrag);
newVarDec.setType((Type) rewrite.createCopyTarget(oldVarDecl.getType()));
newVarDec.modifiers().addAll(ASTNodeFactory.newModifiers(ast, oldVarDecl.getModifiers()));
newStatement = newVarDec;
}
ListRewrite listRewriter = rewrite.getListRewrite(statementParent, (ChildListPropertyDescriptor) property);
listRewriter.insertAt(newStatement, insertIndex, null);
resultingCollections.add(proposal);
return true;
}
use of org.eclipse.jdt.core.dom.rewrite.ListRewrite in project che by eclipse.
the class AdvancedQuickAssistProcessor method getConvertToIfReturnProposals.
private static boolean getConvertToIfReturnProposals(IInvocationContext context, ASTNode coveringNode, ArrayList<ICommandAccess> resultingCollections) {
if (!(coveringNode instanceof IfStatement)) {
return false;
}
IfStatement ifStatement = (IfStatement) coveringNode;
if (ifStatement.getElseStatement() != null) {
return false;
}
// enclosing lambda or method should return 'void'
LambdaExpression enclosingLambda = ASTResolving.findEnclosingLambdaExpression(ifStatement);
if (enclosingLambda != null) {
IMethodBinding lambdaMethodBinding = enclosingLambda.resolveMethodBinding();
if (lambdaMethodBinding == null) {
return false;
}
if (!(ifStatement.getAST().resolveWellKnownType("void").equals(lambdaMethodBinding.getReturnType()))) {
//$NON-NLS-1$
return false;
}
} else {
MethodDeclaration coveringMethod = ASTResolving.findParentMethodDeclaration(ifStatement);
if (coveringMethod == null) {
return false;
}
Type returnType = coveringMethod.getReturnType2();
if (!isVoid(returnType)) {
return false;
}
}
// should be present in a block
if (!(ifStatement.getParent() instanceof Block)) {
return false;
}
// should have at least one statement in 'then' part other than 'return'
Statement thenStatement = ifStatement.getThenStatement();
if (thenStatement instanceof ReturnStatement) {
return false;
}
if (thenStatement instanceof Block) {
List<Statement> thenStatements = ((Block) thenStatement).statements();
if (thenStatements.isEmpty() || (thenStatements.size() == 1 && (thenStatements.get(0) instanceof ReturnStatement))) {
return false;
}
}
// should have no further executable statement
if (!isLastStatementInEnclosingMethodOrLambda(ifStatement)) {
return false;
}
// we could produce quick assist
if (resultingCollections == null) {
return true;
}
AST ast = coveringNode.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
// create inverted 'if' statement
Expression inversedExpression = getInversedExpression(rewrite, ifStatement.getExpression());
IfStatement newIf = ast.newIfStatement();
newIf.setExpression(inversedExpression);
newIf.setThenStatement(ast.newReturnStatement());
ListRewrite listRewriter = rewrite.getListRewrite(ifStatement.getParent(), (ChildListPropertyDescriptor) ifStatement.getLocationInParent());
listRewriter.replace(ifStatement, newIf, null);
// remove last 'return' in 'then' block
ArrayList<Statement> statements = getUnwrappedStatements(ifStatement.getThenStatement());
Statement lastStatement = statements.get(statements.size() - 1);
if (lastStatement instanceof ReturnStatement) {
statements.remove(lastStatement);
}
// add statements from 'then' to the end of block
for (Statement statement : statements) {
listRewriter.insertLast(rewrite.createMoveTarget(statement), null);
}
// add correction proposal
String label = CorrectionMessages.AdvancedQuickAssistProcessor_convertToIfReturn;
Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_TO_IF_RETURN, image);
resultingCollections.add(proposal);
return true;
}
Aggregations