Search in sources :

Example 1 with ASTRewriteCorrectionProposal

use of org.eclipse.jdt.ls.core.internal.corrections.proposals.ASTRewriteCorrectionProposal in project eclipse.jdt.ls by eclipse.

the class AdvancedQuickAssistProcessor method getSplitAndConditionProposals.

// 
// public boolean hasAssists(IInvocationContext context) throws CoreException {
// ASTNode coveringNode = context.getCoveringNode();
// if (coveringNode != null) {
// ArrayList<ASTNode> coveredNodes = getFullyCoveredNodes(context, coveringNode);
// return getConvertToIfReturnProposals(context, coveringNode, null) || getInverseIfProposals(context, coveringNode, null) || getIfReturnIntoIfElseAtEndOfVoidMethodProposals(context, coveringNode, null)
// || getInverseIfContinueIntoIfThenInLoopsProposals(context, coveringNode, null) || getInverseIfIntoContinueInLoopsProposals(context, coveringNode, null)
// || getInverseConditionProposals(context, coveringNode, coveredNodes, null) || getRemoveExtraParenthesesProposals(context, coveringNode, coveredNodes, null)
// || getAddParanoidalParenthesesProposals(context, coveredNodes, null) || getAddParenthesesForExpressionProposals(context, coveringNode, null) || getJoinAndIfStatementsProposals(context, coveringNode, null)
// || getSplitAndConditionProposals(context, coveringNode, null) || getJoinOrIfStatementsProposals(context, coveringNode, coveredNodes, null) || getSplitOrConditionProposals(context, coveringNode, null)
// || getInverseConditionalExpressionProposals(context, coveringNode, null) || getExchangeInnerAndOuterIfConditionsProposals(context, coveringNode, null) || getExchangeOperandsProposals(context, coveringNode, null)
// || getCastAndAssignIfStatementProposals(context, coveringNode, null) || getCombineStringProposals(context, coveringNode, null) || getPickOutStringProposals(context, coveringNode, null)
// || getReplaceIfElseWithConditionalProposals(context, coveringNode, null) || getReplaceConditionalWithIfElseProposals(context, coveringNode, null) || getInverseLocalVariableProposals(context, coveringNode, null)
// || getPushNegationDownProposals(context, coveringNode, null) || getPullNegationUpProposals(context, coveredNodes, null) || getJoinIfListInIfElseIfProposals(context, coveringNode, coveredNodes, null)
// || getConvertSwitchToIfProposals(context, coveringNode, null) || getConvertIfElseToSwitchProposals(context, coveringNode, null)
// || GetterSetterCorrectionSubProcessor.addGetterSetterProposal(context, coveringNode, null, null);
// }
// return false;
// }
// 
// @Override
// public IJavaCompletionProposal[] getAssists(IInvocationContext context, IProblemLocation[] locations) throws CoreException {
// ASTNode coveringNode = context.getCoveringNode();
// if (coveringNode != null) {
// ArrayList<ASTNode> coveredNodes = getFullyCoveredNodes(context, coveringNode);
// ArrayList<ICommandAccess> resultingCollections = new ArrayList<>();
// 
// //quick assists that show up also if there is an error/warning
// getReplaceConditionalWithIfElseProposals(context, coveringNode, resultingCollections);
// 
// if (QuickAssistProcessor.noErrorsAtLocation(locations)) {
// getConvertToIfReturnProposals(context, coveringNode, resultingCollections);
// getInverseIfProposals(context, coveringNode, resultingCollections);
// getIfReturnIntoIfElseAtEndOfVoidMethodProposals(context, coveringNode, resultingCollections);
// getInverseIfContinueIntoIfThenInLoopsProposals(context, coveringNode, resultingCollections);
// getInverseIfIntoContinueInLoopsProposals(context, coveringNode, resultingCollections);
// getInverseConditionProposals(context, coveringNode, coveredNodes, resultingCollections);
// getRemoveExtraParenthesesProposals(context, coveringNode, coveredNodes, resultingCollections);
// getAddParanoidalParenthesesProposals(context, coveredNodes, resultingCollections);
// getAddParenthesesForExpressionProposals(context, coveringNode, resultingCollections);
// getJoinAndIfStatementsProposals(context, coveringNode, resultingCollections);
// getSplitAndConditionProposals(context, coveringNode, resultingCollections);
// getJoinOrIfStatementsProposals(context, coveringNode, coveredNodes, resultingCollections);
// getSplitOrConditionProposals(context, coveringNode, resultingCollections);
// getInverseConditionalExpressionProposals(context, coveringNode, resultingCollections);
// getExchangeInnerAndOuterIfConditionsProposals(context, coveringNode, resultingCollections);
// getExchangeOperandsProposals(context, coveringNode, resultingCollections);
// getCastAndAssignIfStatementProposals(context, coveringNode, resultingCollections);
// getCombineStringProposals(context, coveringNode, resultingCollections);
// getPickOutStringProposals(context, coveringNode, resultingCollections);
// getReplaceIfElseWithConditionalProposals(context, coveringNode, resultingCollections);
// getInverseLocalVariableProposals(context, coveringNode, resultingCollections);
// getPushNegationDownProposals(context, coveringNode, resultingCollections);
// getPullNegationUpProposals(context, coveredNodes, resultingCollections);
// getJoinIfListInIfElseIfProposals(context, coveringNode, coveredNodes, resultingCollections);
// getConvertSwitchToIfProposals(context, coveringNode, resultingCollections);
// getConvertIfElseToSwitchProposals(context, coveringNode, resultingCollections);
// GetterSetterCorrectionSubProcessor.addGetterSetterProposal(context, coveringNode, locations, resultingCollections);
// }
// 
// return resultingCollections.toArray(new IJavaCompletionProposal[resultingCollections.size()]);
// }
// return null;
// }
// 
// 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;
// }
// 
// private static boolean isVoid(Type type) {
// return type instanceof PrimitiveType && ((PrimitiveType) type).getPrimitiveTypeCode() == PrimitiveType.VOID;
// }
// 
// private static boolean isLastStatementInEnclosingMethodOrLambda(Statement statement) {
// ASTNode currentStructure = statement;
// ASTNode currentParent = statement.getParent();
// while (!(currentParent instanceof MethodDeclaration || currentParent instanceof LambdaExpression)) {
// // should not be in a loop
// if (currentParent instanceof ForStatement || currentParent instanceof EnhancedForStatement || currentParent instanceof WhileStatement || currentParent instanceof DoStatement) {
// return false;
// }
// if (currentParent instanceof Block) {
// Block parentBlock = (Block) currentParent;
// if (parentBlock.statements().indexOf(currentStructure) != parentBlock.statements().size() - 1) { // not last statement in the block
// return false;
// }
// }
// currentStructure = currentParent;
// currentParent = currentParent.getParent();
// }
// return true;
// }
// 
// private static boolean getIfReturnIntoIfElseAtEndOfVoidMethodProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
// if (!(covering instanceof IfStatement)) {
// return false;
// }
// IfStatement ifStatement = (IfStatement) covering;
// if (ifStatement.getElseStatement() != null) {
// return false;
// }
// // 'then' block should have 'return' as last statement
// Statement thenStatement = ifStatement.getThenStatement();
// if (!(thenStatement instanceof Block)) {
// return false;
// }
// Block thenBlock = (Block) thenStatement;
// List<Statement> thenStatements = thenBlock.statements();
// if (thenStatements.isEmpty() || !(thenStatements.get(thenStatements.size() - 1) instanceof ReturnStatement)) {
// return false;
// }
// // method should return 'void'
// MethodDeclaration coveringMetod = ASTResolving.findParentMethodDeclaration(covering);
// if (coveringMetod == null) {
// return false;
// }
// Type returnType = coveringMetod.getReturnType2();
// if (!isVoid(returnType)) {
// return false;
// }
// //
// List<Statement> statements = coveringMetod.getBody().statements();
// int ifIndex = statements.indexOf(ifStatement);
// if (ifIndex == -1) {
// return false;
// }
// //  we could produce quick assist
// if (resultingCollections == null) {
// return true;
// }
// //
// AST ast = covering.getAST();
// ASTRewrite rewrite = ASTRewrite.create(ast);
// // remove last 'return' in 'then' block
// ListRewrite listRewriter = rewrite.getListRewrite(thenBlock, (ChildListPropertyDescriptor) ifStatement.getLocationInParent());
// listRewriter.remove(thenStatements.get(thenStatements.size() - 1), null);
// // prepare original nodes
// Expression conditionPlaceholder = (Expression) rewrite.createMoveTarget(ifStatement.getExpression());
// Statement thenPlaceholder = (Statement) rewrite.createMoveTarget(ifStatement.getThenStatement());
// // prepare 'else' block
// Block elseBlock = ast.newBlock();
// for (int i = ifIndex + 1; i < statements.size(); i++) {
// Statement statement = statements.get(i);
// elseBlock.statements().add(rewrite.createMoveTarget(statement));
// }
// // prepare new 'if' statement
// IfStatement newIf = ast.newIfStatement();
// newIf.setExpression(conditionPlaceholder);
// newIf.setThenStatement(thenPlaceholder);
// newIf.setElseStatement(elseBlock);
// rewrite.replace(ifStatement, newIf, null);
// // add correction proposal
// String label = CorrectionMessages.AdvancedQuickAssistProcessor_convertToIfElse_description;
// Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
// ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CONVERT_TO_IF_ELSE, image);
// resultingCollections.add(proposal);
// return true;
// }
// 
// private static boolean getInverseIfProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
// if (!(covering instanceof IfStatement)) {
// return false;
// }
// IfStatement ifStatement = (IfStatement) covering;
// if (ifStatement.getElseStatement() == null) {
// return false;
// }
// //  we could produce quick assist
// if (resultingCollections == null) {
// return true;
// }
// //
// AST ast = covering.getAST();
// ASTRewrite rewrite = ASTRewrite.create(ast);
// Statement thenStatement = ifStatement.getThenStatement();
// Statement elseStatement = ifStatement.getElseStatement();
// 
// // prepare original nodes
// Expression inversedExpression = getInversedExpression(rewrite, ifStatement.getExpression());
// 
// Statement newElseStatement = (Statement) rewrite.createMoveTarget(thenStatement);
// Statement newThenStatement = (Statement) rewrite.createMoveTarget(elseStatement);
// // set new nodes
// rewrite.set(ifStatement, IfStatement.EXPRESSION_PROPERTY, inversedExpression, null);
// 
// if (elseStatement instanceof IfStatement) {// bug 79507 && bug 74580
// Block elseBlock = ast.newBlock();
// elseBlock.statements().add(newThenStatement);
// newThenStatement = elseBlock;
// }
// rewrite.set(ifStatement, IfStatement.THEN_STATEMENT_PROPERTY, newThenStatement, null);
// rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, newElseStatement, null);
// // add correction proposal
// String label = CorrectionMessages.AdvancedQuickAssistProcessor_inverseIf_description;
// Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
// ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERSE_IF_STATEMENT, image);
// resultingCollections.add(proposal);
// return true;
// }
// 
// private static boolean getInverseIfContinueIntoIfThenInLoopsProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
// if (!(covering instanceof IfStatement)) {
// return false;
// }
// IfStatement ifStatement = (IfStatement) covering;
// if (ifStatement.getElseStatement() != null) {
// return false;
// }
// // check that 'then' is 'continue'
// if (!(ifStatement.getThenStatement() instanceof ContinueStatement)) {
// return false;
// }
// // check that 'if' statement is statement in block that is body of loop
// Block loopBlock = null;
// if (ifStatement.getParent() instanceof Block && ifStatement.getParent().getParent() instanceof ForStatement) {
// loopBlock = (Block) ifStatement.getParent();
// } else if (ifStatement.getParent() instanceof Block && ifStatement.getParent().getParent() instanceof WhileStatement) {
// loopBlock = (Block) ifStatement.getParent();
// } else {
// return false;
// }
// 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);
// // prepare 'then' for new 'if'
// Block thenBlock = ast.newBlock();
// int ifIndex = loopBlock.statements().indexOf(ifStatement);
// for (int i = ifIndex + 1; i < loopBlock.statements().size(); i++) {
// Statement statement = (Statement) loopBlock.statements().get(i);
// thenBlock.statements().add(rewrite.createMoveTarget(statement));
// }
// newIf.setThenStatement(thenBlock);
// // replace 'if' statement in loop
// rewrite.replace(ifStatement, newIf, null);
// // add correction proposal
// String label = CorrectionMessages.AdvancedQuickAssistProcessor_inverseIfContinue_description;
// Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
// ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERSE_IF_CONTINUE, image);
// resultingCollections.add(proposal);
// return true;
// }
// 
// 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;
// }
// 
// private static ArrayList<Statement> getUnwrappedStatements(Statement body) {
// ArrayList<Statement> statements = new ArrayList<>();
// if (body instanceof Block) {
// for (Iterator<Statement> iter = ((Block) body).statements().iterator(); iter.hasNext();) {
// Statement statement = iter.next();
// statements.add(statement);
// }
// } else {
// statements.add(body);
// }
// return statements;
// }
// 
// private static boolean getInverseConditionProposals(IInvocationContext context, ASTNode covering, ArrayList<ASTNode> coveredNodes, Collection<ICommandAccess> resultingCollections) {
// if (coveredNodes.isEmpty()) {
// return false;
// }
// //
// final AST ast = covering.getAST();
// final ASTRewrite rewrite = ASTRewrite.create(ast);
// // check sub-expressions in fully covered nodes
// boolean hasChanges = false;
// for (Iterator<ASTNode> iter = coveredNodes.iterator(); iter.hasNext();) {
// ASTNode covered = iter.next();
// Expression coveredExpression = getBooleanExpression(covered);
// if (coveredExpression != null) {
// Expression inversedExpression = getInversedExpression(rewrite, coveredExpression);
// rewrite.replace(coveredExpression, inversedExpression, null);
// hasChanges = true;
// }
// }
// //
// if (!hasChanges) {
// return false;
// }
// if (resultingCollections == null) {
// return true;
// }
// // add correction proposal
// String label = CorrectionMessages.AdvancedQuickAssistProcessor_inverseConditions_description;
// Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
// ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INVERSE_CONDITIONS, image);
// resultingCollections.add(proposal);
// return true;
// }
// 
// private static Expression getInversedExpression(ASTRewrite rewrite, Expression expression) {
// return getInversedExpression(rewrite, expression, null);
// }
// 
// private interface SimpleNameRenameProvider {
// SimpleName getRenamed(SimpleName name);
// }
// 
// private static Expression getRenamedNameCopy(SimpleNameRenameProvider provider, ASTRewrite rewrite, Expression expression) {
// if (provider != null) {
// if (expression instanceof SimpleName) {
// SimpleName name = (SimpleName) expression;
// SimpleName newName = provider.getRenamed(name);
// if (newName != null) {
// return newName;
// }
// }
// }
// return (Expression) rewrite.createCopyTarget(expression);
// }
// 
// private static Expression getInversedExpression(ASTRewrite rewrite, Expression expression, SimpleNameRenameProvider provider) {
// AST ast = rewrite.getAST();
// //
// if (expression instanceof BooleanLiteral) {
// return ast.newBooleanLiteral(!((BooleanLiteral) expression).booleanValue());
// }
// if (expression instanceof InfixExpression) {
// InfixExpression infixExpression = (InfixExpression) expression;
// InfixExpression.Operator operator = infixExpression.getOperator();
// if (operator == InfixExpression.Operator.LESS) {
// return getInversedInfixExpression(rewrite, infixExpression, InfixExpression.Operator.GREATER_EQUALS, provider);
// }
// if (operator == InfixExpression.Operator.GREATER) {
// return getInversedInfixExpression(rewrite, infixExpression, InfixExpression.Operator.LESS_EQUALS, provider);
// }
// if (operator == InfixExpression.Operator.LESS_EQUALS) {
// return getInversedInfixExpression(rewrite, infixExpression, InfixExpression.Operator.GREATER, provider);
// }
// if (operator == InfixExpression.Operator.GREATER_EQUALS) {
// return getInversedInfixExpression(rewrite, infixExpression, InfixExpression.Operator.LESS, provider);
// }
// if (operator == InfixExpression.Operator.EQUALS) {
// return getInversedInfixExpression(rewrite, infixExpression, InfixExpression.Operator.NOT_EQUALS, provider);
// }
// if (operator == InfixExpression.Operator.NOT_EQUALS) {
// return getInversedInfixExpression(rewrite, infixExpression, InfixExpression.Operator.EQUALS, provider);
// }
// if (operator == InfixExpression.Operator.CONDITIONAL_AND) {
// return getInversedAndOrExpression(rewrite, infixExpression, InfixExpression.Operator.CONDITIONAL_OR, provider);
// }
// if (operator == InfixExpression.Operator.CONDITIONAL_OR) {
// return getInversedAndOrExpression(rewrite, infixExpression, InfixExpression.Operator.CONDITIONAL_AND, provider);
// }
// if (operator == InfixExpression.Operator.AND) {
// return getInversedAndOrExpression(rewrite, infixExpression, InfixExpression.Operator.OR, provider);
// }
// if (operator == InfixExpression.Operator.OR) {
// return getInversedAndOrExpression(rewrite, infixExpression, InfixExpression.Operator.AND, provider);
// }
// if (operator == InfixExpression.Operator.XOR) {
// return getInversedNotExpression(rewrite, expression, ast);
// }
// }
// if (expression instanceof PrefixExpression) {
// PrefixExpression prefixExpression = (PrefixExpression) expression;
// if (prefixExpression.getOperator() == PrefixExpression.Operator.NOT) {
// Expression operand = prefixExpression.getOperand();
// if ((operand instanceof ParenthesizedExpression) && NecessaryParenthesesChecker.canRemoveParentheses(operand, expression.getParent(), expression.getLocationInParent())) {
// operand = ((ParenthesizedExpression) operand).getExpression();
// }
// Expression renamedNameCopy = getRenamedNameCopy(provider, rewrite, operand);
// if (renamedNameCopy instanceof InfixExpression) {
// InfixExpression infixExpression = (InfixExpression) renamedNameCopy;
// infixExpression.setOperator(((InfixExpression) operand).getOperator());
// }
// return renamedNameCopy;
// }
// }
// if (expression instanceof InstanceofExpression) {
// return getInversedNotExpression(rewrite, expression, ast);
// }
// if (expression instanceof ParenthesizedExpression) {
// ParenthesizedExpression parenthesizedExpression = (ParenthesizedExpression) expression;
// Expression innerExpression = parenthesizedExpression.getExpression();
// while (innerExpression instanceof ParenthesizedExpression) {
// innerExpression = ((ParenthesizedExpression) innerExpression).getExpression();
// }
// if (innerExpression instanceof InstanceofExpression) {
// return getInversedExpression(rewrite, innerExpression, provider);
// }
// parenthesizedExpression = getParenthesizedExpression(ast, getInversedExpression(rewrite, innerExpression, provider));
// return parenthesizedExpression;
// }
// if (expression instanceof ConditionalExpression) {
// ConditionalExpression conditionalExpression = (ConditionalExpression) expression;
// ConditionalExpression newExpression = ast.newConditionalExpression();
// newExpression.setExpression((Expression) rewrite.createCopyTarget(conditionalExpression.getExpression()));
// newExpression.setThenExpression(getInversedExpression(rewrite, conditionalExpression.getThenExpression()));
// newExpression.setElseExpression(getInversedExpression(rewrite, conditionalExpression.getElseExpression()));
// return newExpression;
// }
// 
// PrefixExpression prefixExpression = ast.newPrefixExpression();
// prefixExpression.setOperator(PrefixExpression.Operator.NOT);
// Expression renamedNameCopy = getRenamedNameCopy(provider, rewrite, expression);
// if (NecessaryParenthesesChecker.needsParentheses(renamedNameCopy, prefixExpression, PrefixExpression.OPERAND_PROPERTY)) {
// renamedNameCopy = getParenthesizedExpression(ast, renamedNameCopy);
// }
// prefixExpression.setOperand(renamedNameCopy);
// return prefixExpression;
// }
// 
// private static Expression getInversedNotExpression(ASTRewrite rewrite, Expression expression, AST ast) {
// PrefixExpression prefixExpression = ast.newPrefixExpression();
// prefixExpression.setOperator(PrefixExpression.Operator.NOT);
// ParenthesizedExpression parenthesizedExpression = getParenthesizedExpression(ast, (Expression) rewrite.createCopyTarget(expression));
// prefixExpression.setOperand(parenthesizedExpression);
// return prefixExpression;
// }
// 
// private static boolean isBoolean(Expression expression) {
// ITypeBinding typeBinding = expression.resolveTypeBinding();
// AST ast = expression.getAST();
// return typeBinding == ast.resolveWellKnownType("boolean") //$NON-NLS-1$
// || typeBinding == ast.resolveWellKnownType("java.lang.Boolean"); //$NON-NLS-1$
// }
// 
// private static Expression getInversedInfixExpression(ASTRewrite rewrite, InfixExpression expression, InfixExpression.Operator newOperator, SimpleNameRenameProvider provider) {
// InfixExpression newExpression = rewrite.getAST().newInfixExpression();
// newExpression.setOperator(newOperator);
// newExpression.setLeftOperand(getRenamedNameCopy(provider, rewrite, expression.getLeftOperand()));
// newExpression.setRightOperand(getRenamedNameCopy(provider, rewrite, expression.getRightOperand()));
// return newExpression;
// }
// 
// private static Expression parenthesizeIfRequired(Expression operand, int newOperatorPrecedence) {
// if (newOperatorPrecedence > OperatorPrecedence.getExpressionPrecedence(operand)) {
// return getParenthesizedExpression(operand.getAST(), operand);
// }
// return operand;
// }
// 
// private static Expression getInversedAndOrExpression(ASTRewrite rewrite, InfixExpression infixExpression, Operator newOperator, SimpleNameRenameProvider provider) {
// InfixExpression newExpression = rewrite.getAST().newInfixExpression();
// newExpression.setOperator(newOperator);
// 
// int newOperatorPrecedence = OperatorPrecedence.getOperatorPrecedence(newOperator);
// //
// Expression leftOperand = getInversedExpression(rewrite, infixExpression.getLeftOperand(), provider);
// newExpression.setLeftOperand(parenthesizeIfRequired(leftOperand, newOperatorPrecedence));
// 
// Expression rightOperand = getInversedExpression(rewrite, infixExpression.getRightOperand(), provider);
// newExpression.setRightOperand(parenthesizeIfRequired(rightOperand, newOperatorPrecedence));
// 
// List<Expression> extraOperands = infixExpression.extendedOperands();
// List<Expression> newExtraOperands = newExpression.extendedOperands();
// for (int i = 0; i < extraOperands.size(); i++) {
// Expression extraOperand = getInversedExpression(rewrite, extraOperands.get(i), provider);
// newExtraOperands.add(parenthesizeIfRequired(extraOperand, newOperatorPrecedence));
// }
// return newExpression;
// }
// 
// private static boolean getRemoveExtraParenthesesProposals(IInvocationContext context, ASTNode covering, ArrayList<ASTNode> coveredNodes, Collection<ICommandAccess> resultingCollections) {
// ArrayList<ASTNode> nodes;
// if (context.getSelectionLength() == 0 && covering instanceof ParenthesizedExpression) {
// nodes = new ArrayList<>();
// nodes.add(covering);
// } else {
// nodes = coveredNodes;
// }
// if (nodes.isEmpty()) {
// return false;
// }
// 
// IProposableFix fix = ExpressionsFix.createRemoveUnnecessaryParenthesisFix(context.getASTRoot(), nodes.toArray(new ASTNode[nodes.size()]));
// if (fix == null) {
// return false;
// }
// 
// if (resultingCollections == null) {
// return true;
// }
// 
// Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE);
// Map<String, String> options = new Hashtable<>();
// options.put(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES, CleanUpOptions.TRUE);
// options.put(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_NEVER, CleanUpOptions.TRUE);
// FixCorrectionProposal proposal = new FixCorrectionProposal(fix, new ExpressionsCleanUp(options), IProposalRelevance.REMOVE_EXTRA_PARENTHESES, image, context);
// resultingCollections.add(proposal);
// return true;
// }
// 
// private static boolean getAddParanoidalParenthesesProposals(IInvocationContext context, ArrayList<ASTNode> coveredNodes, Collection<ICommandAccess> resultingCollections) {
// 
// IProposableFix fix = ExpressionsFix.createAddParanoidalParenthesisFix(context.getASTRoot(), coveredNodes.toArray(new ASTNode[coveredNodes.size()]));
// if (fix == null) {
// return false;
// }
// 
// if (resultingCollections == null) {
// return true;
// }
// 
// // add correction proposal
// Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CAST);
// Map<String, String> options = new Hashtable<>();
// options.put(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES, CleanUpOptions.TRUE);
// options.put(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_ALWAYS, CleanUpOptions.TRUE);
// FixCorrectionProposal proposal = new FixCorrectionProposal(fix, new ExpressionsCleanUp(options), IProposalRelevance.ADD_PARANOIDAL_PARENTHESES, image, context);
// resultingCollections.add(proposal);
// return true;
// }
// 
// private static boolean getAddParenthesesForExpressionProposals(IInvocationContext context, ASTNode coveringNode, Collection<ICommandAccess> resultingCollections) {
// ASTNode node;
// 
// if (context.getSelectionLength() == 0) {
// node = coveringNode;
// while (node != null && !(node instanceof CastExpression) && !(node instanceof InfixExpression) && !(node instanceof InstanceofExpression) && !(node instanceof ConditionalExpression)) {
// node = node.getParent();
// }
// } else {
// node = context.getCoveredNode();
// }
// 
// String label = null;
// if (node instanceof CastExpression) {
// label = CorrectionMessages.UnresolvedElementsSubProcessor_missingcastbrackets_description;
// } else if (node instanceof InstanceofExpression) {
// label = CorrectionMessages.LocalCorrectionsSubProcessor_setparenteses_instanceof_description;
// } else if (node instanceof InfixExpression) {
// InfixExpression infixExpression = (InfixExpression) node;
// label = Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_setparenteses_description, infixExpression.getOperator().toString());
// } else if (node instanceof ConditionalExpression) {
// label = CorrectionMessages.AdvancedQuickAssistProcessor_putConditionalExpressionInParentheses;
// } else {
// return false;
// }
// 
// if (node.getParent() instanceof ParenthesizedExpression) {
// return false;
// }
// 
// if (resultingCollections == null) {
// return true;
// }
// 
// AST ast = node.getAST();
// ASTRewrite rewrite = ASTRewrite.create(ast);
// 
// ParenthesizedExpression parenthesizedExpression = ast.newParenthesizedExpression();
// parenthesizedExpression.setExpression((Expression) rewrite.createCopyTarget(node));
// rewrite.replace(node, parenthesizedExpression, null);
// 
// Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CAST);
// ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_PARENTHESES_FOR_EXPRESSION, image);
// resultingCollections.add(proposal);
// return true;
// }
// 
// static ArrayList<ASTNode> getFullyCoveredNodes(IInvocationContext context, ASTNode coveringNode) {
// final ArrayList<ASTNode> coveredNodes = new ArrayList<>();
// final int selectionBegin = context.getSelectionOffset();
// final int selectionEnd = selectionBegin + context.getSelectionLength();
// coveringNode.accept(new GenericVisitor() {
// @Override
// protected boolean visitNode(ASTNode node) {
// int nodeStart = node.getStartPosition();
// int nodeEnd = nodeStart + node.getLength();
// // if node does not intersects with selection, don't visit children
// if (nodeEnd < selectionBegin || selectionEnd < nodeStart) {
// return false;
// }
// // if node is fully covered, we don't need to visit children
// if (isCovered(node)) {
// ASTNode parent = node.getParent();
// if (parent == null || !isCovered(parent)) {
// coveredNodes.add(node);
// return false;
// }
// }
// // if node only partly intersects with selection, we try to find fully covered children
// return true;
// }
// 
// private boolean isCovered(ASTNode node) {
// int begin = node.getStartPosition();
// int end = begin + node.getLength();
// return begin >= selectionBegin && end <= selectionEnd;
// }
// });
// return coveredNodes;
// }
// 
// private static boolean getJoinAndIfStatementsProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
// 
// //
// if (!(node instanceof IfStatement)) {
// return false;
// }
// IfStatement ifStatement = (IfStatement) node;
// if (ifStatement.getElseStatement() != null) {
// return false;
// }
// // case when current IfStatement is sole child of another IfStatement
// {
// IfStatement outerIf = null;
// if (ifStatement.getParent() instanceof IfStatement) {
// outerIf = (IfStatement) ifStatement.getParent();
// } else if (ifStatement.getParent() instanceof Block) {
// Block block = (Block) ifStatement.getParent();
// if (block.getParent() instanceof IfStatement && block.statements().size() == 1) {
// outerIf = (IfStatement) block.getParent();
// }
// }
// if (outerIf != null && outerIf.getElseStatement() == null) {
// if (resultingCollections == null) {
// return true;
// }
// //
// AST ast = node.getAST();
// ASTRewrite rewrite = ASTRewrite.create(ast);
// // create compound condition
// InfixExpression condition = ast.newInfixExpression();
// condition.setOperator(InfixExpression.Operator.CONDITIONAL_AND);
// // prepare condition parts, add parentheses if needed
// Expression outerCondition = getParenthesizedExpressionIfNeeded(ast, rewrite, outerIf.getExpression(), condition, InfixExpression.LEFT_OPERAND_PROPERTY);
// Expression innerCondition = getParenthesizedExpressionIfNeeded(ast, rewrite, ifStatement.getExpression(), condition, InfixExpression.RIGHT_OPERAND_PROPERTY);
// condition.setLeftOperand(outerCondition);
// condition.setRightOperand(innerCondition);
// // create new IfStatement
// IfStatement newIf = ast.newIfStatement();
// newIf.setExpression(condition);
// Statement bodyPlaceholder = (Statement) rewrite.createCopyTarget(ifStatement.getThenStatement());
// newIf.setThenStatement(bodyPlaceholder);
// rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
// rewrite.replace(outerIf, newIf, null);
// // add correction proposal
// String label = CorrectionMessages.AdvancedQuickAssistProcessor_joinWithOuter_description;
// Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
// ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.JOIN_IF_WITH_OUTER_IF, image);
// resultingCollections.add(proposal);
// }
// }
// // case when current IfStatement has another IfStatement as sole child
// {
// IfStatement innerIf = null;
// if (ifStatement.getThenStatement() instanceof IfStatement) {
// innerIf = (IfStatement) ifStatement.getThenStatement();
// } else if (ifStatement.getThenStatement() instanceof Block) {
// Block block = (Block) ifStatement.getThenStatement();
// if (block.statements().size() == 1 && block.statements().get(0) instanceof IfStatement) {
// innerIf = (IfStatement) block.statements().get(0);
// }
// }
// if (innerIf != null && innerIf.getElseStatement() == null) {
// if (resultingCollections == null) {
// return true;
// }
// //
// AST ast = node.getAST();
// ASTRewrite rewrite = ASTRewrite.create(ast);
// // create compound condition
// InfixExpression condition = ast.newInfixExpression();
// condition.setOperator(InfixExpression.Operator.CONDITIONAL_AND);
// // prepare condition parts, add parentheses if needed
// Expression outerCondition = getParenthesizedExpressionIfNeeded(ast, rewrite, ifStatement.getExpression(), condition, InfixExpression.LEFT_OPERAND_PROPERTY);
// Expression innerCondition = getParenthesizedExpressionIfNeeded(ast, rewrite, innerIf.getExpression(), condition, InfixExpression.RIGHT_OPERAND_PROPERTY);
// condition.setLeftOperand(outerCondition);
// condition.setRightOperand(innerCondition);
// // create new IfStatement
// IfStatement newIf = ast.newIfStatement();
// newIf.setExpression(condition);
// Statement bodyPlaceholder = (Statement) rewrite.createCopyTarget(innerIf.getThenStatement());
// newIf.setThenStatement(bodyPlaceholder);
// rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer());
// rewrite.replace(ifStatement, newIf, null);
// // add correction proposal
// String label = CorrectionMessages.AdvancedQuickAssistProcessor_joinWithInner_description;
// Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
// ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.JOIN_IF_WITH_INNER_IF, image);
// resultingCollections.add(proposal);
// }
// }
// return true;
// }
// 
// private static Expression getParenthesizedExpressionIfNeeded(AST ast, ASTRewrite rewrite, Expression expression, ASTNode parent, StructuralPropertyDescriptor locationInParent) {
// boolean addParentheses = NecessaryParenthesesChecker.needsParentheses(expression, parent, locationInParent);
// expression = (Expression) rewrite.createCopyTarget(expression);
// if (addParentheses) {
// return getParenthesizedExpression(ast, expression);
// }
// return expression;
// }
// 
// private static ParenthesizedExpression getParenthesizedExpression(AST ast, Expression expression) {
// ParenthesizedExpression parenthesizedExpression = ast.newParenthesizedExpression();
// parenthesizedExpression.setExpression(expression);
// return parenthesizedExpression;
// }
// 
public static boolean getSplitAndConditionProposals(IInvocationContext context, ASTNode node, Collection<CUCorrectionProposal> resultingCollections) {
    Operator andOperator = InfixExpression.Operator.CONDITIONAL_AND;
    // check that user invokes quick assist on infix expression
    if (!(node instanceof InfixExpression)) {
        return false;
    }
    InfixExpression infixExpression = (InfixExpression) node;
    if (infixExpression.getOperator() != andOperator) {
        return false;
    }
    int offset = isOperatorSelected(infixExpression, context.getSelectionOffset(), context.getSelectionLength());
    if (offset == -1) {
        return false;
    }
    // check that infix expression belongs to IfStatement
    Statement statement = ASTResolving.findParentStatement(node);
    if (!(statement instanceof IfStatement)) {
        return false;
    }
    IfStatement ifStatement = (IfStatement) statement;
    // check that infix expression is part of first level && condition of IfStatement
    InfixExpression topInfixExpression = infixExpression;
    while (topInfixExpression.getParent() instanceof InfixExpression && ((InfixExpression) topInfixExpression.getParent()).getOperator() == andOperator) {
        topInfixExpression = (InfixExpression) topInfixExpression.getParent();
    }
    if (ifStatement.getExpression() != topInfixExpression) {
        return false;
    }
    // 
    if (resultingCollections == null) {
        return true;
    }
    AST ast = ifStatement.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    // prepare left and right conditions
    Expression[] newOperands = { null, null };
    breakInfixOperationAtOperation(rewrite, topInfixExpression, andOperator, offset, true, newOperands);
    Expression leftCondition = newOperands[0];
    Expression rightCondition = newOperands[1];
    // replace conditions in outer IfStatement
    rewrite.set(ifStatement, IfStatement.EXPRESSION_PROPERTY, leftCondition, null);
    // prepare inner IfStatement
    IfStatement innerIf = ast.newIfStatement();
    innerIf.setExpression(rightCondition);
    innerIf.setThenStatement((Statement) rewrite.createMoveTarget(ifStatement.getThenStatement()));
    Block innerBlock = ast.newBlock();
    innerBlock.statements().add(innerIf);
    Statement elseStatement = ifStatement.getElseStatement();
    if (elseStatement != null) {
        innerIf.setElseStatement((Statement) rewrite.createCopyTarget(elseStatement));
    }
    // replace outer thenStatement
    rewrite.replace(ifStatement.getThenStatement(), innerBlock, null);
    // add correction proposal
    String label = CorrectionMessages.AdvancedQuickAssistProcessor_splitAndCondition_description;
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.SPLIT_AND_CONDITION);
    resultingCollections.add(proposal);
    return true;
}
Also used : Operator(org.eclipse.jdt.core.dom.InfixExpression.Operator) ASTRewriteCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.ASTRewriteCorrectionProposal) IfStatement(org.eclipse.jdt.core.dom.IfStatement) AST(org.eclipse.jdt.core.dom.AST) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) Expression(org.eclipse.jdt.core.dom.Expression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) Statement(org.eclipse.jdt.core.dom.Statement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) Block(org.eclipse.jdt.core.dom.Block)

Example 2 with ASTRewriteCorrectionProposal

use of org.eclipse.jdt.ls.core.internal.corrections.proposals.ASTRewriteCorrectionProposal in project eclipse.jdt.ls by eclipse.

the class QuickAssistProcessor method getCatchClauseToThrowsProposals.

public static boolean getCatchClauseToThrowsProposals(IInvocationContext context, ASTNode node, Collection<CUCorrectionProposal> resultingCollections) {
    if (resultingCollections == null) {
        return true;
    }
    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;
    }
    AST ast = bodyDeclaration.getAST();
    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);
            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);
            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);
            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);
            resultingCollections.add(proposal);
        }
    }
    return true;
}
Also used : UnionType(org.eclipse.jdt.core.dom.UnionType) AST(org.eclipse.jdt.core.dom.AST) Statement(org.eclipse.jdt.core.dom.Statement) ExpressionStatement(org.eclipse.jdt.core.dom.ExpressionStatement) TryStatement(org.eclipse.jdt.core.dom.TryStatement) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) CatchClause(org.eclipse.jdt.core.dom.CatchClause) SimpleName(org.eclipse.jdt.core.dom.SimpleName) Name(org.eclipse.jdt.core.dom.Name) ASTRewriteCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.ASTRewriteCorrectionProposal) SimpleType(org.eclipse.jdt.core.dom.SimpleType) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType) IType(org.eclipse.jdt.core.IType) UnionType(org.eclipse.jdt.core.dom.UnionType) ArrayType(org.eclipse.jdt.core.dom.ArrayType) ParameterizedType(org.eclipse.jdt.core.dom.ParameterizedType) SimpleType(org.eclipse.jdt.core.dom.SimpleType) Type(org.eclipse.jdt.core.dom.Type) Initializer(org.eclipse.jdt.core.dom.Initializer) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) NameQualifiedType(org.eclipse.jdt.core.dom.NameQualifiedType)

Example 3 with ASTRewriteCorrectionProposal

use of org.eclipse.jdt.ls.core.internal.corrections.proposals.ASTRewriteCorrectionProposal in project eclipse.jdt.ls by eclipse.

the class AdvancedQuickAssistProcessor method getSplitOrConditionProposals.

// 
// private static boolean getJoinOrIfStatementsProposals(IInvocationContext context, ASTNode covering, ArrayList<ASTNode> coveredNodes, Collection<ICommandAccess> resultingCollections) {
// Operator orOperator = InfixExpression.Operator.CONDITIONAL_OR;
// if (coveredNodes.size() < 2) {
// return false;
// }
// // check that all covered nodes are IfStatement's with same 'then' statement and without 'else'
// String commonThenSource = null;
// for (Iterator<ASTNode> iter = coveredNodes.iterator(); iter.hasNext();) {
// ASTNode node = iter.next();
// if (!(node instanceof IfStatement)) {
// return false;
// }
// //
// IfStatement ifStatement = (IfStatement) node;
// if (ifStatement.getElseStatement() != null) {
// return false;
// }
// //
// Statement thenStatement = ifStatement.getThenStatement();
// try {
// String thenSource = context.getCompilationUnit().getBuffer().getText(thenStatement.getStartPosition(), thenStatement.getLength());
// if (commonThenSource == null) {
// commonThenSource = thenSource;
// } else {
// if (!commonThenSource.equals(thenSource)) {
// return false;
// }
// }
// } catch (Throwable e) {
// return false;
// }
// }
// if (resultingCollections == null) {
// return true;
// }
// //
// final AST ast = covering.getAST();
// final ASTRewrite rewrite = ASTRewrite.create(ast);
// // prepare OR'ed condition
// InfixExpression condition = null;
// boolean hasRightOperand = false;
// Statement thenStatement = null;
// for (Iterator<ASTNode> iter = coveredNodes.iterator(); iter.hasNext();) {
// IfStatement ifStatement = (IfStatement) iter.next();
// if (thenStatement == null) {
// thenStatement = (Statement) rewrite.createCopyTarget(ifStatement.getThenStatement());
// }
// if (condition == null) {
// condition = ast.newInfixExpression();
// condition.setOperator(orOperator);
// condition.setLeftOperand(getParenthesizedExpressionIfNeeded(ast, rewrite, ifStatement.getExpression(), condition, InfixExpression.LEFT_OPERAND_PROPERTY));
// } else if (!hasRightOperand) {
// condition.setRightOperand(getParenthesizedExpressionIfNeeded(ast, rewrite, ifStatement.getExpression(), condition, InfixExpression.RIGHT_OPERAND_PROPERTY));
// hasRightOperand = true;
// } else {
// InfixExpression newCondition = ast.newInfixExpression();
// newCondition.setOperator(orOperator);
// newCondition.setLeftOperand(condition);
// newCondition.setRightOperand(getParenthesizedExpressionIfNeeded(ast, rewrite, ifStatement.getExpression(), condition, InfixExpression.RIGHT_OPERAND_PROPERTY));
// condition = newCondition;
// }
// }
// // prepare new IfStatement with OR'ed condition
// IfStatement newIf = ast.newIfStatement();
// newIf.setExpression(condition);
// newIf.setThenStatement(thenStatement);
// //
// ListRewrite listRewriter = null;
// for (Iterator<ASTNode> iter = coveredNodes.iterator(); iter.hasNext();) {
// IfStatement ifStatement = (IfStatement) iter.next();
// if (listRewriter == null) {
// Block sourceBlock = (Block) ifStatement.getParent();
// //int insertIndex = sourceBlock.statements().indexOf(ifStatement);
// listRewriter = rewrite.getListRewrite(sourceBlock, (ChildListPropertyDescriptor) ifStatement.getLocationInParent());
// }
// if (newIf != null) {
// listRewriter.replace(ifStatement, newIf, null);
// newIf = null;
// } else {
// listRewriter.remove(ifStatement, null);
// }
// }
// // add correction proposal
// String label = CorrectionMessages.AdvancedQuickAssistProcessor_joinWithOr_description;
// Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
// ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.JOIN_IF_STATEMENTS_WITH_OR, image);
// resultingCollections.add(proposal);
// return true;
// }
// 
public static boolean getSplitOrConditionProposals(IInvocationContext context, ASTNode node, Collection<CUCorrectionProposal> resultingCollections) {
    Operator orOperator = InfixExpression.Operator.CONDITIONAL_OR;
    // check that user invokes quick assist on infix expression
    if (!(node instanceof InfixExpression)) {
        return false;
    }
    InfixExpression infixExpression = (InfixExpression) node;
    if (infixExpression.getOperator() != orOperator) {
        return false;
    }
    int offset = isOperatorSelected(infixExpression, context.getSelectionOffset(), context.getSelectionLength());
    if (offset == -1) {
        return false;
    }
    // check that infix expression belongs to IfStatement
    Statement statement = ASTResolving.findParentStatement(node);
    if (!(statement instanceof IfStatement)) {
        return false;
    }
    IfStatement ifStatement = (IfStatement) statement;
    // check that infix expression is part of first level || condition of IfStatement
    InfixExpression topInfixExpression = infixExpression;
    while (topInfixExpression.getParent() instanceof InfixExpression && ((InfixExpression) topInfixExpression.getParent()).getOperator() == orOperator) {
        topInfixExpression = (InfixExpression) topInfixExpression.getParent();
    }
    if (ifStatement.getExpression() != topInfixExpression) {
        return false;
    }
    // 
    if (resultingCollections == null) {
        return true;
    }
    AST ast = ifStatement.getAST();
    ASTRewrite rewrite = ASTRewrite.create(ast);
    // prepare left and right conditions
    Expression[] newOperands = { null, null };
    breakInfixOperationAtOperation(rewrite, topInfixExpression, orOperator, offset, true, newOperands);
    Expression leftCondition = newOperands[0];
    Expression rightCondition = newOperands[1];
    // prepare first statement
    rewrite.replace(ifStatement.getExpression(), leftCondition, null);
    IfStatement secondIf = ast.newIfStatement();
    secondIf.setExpression(rightCondition);
    secondIf.setThenStatement((Statement) rewrite.createCopyTarget(ifStatement.getThenStatement()));
    Statement elseStatement = ifStatement.getElseStatement();
    if (elseStatement == null) {
        rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, secondIf, null);
    } else {
        rewrite.replace(elseStatement, secondIf, null);
        secondIf.setElseStatement((Statement) rewrite.createMoveTarget(elseStatement));
    }
    // add correction proposal
    String label = CorrectionMessages.AdvancedQuickAssistProcessor_splitOrCondition_description;
    ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.SPLIT_OR_CONDITION);
    resultingCollections.add(proposal);
    return true;
}
Also used : Operator(org.eclipse.jdt.core.dom.InfixExpression.Operator) ASTRewriteCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.ASTRewriteCorrectionProposal) IfStatement(org.eclipse.jdt.core.dom.IfStatement) AST(org.eclipse.jdt.core.dom.AST) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) Expression(org.eclipse.jdt.core.dom.Expression) ParenthesizedExpression(org.eclipse.jdt.core.dom.ParenthesizedExpression) Statement(org.eclipse.jdt.core.dom.Statement) IfStatement(org.eclipse.jdt.core.dom.IfStatement) InfixExpression(org.eclipse.jdt.core.dom.InfixExpression) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite)

Example 4 with ASTRewriteCorrectionProposal

use of org.eclipse.jdt.ls.core.internal.corrections.proposals.ASTRewriteCorrectionProposal in project eclipse.jdt.ls by eclipse.

the class ReturnTypeSubProcessor method addMissingReturnStatementProposals.

public static void addMissingReturnStatementProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) {
    ICompilationUnit cu = context.getCompilationUnit();
    ASTNode selectedNode = problem.getCoveringNode(context.getASTRoot());
    if (selectedNode == null) {
        return;
    }
    ReturnStatement existingStatement = (selectedNode instanceof ReturnStatement) ? (ReturnStatement) selectedNode : null;
    // Lambda Expression can be in a MethodDeclaration or a Field Declaration
    if (selectedNode instanceof LambdaExpression) {
        MissingReturnTypeInLambdaCorrectionProposal proposal = new MissingReturnTypeInLambdaCorrectionProposal(cu, (LambdaExpression) selectedNode, existingStatement, IProposalRelevance.MISSING_RETURN_TYPE);
        proposals.add(proposal);
    } else {
        BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
        if (decl instanceof MethodDeclaration) {
            MethodDeclaration methodDecl = (MethodDeclaration) decl;
            Block block = methodDecl.getBody();
            if (block == null) {
                return;
            }
            proposals.add(new MissingReturnTypeCorrectionProposal(cu, methodDecl, existingStatement, IProposalRelevance.MISSING_RETURN_TYPE));
            Type returnType = methodDecl.getReturnType2();
            if (returnType != null && !"void".equals(ASTNodes.asString(returnType))) {
                // $NON-NLS-1$
                AST ast = methodDecl.getAST();
                ASTRewrite rewrite = ASTRewrite.create(ast);
                rewrite.replace(returnType, ast.newPrimitiveType(PrimitiveType.VOID), null);
                Javadoc javadoc = methodDecl.getJavadoc();
                if (javadoc != null) {
                    TagElement tagElement = JavadocTagsSubProcessor.findTag(javadoc, TagElement.TAG_RETURN, null);
                    if (tagElement != null) {
                        rewrite.remove(tagElement, null);
                    }
                }
                String label = CorrectionMessages.ReturnTypeSubProcessor_changetovoid_description;
                ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_RETURN_TYPE_TO_VOID);
                proposals.add(proposal);
            }
        }
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) MissingReturnTypeInLambdaCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.MissingReturnTypeInLambdaCorrectionProposal) Javadoc(org.eclipse.jdt.core.dom.Javadoc) ASTRewriteCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.ASTRewriteCorrectionProposal) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) MissingReturnTypeCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.MissingReturnTypeCorrectionProposal) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) Block(org.eclipse.jdt.core.dom.Block) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TagElement(org.eclipse.jdt.core.dom.TagElement) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression)

Example 5 with ASTRewriteCorrectionProposal

use of org.eclipse.jdt.ls.core.internal.corrections.proposals.ASTRewriteCorrectionProposal in project eclipse.jdt.ls by eclipse.

the class ReturnTypeSubProcessor method addVoidMethodReturnsProposals.

public static void addVoidMethodReturnsProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) {
    ICompilationUnit cu = context.getCompilationUnit();
    CompilationUnit astRoot = context.getASTRoot();
    ASTNode selectedNode = problem.getCoveringNode(astRoot);
    if (selectedNode == null) {
        return;
    }
    BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(selectedNode);
    if (decl instanceof MethodDeclaration && selectedNode.getNodeType() == ASTNode.RETURN_STATEMENT) {
        ReturnStatement returnStatement = (ReturnStatement) selectedNode;
        Expression expr = returnStatement.getExpression();
        if (expr != null) {
            AST ast = astRoot.getAST();
            ITypeBinding binding = Bindings.normalizeTypeBinding(expr.resolveTypeBinding());
            if (binding == null) {
                // $NON-NLS-1$
                binding = ast.resolveWellKnownType("java.lang.Object");
            }
            if (binding.isWildcardType()) {
                binding = ASTResolving.normalizeWildcardType(binding, true, ast);
            }
            MethodDeclaration methodDeclaration = (MethodDeclaration) decl;
            ASTRewrite rewrite = ASTRewrite.create(ast);
            String label = Messages.format(CorrectionMessages.ReturnTypeSubProcessor_voidmethodreturns_description, BindingLabelProvider.getBindingLabel(binding, BindingLabelProvider.DEFAULT_TEXTFLAGS));
            LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.VOID_METHOD_RETURNS);
            ImportRewrite imports = proposal.createImportRewrite(astRoot);
            ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(methodDeclaration, imports);
            Type newReturnType = imports.addImport(binding, ast, importRewriteContext, TypeLocation.RETURN_TYPE);
            if (methodDeclaration.isConstructor()) {
                rewrite.set(methodDeclaration, MethodDeclaration.CONSTRUCTOR_PROPERTY, Boolean.FALSE, null);
                rewrite.set(methodDeclaration, MethodDeclaration.RETURN_TYPE2_PROPERTY, newReturnType, null);
            } else {
                rewrite.replace(methodDeclaration.getReturnType2(), newReturnType, null);
            }
            // $NON-NLS-1$
            String key = "return_type";
            proposal.addLinkedPosition(rewrite.track(newReturnType), true, key);
            ITypeBinding[] bindings = ASTResolving.getRelaxingTypes(ast, binding);
            for (int i = 0; i < bindings.length; i++) {
                proposal.addLinkedPositionProposal(key, bindings[i]);
            }
            Javadoc javadoc = methodDeclaration.getJavadoc();
            if (javadoc != null) {
                TagElement newTag = ast.newTagElement();
                newTag.setTagName(TagElement.TAG_RETURN);
                TextElement commentStart = ast.newTextElement();
                newTag.fragments().add(commentStart);
                JavadocTagsSubProcessor.insertTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), newTag, null);
                // $NON-NLS-1$
                proposal.addLinkedPosition(rewrite.track(commentStart), false, "comment_start");
            }
            proposals.add(proposal);
        }
        ASTRewrite rewrite = ASTRewrite.create(decl.getAST());
        rewrite.remove(returnStatement.getExpression(), null);
        String label = CorrectionMessages.ReturnTypeSubProcessor_removereturn_description;
        ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_TO_RETURN);
        proposals.add(proposal);
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) AST(org.eclipse.jdt.core.dom.AST) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Javadoc(org.eclipse.jdt.core.dom.Javadoc) ASTRewriteCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.ASTRewriteCorrectionProposal) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Type(org.eclipse.jdt.core.dom.Type) PrimitiveType(org.eclipse.jdt.core.dom.PrimitiveType) TextElement(org.eclipse.jdt.core.dom.TextElement) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.ls.core.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) Expression(org.eclipse.jdt.core.dom.Expression) LambdaExpression(org.eclipse.jdt.core.dom.LambdaExpression) LinkedCorrectionProposal(org.eclipse.jdt.ls.core.internal.corrections.proposals.LinkedCorrectionProposal) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ReturnStatement(org.eclipse.jdt.core.dom.ReturnStatement) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) TagElement(org.eclipse.jdt.core.dom.TagElement) BodyDeclaration(org.eclipse.jdt.core.dom.BodyDeclaration)

Aggregations

ASTRewrite (org.eclipse.jdt.core.dom.rewrite.ASTRewrite)6 ASTRewriteCorrectionProposal (org.eclipse.jdt.ls.core.internal.corrections.proposals.ASTRewriteCorrectionProposal)6 AST (org.eclipse.jdt.core.dom.AST)5 ASTNode (org.eclipse.jdt.core.dom.ASTNode)4 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)4 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)3 BodyDeclaration (org.eclipse.jdt.core.dom.BodyDeclaration)3 Expression (org.eclipse.jdt.core.dom.Expression)3 ReturnStatement (org.eclipse.jdt.core.dom.ReturnStatement)3 Statement (org.eclipse.jdt.core.dom.Statement)3 Type (org.eclipse.jdt.core.dom.Type)3 Block (org.eclipse.jdt.core.dom.Block)2 IfStatement (org.eclipse.jdt.core.dom.IfStatement)2 InfixExpression (org.eclipse.jdt.core.dom.InfixExpression)2 Operator (org.eclipse.jdt.core.dom.InfixExpression.Operator)2 Javadoc (org.eclipse.jdt.core.dom.Javadoc)2 LambdaExpression (org.eclipse.jdt.core.dom.LambdaExpression)2 ParenthesizedExpression (org.eclipse.jdt.core.dom.ParenthesizedExpression)2 PrimitiveType (org.eclipse.jdt.core.dom.PrimitiveType)2 TagElement (org.eclipse.jdt.core.dom.TagElement)2