private static boolean locationNeedsParentheses(StructuralPropertyDescriptor locationInParent) { if (locationInParent instanceof ChildListPropertyDescriptor && locationInParent != InfixExpression.EXTENDED_OPERANDS_PROPERTY) { // e.g. argument lists of MethodInvocation, ClassInstanceCreation, dimensions of ArrayCreation ... return false; } if (locationInParent == VariableDeclarationFragment.INITIALIZER_PROPERTY || locationInParent == SingleVariableDeclaration.INITIALIZER_PROPERTY || locationInParent == ReturnStatement.EXPRESSION_PROPERTY || locationInParent == EnhancedForStatement.EXPRESSION_PROPERTY || locationInParent == ForStatement.EXPRESSION_PROPERTY || locationInParent == WhileStatement.EXPRESSION_PROPERTY || locationInParent == DoStatement.EXPRESSION_PROPERTY || locationInParent == AssertStatement.EXPRESSION_PROPERTY || locationInParent == AssertStatement.MESSAGE_PROPERTY || locationInParent == IfStatement.EXPRESSION_PROPERTY || locationInParent == SwitchStatement.EXPRESSION_PROPERTY || locationInParent == SwitchCase.EXPRESSION_PROPERTY || locationInParent == ArrayAccess.INDEX_PROPERTY || locationInParent == ThrowStatement.EXPRESSION_PROPERTY || locationInParent == SynchronizedStatement.EXPRESSION_PROPERTY || locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) { return false; } return true; }
private BlockInfo.Type getBlockType(ASTNode node) { if(node instanceof TypeDeclaration) return BlockInfo.Type.TYPE; else if(node instanceof MethodDeclaration) return BlockInfo.Type.METHOD; else if(node instanceof WhileStatement) return BlockInfo.Type.WHILE; else if(node instanceof ForStatement) return BlockInfo.Type.FOR; else if(node instanceof IfStatement) return BlockInfo.Type.IF; else return BlockInfo.Type.OTHER; }
/** * Method that check statement type. * @author Mariana Azevedo * @since 13/07/2014 * @param itStatement */ private void getStatementType(Object itStatement) { if (itStatement instanceof CatchClause){ this.visitor.visit((CatchClause)itStatement); }else if (itStatement instanceof ForStatement){ this.visitor.visit((ForStatement)itStatement); }else if (itStatement instanceof IfStatement){ this.visitor.visit((IfStatement)itStatement); }else if (itStatement instanceof WhileStatement){ this.visitor.visit((WhileStatement)itStatement); }else if (itStatement instanceof TryStatement){ this.visitor.visit((TryStatement)itStatement); }else if (itStatement instanceof ConditionalExpression){ this.visitor.visit((ConditionalExpression)itStatement); }else if (itStatement instanceof SwitchCase){ this.visitor.visit((SwitchCase)itStatement); }else if (itStatement instanceof DoStatement){ this.visitor.visit((DoStatement)itStatement); }else if (itStatement instanceof ExpressionStatement){ this.visitor.visit((ExpressionStatement)itStatement); } }
private List<IfStatement> collectIfStatements(MethodDeclaration md) { List<IfStatement> ifStatements = new ArrayList<IfStatement>(); Block body = md.getBody(); if (body == null) { return ifStatements; } for (Object statement : body.statements()) { if (statement instanceof Statement) { Statement st = (Statement) statement; ifStatements.addAll(collectIfStatements(st)); } } return ifStatements; }
private static boolean locationNeedsParentheses(StructuralPropertyDescriptor locationInParent) { if (locationInParent instanceof ChildListPropertyDescriptor && locationInParent != InfixExpression.EXTENDED_OPERANDS_PROPERTY) { // e.g. argument lists of MethodInvocation, ClassInstanceCreation, dimensions of ArrayCreation // ... return false; } if (locationInParent == VariableDeclarationFragment.INITIALIZER_PROPERTY || locationInParent == SingleVariableDeclaration.INITIALIZER_PROPERTY || locationInParent == ReturnStatement.EXPRESSION_PROPERTY || locationInParent == EnhancedForStatement.EXPRESSION_PROPERTY || locationInParent == ForStatement.EXPRESSION_PROPERTY || locationInParent == WhileStatement.EXPRESSION_PROPERTY || locationInParent == DoStatement.EXPRESSION_PROPERTY || locationInParent == AssertStatement.EXPRESSION_PROPERTY || locationInParent == AssertStatement.MESSAGE_PROPERTY || locationInParent == IfStatement.EXPRESSION_PROPERTY || locationInParent == SwitchStatement.EXPRESSION_PROPERTY || locationInParent == SwitchCase.EXPRESSION_PROPERTY || locationInParent == ArrayAccess.INDEX_PROPERTY || locationInParent == ThrowStatement.EXPRESSION_PROPERTY || locationInParent == SynchronizedStatement.EXPRESSION_PROPERTY || locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) { return false; } return true; }
/** {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { ASTRewrite rewrite = cuRewrite.getASTRewrite(); String label; if (fBodyProperty == IfStatement.THEN_STATEMENT_PROPERTY) { label = FixMessages.CodeStyleFix_ChangeIfToBlock_desription; } else if (fBodyProperty == IfStatement.ELSE_STATEMENT_PROPERTY) { label = FixMessages.CodeStyleFix_ChangeElseToBlock_description; } else { label = FixMessages.CodeStyleFix_ChangeControlToBlock_description; } TextEditGroup group = createTextEditGroup(label, cuRewrite); ASTNode moveTarget = rewrite.createMoveTarget(fBody); Block replacingBody = cuRewrite.getRoot().getAST().newBlock(); replacingBody.statements().add(moveTarget); rewrite.set(fControlStatement, fBodyProperty, replacingBody, group); }
private boolean isSingleControlStatementWithoutBlock() { List<Statement> statements = fDeclaration.getBody().statements(); int size = statements.size(); if (size != 1) return false; Statement statement = statements.get(size - 1); int nodeType = statement.getNodeType(); if (nodeType == ASTNode.IF_STATEMENT) { IfStatement ifStatement = (IfStatement) statement; return !(ifStatement.getThenStatement() instanceof Block) && !(ifStatement.getElseStatement() instanceof Block); } else if (nodeType == ASTNode.FOR_STATEMENT) { return !(((ForStatement) statement).getBody() instanceof Block); } else if (nodeType == ASTNode.WHILE_STATEMENT) { return !(((WhileStatement) statement).getBody() instanceof Block); } return false; }
private boolean needsBlockAroundDanglingIf() { /* see https://bugs.eclipse.org/bugs/show_bug.cgi?id=169331 * * Situation: * boolean a, b; * void toInline() { * if (a) * hashCode(); * } * void m() { * if (b) * toInline(); * else * toString(); * } * => needs block around inlined "if (a)..." to avoid attaching else to wrong if. */ return fTargetNode.getLocationInParent() == IfStatement.THEN_STATEMENT_PROPERTY && fTargetNode.getParent().getStructuralProperty(IfStatement.ELSE_STATEMENT_PROPERTY) != null && fSourceProvider.isDangligIf(); }
@Override public void insertIfStatement(IfStatement ifStmt, Block thenBlock) { // when stmt declares a local variable (see RearrangeStrategy.create(..)) we need to move // all // subsequent statements into the then-block to ensure that the existing declared local is // visible: List<ASTNode> blockStmts = this.block.statements(); int stmtIdx = blockStmts.indexOf(this.origStmt); int lastIdx = blockStmts.size() - 1; if (stmtIdx != -1 && stmtIdx < lastIdx) { thenBlock .statements() .add( this.blockRewrite.createMoveTarget( blockStmts.get(stmtIdx + 1), blockStmts.get(lastIdx), null, this.group)); } super.insertIfStatement(ifStmt, thenBlock); }
@Override public boolean preNext(IfStatement curElement) { Statement thenStatement = curElement.getThenStatement(); Statement elseStatement = curElement.getElseStatement(); Expression condition = curElement.getExpression(); if (elseStatement == null) { compiler.println("opt " + condition.toString()); return true; } else { compiler.println("alt " + condition.toString()); thenStatement.accept(compiler); if (elseStatement instanceof IfStatement) { processAltStatement((IfStatement) elseStatement); } else { compiler.println("else"); elseStatement.accept(compiler); } return false; } }
private void processAltStatement(IfStatement statement) { Statement thenStatement = statement.getThenStatement(); Statement elseStatement = statement.getElseStatement(); Expression condition = statement.getExpression(); compiler.println("else " + condition.toString()); thenStatement.accept(compiler); if (elseStatement != null) { if (elseStatement instanceof IfStatement) { processAltStatement((IfStatement) elseStatement); } else { compiler.println("else"); elseStatement.accept(compiler); } } }
private boolean isSingleControlStatementWithoutBlock() { List<Statement> statements= fDeclaration.getBody().statements(); int size= statements.size(); if (size != 1) return false; Statement statement= statements.get(size - 1); int nodeType= statement.getNodeType(); if (nodeType == ASTNode.IF_STATEMENT) { IfStatement ifStatement= (IfStatement) statement; return !(ifStatement.getThenStatement() instanceof Block) && !(ifStatement.getElseStatement() instanceof Block); } else if (nodeType == ASTNode.FOR_STATEMENT) { return !(((ForStatement)statement).getBody() instanceof Block); } else if (nodeType == ASTNode.WHILE_STATEMENT) { return !(((WhileStatement)statement).getBody() instanceof Block); } return false; }
@Override protected void addMemberCheckNull(Object member, boolean addSeparator) { IfStatement ifStatement= fAst.newIfStatement(); ifStatement.setExpression(createInfixExpression(createMemberAccessExpression(member, true, true), Operator.NOT_EQUALS, fAst.newNullLiteral())); Block thenBlock= fAst.newBlock(); flushBuffer(null); String[] arrayString= getContext().getTemplateParser().getBody(); for (int i= 0; i < arrayString.length; i++) { addElement(processElement(arrayString[i], member), thenBlock); } if (addSeparator) addElement(getContext().getTemplateParser().getSeparator(), thenBlock); flushBuffer(thenBlock); if (thenBlock.statements().size() == 1 && !getContext().isForceBlocks()) { ifStatement.setThenStatement((Statement)ASTNode.copySubtree(fAst, (ASTNode)thenBlock.statements().get(0))); } else { ifStatement.setThenStatement(thenBlock); } toStringMethod.getBody().statements().add(ifStatement); }
@Override protected void addMemberCheckNull(Object member, boolean addSeparator) { IfStatement ifStatement= fAst.newIfStatement(); ifStatement.setExpression(createInfixExpression(createMemberAccessExpression(member, true, true), Operator.NOT_EQUALS, fAst.newNullLiteral())); Block thenBlock= fAst.newBlock(); flushTemporaryExpression(); String[] arrayString= getContext().getTemplateParser().getBody(); for (int i= 0; i < arrayString.length; i++) { addElement(processElement(arrayString[i], member), thenBlock); } if (addSeparator) addElement(getContext().getTemplateParser().getSeparator(), thenBlock); flushTemporaryExpression(); if (thenBlock.statements().size() == 1 && !getContext().isForceBlocks()) { ifStatement.setThenStatement((Statement)ASTNode.copySubtree(fAst, (ASTNode)thenBlock.statements().get(0))); } else { ifStatement.setThenStatement(thenBlock); } toStringMethod.getBody().statements().add(ifStatement); }
private Statement createOuterComparison() { MethodInvocation outer1= fAst.newMethodInvocation(); outer1.setName(fAst.newSimpleName(METHODNAME_OUTER_TYPE)); MethodInvocation outer2= fAst.newMethodInvocation(); outer2.setName(fAst.newSimpleName(METHODNAME_OUTER_TYPE)); outer2.setExpression(fAst.newSimpleName(VARIABLE_NAME_EQUALS_CASTED)); MethodInvocation outerEql= fAst.newMethodInvocation(); outerEql.setName(fAst.newSimpleName(METHODNAME_EQUALS)); outerEql.setExpression(outer1); outerEql.arguments().add(outer2); PrefixExpression not= fAst.newPrefixExpression(); not.setOperand(outerEql); not.setOperator(PrefixExpression.Operator.NOT); IfStatement notEqNull= fAst.newIfStatement(); notEqNull.setExpression(not); notEqNull.setThenStatement(getThenStatement(getReturnFalse())); return notEqNull; }
private Statement createArrayComparison(String name) { MethodInvocation invoc= fAst.newMethodInvocation(); invoc.setName(fAst.newSimpleName(METHODNAME_EQUALS)); invoc.setExpression(getQualifiedName(JAVA_UTIL_ARRAYS)); invoc.arguments().add(getThisAccessForEquals(name)); invoc.arguments().add(getOtherAccess(name)); PrefixExpression pe= fAst.newPrefixExpression(); pe.setOperator(PrefixExpression.Operator.NOT); pe.setOperand(invoc); IfStatement ifSt= fAst.newIfStatement(); ifSt.setExpression(pe); ifSt.setThenStatement(getThenStatement(getReturnFalse())); return ifSt; }
private Statement createMultiArrayComparison(String name) { MethodInvocation invoc= fAst.newMethodInvocation(); invoc.setName(fAst.newSimpleName(METHODNAME_DEEP_EQUALS)); invoc.setExpression(getQualifiedName(JAVA_UTIL_ARRAYS)); invoc.arguments().add(getThisAccessForEquals(name)); invoc.arguments().add(getOtherAccess(name)); PrefixExpression pe= fAst.newPrefixExpression(); pe.setOperator(PrefixExpression.Operator.NOT); pe.setOperand(invoc); IfStatement ifSt= fAst.newIfStatement(); ifSt.setExpression(pe); ifSt.setThenStatement(getThenStatement(getReturnFalse())); return ifSt; }
/** * {@inheritDoc} */ @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { ASTRewrite rewrite= cuRewrite.getASTRewrite(); String label; if (fBodyProperty == IfStatement.THEN_STATEMENT_PROPERTY) { label = FixMessages.CodeStyleFix_ChangeIfToBlock_desription; } else if (fBodyProperty == IfStatement.ELSE_STATEMENT_PROPERTY) { label = FixMessages.CodeStyleFix_ChangeElseToBlock_description; } else { label = FixMessages.CodeStyleFix_ChangeControlToBlock_description; } TextEditGroup group= createTextEditGroup(label, cuRewrite); ASTNode moveTarget= rewrite.createMoveTarget(fBody); Block replacingBody= cuRewrite.getRoot().getAST().newBlock(); replacingBody.statements().add(moveTarget); rewrite.set(fControlStatement, fBodyProperty, replacingBody, group); }
private static boolean getAddElseProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) { if (!(node instanceof IfStatement)) { return false; } IfStatement ifStatement= (IfStatement) node; if (ifStatement.getElseStatement() != null) { return false; } if (resultingCollections == null) { return true; } AST ast= node.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); Block body= ast.newBlock(); rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, body, null); String label= CorrectionMessages.QuickAssistProcessor_addelseblock_description; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_ELSE_BLOCK, image); resultingCollections.add(proposal); return true; }
private static boolean getAddElseProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) { if (!(node instanceof IfStatement)) { return false; } IfStatement ifStatement= (IfStatement) node; if (ifStatement.getElseStatement() != null) { return false; } if (resultingCollections == null) { return true; } AST ast= node.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); Block body= ast.newBlock(); rewrite.set(ifStatement, IfStatement.ELSE_STATEMENT_PROPERTY, body, null); String label= CorrectionMessages.QuickAssistProcessor_addelseblock_description; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 1, image); resultingCollections.add(proposal); return true; }
/** * 'if(' expression ') {' thenStatement '}' ['else {' elseStatement '}'] */ @Override public boolean visit(final IfStatement node) { final int lineNo = lineStart(node); // dependence id final LineKind kind = node.getElseStatement() == null ? LK_IF_THEN : LK_IF_THEN_ELSE; // new dependence final IResolvedLine rd = createDependence(kind, lineNo, mdg.parent()); // append control dependences appendDependences(rd, node.getExpression(), null, false); // recursively append "then" dependences appendRecursive(lineNo, rd, node.getThenStatement()); // recursively append "else" dependences if (node.getElseStatement() != null) { appendRecursive(lineNo, rd, node.getElseStatement()); } // do not visit children return false; }
@SuppressWarnings("unchecked") private Statement makeIfStatement(ASTRewrite rewrite, ReturnValueResolutionVisitor rvrFinder, boolean b) { AST rootNode = rewrite.getAST(); IfStatement ifStatement = rootNode.newIfStatement(); Expression expression = makeIfExpression(rewrite, rvrFinder, b); ifStatement.setExpression(expression); // the block surrounds the inner statement with {} Block thenBlock = rootNode.newBlock(); Statement thenStatement = makeExceptionalStatement(rootNode); thenBlock.statements().add(thenStatement); ifStatement.setThenStatement(thenBlock); return ifStatement; }
@SuppressWarnings("unchecked") @Override public boolean visit(QJump statement) { Block block = blocks.peek(); // dummy break if (isParentFor(statement)) { IfStatement ifSt = ast.newIfStatement(); ifSt.setExpression(ast.newBooleanLiteral(false)); ifSt.setThenStatement(ast.newBreakStatement()); block.statements().add(ifSt); } MethodInvocation methodInvocation = ast.newMethodInvocation(); methodInvocation.setExpression(ast.newSimpleName("qRPJ")); methodInvocation.setName(ast.newSimpleName("qJump")); Name labelName = ast.newName(new String[] { "TAG", statement.getLabel() }); methodInvocation.arguments().add(0, labelName); ExpressionStatement expressionStatement = ast.newExpressionStatement(methodInvocation); block.statements().add(expressionStatement); return super.visit(statement); }
@SuppressWarnings("unchecked") @Override public boolean visit(QReturn statement) { Block block = blocks.peek(); ReturnStatement returnSt = ast.newReturnStatement(); if (isParentProcedure(statement)) { block.statements().add(returnSt); } else { // dummy condition IfStatement ifSt = ast.newIfStatement(); ifSt.setExpression(ast.newBooleanLiteral(true)); ifSt.setThenStatement(returnSt); block.statements().add(ifSt); } return false; }
@Override public boolean visit(IfStatement node) { //System.out.println("Found: " + node.getClass()); print("if ("); node.getExpression().accept(this); println(") {"); indent++; node.getThenStatement().accept(this); indent--; if (node.getElseStatement() == null) { println("}"); } else { if (node.getElseStatement() instanceof IfStatement) { print("} else "); node.getElseStatement().accept(this); } else { println("} else {"); indent++; node.getElseStatement().accept(this); indent--; println("}"); } } return false; }
public IfStatementWrapper(IfStatement statement, int indentationLevel, Applicable applicable) { super(indentationLevel, applicable); this.expression = statement.getExpression(); this.thenBlock = new LinkedList<>(); this.elseBlock = new LinkedList<>(); statementsFrom(statement.getThenStatement(), thenBlock); statementsFrom(statement.getElseStatement(), elseBlock); applicable.applyFeaturesToStatements(thenBlock); applicable.applyFeaturesToStatements(elseBlock); }
public static Object wrap(Object statement, int indentation, Applicable applicable) { if (statement instanceof IfStatement) { return new IfStatementWrapper((IfStatement) statement, indentation, applicable); } else if (statement instanceof TryStatement) { return new TryStatementWrapper((TryStatement) statement, indentation, applicable); } return statement; }
public boolean visit(IfStatement node) { Statement thenStmt = node.getThenStatement(); Statement elseStmt = node.getElseStatement(); Expression condExpr = node.getExpression(); String thenStr = (thenStmt.toString()).replace('\n', ' '); String elseStr = ""; if (elseStmt != null) { elseStr = (elseStmt.toString()).replace('\n', ' '); } if (mtbStack.isEmpty()) // not part of a method return true; IMethodBinding mtb = mtbStack.peek(); String methodStr = getQualifiedName(mtb); String condStr = condExpr.toString(); condStr = edit_str(condStr); thenStr = edit_str(thenStr); elseStr = edit_str(elseStr); // make conditional fact try { facts.add(Fact.makeConditionalFact(condStr, thenStr, elseStr, methodStr)); } catch (Exception e) { System.err.println("Cannot resolve conditional \"" + condExpr.toString() + "\""); System.out.println("ifStmt: " + thenStr); System.out.println("elseStmt: " + elseStr); System.err.println(e.getMessage()); } return true; }
private boolean isLoopStatement(Block block) { ASTNode parent = block.getParent(); return parent instanceof WhileStatement || parent instanceof ForStatement || parent instanceof DoStatement || parent instanceof EnhancedForStatement || parent instanceof IfStatement; }