@Override public Void visitWhileLoop(WhileLoopTree node, Void p) { super.visitWhileLoop(node, p); if (isMethodCode() && phase == PHASE_AFTER_SELECTION) { //#109663𛞨: //the selection was inside the while-loop, the variables inside the //condition&statement of the while loop need to be considered to be used again after the loop: if (!secondPass) { secondPass = true; scan(node.getCondition(), p); scan(node.getStatement(), p); secondPass = false; stopSecondPass = false; } } return null; }
@Override public Mirror visitWhileLoop(WhileLoopTree arg0, EvaluationContext evaluationContext) { ExpressionTree condition = arg0.getCondition(); Tree statement = arg0.getStatement(); Mirror result = null; while (evaluateCondition(arg0, evaluationContext, condition)) { try { evaluationContext.pushBlock(); Mirror res = statement.accept(this, evaluationContext); if (res instanceof Break) { break; } else if (res instanceof Continue) { continue; } if (res != null) { result = res; } } finally { evaluationContext.popBlock(); } } return result; }
private boolean testBlock(StringWriter writer, SourcePositions sp, String text, CompilationUnitTree cut, BlockTree blockTree) { boolean success = true; for (StatementTree st : blockTree.getStatements()) { if (isLegal(st)) { success &= testStatement(writer, sp, text, cut, st); } if (st instanceof IfTree) { IfTree ifTree = (IfTree) st; success &= testBranch(writer, sp, text, cut, ifTree.getThenStatement()); success &= testBranch(writer, sp, text, cut, ifTree.getElseStatement()); } else if (st instanceof WhileLoopTree) { WhileLoopTree whileLoopTree = (WhileLoopTree) st; success &= testBranch(writer, sp, text, cut, whileLoopTree.getStatement()); } else if (st instanceof DoWhileLoopTree) { DoWhileLoopTree doWhileLoopTree = (DoWhileLoopTree) st; success &= testBranch(writer, sp, text, cut, doWhileLoopTree.getStatement()); } else if (st instanceof ForLoopTree) { ForLoopTree forLoopTree = (ForLoopTree) st; success &= testBranch(writer, sp, text, cut, forLoopTree.getStatement()); } else if (st instanceof LabeledStatementTree) { LabeledStatementTree labelTree = (LabeledStatementTree) st; success &= testBranch(writer, sp, text, cut, labelTree.getStatement()); } else if (st instanceof SwitchTree) { SwitchTree switchTree = (SwitchTree) st; for (CaseTree caseTree : switchTree.getCases()) { for (StatementTree statementTree : caseTree.getStatements()) { success &= testBranch(writer, sp, text, cut, statementTree); } } } } return success; }
@Test public void testVisitWhileLoop() throws ParseException, BadLocationException, IOException { List<ReformatOption> optionsToReformat = new ArrayList<>(); CompilationUnitTree unit = getCompilationUnitTree(INPUT_FILE); MethodTree methodTree = TreeNavigationUtils.findMethodTreeByName("doSomething", unit).get(0); WhileLoopTree whileLoopTree = (WhileLoopTree) getStatementTreeByClassName(WhileLoopTree.class, methodTree); if (whileLoopTree == null) { fail(ERROR_MESSAGE); } ReformatTreeVisitor reformatTreeVisitor = getReformatTreeVisitor(INPUT_FILE); reformatTreeVisitor.visitWhileLoop(whileLoopTree, optionsToReformat); assertFalse(optionsToReformat.isEmpty()); }
@Test public void testVisitWhileLoopNotReformat() throws ParseException, BadLocationException, IOException { List<ReformatOption> optionsToReformat = new ArrayList<>(); CompilationUnitTree unit = getCompilationUnitTree(INPUT_FILE); MethodTree methodTree = TreeNavigationUtils.findMethodTreeByName("doSomething", unit).get(0); WhileLoopTree whileLoopTree = (WhileLoopTree) getStatementTreeByClassName(WhileLoopTree.class, methodTree); if (whileLoopTree == null) { fail(ERROR_MESSAGE); } ReformatTreeVisitor reformatTreeVisitor = getReformatTreeVisitor(INPUT_FILE, 0, 10); reformatTreeVisitor.visitWhileLoop(whileLoopTree, optionsToReformat); assertTrue(optionsToReformat.isEmpty()); }
@Override public Boolean visitWhileLoop(WhileLoopTree tree, Void unused) { Boolean condValue = ASTHelpers.constValue(tree.getCondition(), Boolean.class); if (!Objects.equals(condValue, false)) { scan(tree.getStatement()); } // (1) if (!Objects.equals(condValue, true)) { return true; } // (2) if (breaks.contains(tree)) { return true; } return false; }
@Override public Description matchWhileLoop(WhileLoopTree tree, VisitorState state) { JCWhileLoop whileLoop = (JCWhileLoop) tree; JCExpression whileExpression = ((JCParens) whileLoop.getCondition()).getExpression(); if (whileExpression instanceof MethodInvocationTree) { MethodInvocationTree methodInvocation = (MethodInvocationTree) whileExpression; if (methodSelect(isDescendantOfMethod("java.util.Iterator", "hasNext()")).matches( methodInvocation, state)) { IdentifierTree identifier = getIncrementedIdentifer(extractSingleStatement(whileLoop.body)); if (identifier != null) { return describeMatch(tree, new SuggestedFix()); } } } return Description.NO_MATCH; }
@Override public Tree visitWhileLoop(WhileLoopTree tree, Void p) { WhileLoopTree n = make.WhileLoop(tree.getCondition(), tree.getStatement()); model.setType(n, model.getType(tree)); comments.copyComments(tree, n); model.setPos(n, model.getPos(tree)); return n; }
public Boolean visitWhileLoop(WhileLoopTree node, TreePath p) { if (p == null) return super.visitWhileLoop(node, p); WhileLoopTree t = (WhileLoopTree) p.getLeaf(); if (!scan(node.getCondition(), t.getCondition(), p)) return false; return scan(node.getStatement(), t.getStatement(), p); }
@Override public Object visitWhileLoop(WhileLoopTree node, Object p) { boolean saveFlag = switchCase; switchCase = false; complexity++; Object o = super.visitWhileLoop(node, p); this.switchCase = saveFlag; return o; }
@Override public Object visitWhileLoop(WhileLoopTree node, Object p) { depth++; Object o = super.visitWhileLoop(node, p); depth--; return o; }
@Override public Void visitWhileLoop(WhileLoopTree tree, List<Node> d) { List<Node> below = new ArrayList<Node>(); addCorrespondingType(below); addCorrespondingComments(below); super.visitWhileLoop(tree, below); d.add(new TreeNode(info, getCurrentPath(), below)); return null; }
@Override public State visitWhileLoop(WhileLoopTree node, Void p) { State s; registerBreakTarget((node)); returnIfRecurse(s = scan(node.getCondition(), p)); return s; }
@Override public List<? extends TypeMirror> visitWhileLoop(WhileLoopTree node, Object p) { if (theExpression == null) { initExpression(node.getCondition()); } return booleanType(); }
@Override public List<Tree> visitWhileLoop(WhileLoopTree node, ExpressionScanner.ExpressionsInfo p) { List<Tree> cond = null; if (acceptsTree(node.getCondition())) { cond = scan(node.getCondition(), p); } List<Tree> statements = scan(node.getStatement(), p); if (cond != null && statements != null && statements.size() > 0) { p.addNextExpression(statements.get(statements.size() - 1), cond.get(0)); } return reduce(cond, statements); }
@Override public Void visitWhileLoop(WhileLoopTree node, Void unused) { sync(node); token("while"); builder.space(); token("("); scan(skipParen(node.getCondition()), null); token(")"); visitStatement( node.getStatement(), CollapseEmptyOrNot.YES, AllowLeadingBlankLine.YES, AllowTrailingBlankLine.NO); return null; }
void testPositionBrokenSource126732b() throws IOException { String[] commands = new String[]{ "break", "break A", "continue ", "continue A",}; for (String command : commands) { String code = "package test;\n" + "public class Test {\n" + " public static void test() {\n" + " while (true) {\n" + " " + command + " {\n" + " new Runnable() {\n" + " };\n" + " }\n" + " }\n" + "}"; JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null, null, Arrays.asList(new MyFileObject(code))); CompilationUnitTree cut = ct.parse().iterator().next(); ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0); MethodTree method = (MethodTree) clazz.getMembers().get(0); List<? extends StatementTree> statements = ((BlockTree) ((WhileLoopTree) method.getBody().getStatements().get(0)).getStatement()).getStatements(); StatementTree ret = statements.get(0); StatementTree block = statements.get(1); Trees t = Trees.instance(ct); int len = code.indexOf(command + " {") + (command + " ").length(); assertEquals(command, len, t.getSourcePositions().getEndPosition(cut, ret)); assertEquals(command, len, t.getSourcePositions().getStartPosition(cut, block)); } }
void testPositionBrokenSource126732b() throws IOException { String[] commands = new String[]{ "break", "break A", "continue ", "continue A",}; for (String command : commands) { String code = "package test;\n" + "public class Test {\n" + " public static void test() {\n" + " while (true) {\n" + " " + command + " {\n" + " new Runnable() {\n" + " };\n" + " }\n" + " }\n" + "}"; JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null, null, Arrays.asList(new MyFileObject(code))); CompilationUnitTree cut = ct.parse().iterator().next(); ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0); MethodTree method = (MethodTree) clazz.getMembers().get(0); List<? extends StatementTree> statements = ((BlockTree) ((WhileLoopTree) method.getBody().getStatements().get(0)).getStatement()).getStatements(); StatementTree ret = statements.get(0); StatementTree block = statements.get(1); Trees t = Trees.instance(ct); int len = code.indexOf(command + " {") + (command + " ").length(); assertEquals(command, len, t.getSourcePositions().getEndPosition(cut, ret)); assertEquals(command, len, t.getSourcePositions().getStartPosition(cut, block)); } }
@Override public Void visitWhileLoop(WhileLoopTree whileLoopTree, List<ReformatOption> optionsToReformat) { StatementTree statement = whileLoopTree.getStatement(); if (statement instanceof BlockTree) { addLeftBraceToList(optionsToReformat, ((BlockTree) statement), PreferencesFormatOptions.BRACES_IN_OTHER_DECLARATION); addRightBraceToList(optionsToReformat, ((CompoundTree) statement), PreferencesFormatOptions.AFTER_OTHER_DECLARATION); } return null; }
@Override public Void visitWhileLoop(WhileLoopTree tree, VisitorState visitorState) { VisitorState state = visitorState.withPath(getCurrentPath()); for (WhileLoopTreeMatcher matcher : whileLoopMatchers) { if (!isSuppressed(matcher, state)) { try { reportMatch(matcher.matchWhileLoop(tree, state), tree, state); } catch (Throwable t) { handleError(matcher, t); } } } return super.visitWhileLoop(tree, state); }
@Override public Result visitWhileLoop(WhileLoopTree node, BreakContext cxt) { cxt.loopDepth++; try { return node.getStatement().accept(this, cxt).or(NEVER_EXITS); } finally { cxt.loopDepth--; } }
@Override public Choice<State<JCWhileLoop>> visitWhileLoop(final WhileLoopTree node, State<?> state) { return chooseSubtrees( state, s -> unifyExpression(node.getCondition(), s), s -> unifyStatement(node.getStatement(), s), maker()::WhileLoop); }
@Override public boolean matches(TryTree tryTree, VisitorState state) { return ASTHelpers.findEnclosingNode(state.getPath(), DoWhileLoopTree.class) != null || ASTHelpers.findEnclosingNode(state.getPath(), EnhancedForLoopTree.class) != null || ASTHelpers.findEnclosingNode(state.getPath(), WhileLoopTree.class) != null || ASTHelpers.findEnclosingNode(state.getPath(), ForLoopTree.class) != null; }
public void testPositionBrokenSource126732b() throws IOException { String[] commands = new String[]{ "break", "break A", "continue ", "continue A",}; for (String command : commands) { String code = "package test;\n" + "public class Test {\n" + " public static void test() {\n" + " while (true) {\n" + " " + command + " {\n" + " new Runnable() {\n" + " };\n" + " }\n" + " }\n" + "}"; JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null, null, Arrays.asList(new MyFileObject(code))); CompilationUnitTree cut = ct.parse().iterator().next(); ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0); MethodTree method = (MethodTree) clazz.getMembers().get(0); List<? extends StatementTree> statements = ((BlockTree) ((WhileLoopTree) method.getBody().getStatements().get(0)).getStatement()).getStatements(); StatementTree ret = statements.get(0); StatementTree block = statements.get(1); Trees t = Trees.instance(ct); int len = code.indexOf(command + " {") + (command + " ").length(); assertEquals(command, len, t.getSourcePositions().getEndPosition(cut, ret)); assertEquals(command, len, t.getSourcePositions().getStartPosition(cut, block)); } }
@Override public Void visitWhileLoop(WhileLoopTree expected, Tree actual) { Optional<WhileLoopTree> other = checkTypeAndCast(expected, actual); if (!other.isPresent()) { addTypeMismatch(expected, actual); return null; } scan(expected.getCondition(), other.get().getCondition()); scan(expected.getStatement(), other.get().getStatement()); return null; }
public void testMoveStatements2() throws Exception { testFile = new File(getWorkDir(), "Test.java"); TestUtilities.copyStringToFile(testFile, "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " public void taragui() {\n" + " System.err.println(1);\n" + " {\n" + " while (true) {\n" + " System.err.println(2);\n" + "\n" + "\n" + " System.err.println(3);System.err.println(3.5);\n" + " System. err.\n" + " println(4);\n" + " }\n" + " }\n" + " if (true) {\n" + " System.err.println(5);\n" + " }\n" + " }\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " public void taragui() {\n" + " System.err.println(1);\n" + " if (true) {\n" + " System.err.println(2);\n" + " \n" + " \n" + " System.err.println(3);System.err.println(3.5);\n" + " System. err.\n" + " println(4);\n" + " }\n" + " }\n" + "}\n"; JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); TreeMaker make = workingCopy.getTreeMaker(); CompilationUnitTree cut = workingCopy.getCompilationUnit(); ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0); MethodTree method = (MethodTree) clazz.getMembers().get(1); BlockTree body = method.getBody(); BlockTree block = (BlockTree)body.getStatements().get(1); WhileLoopTree loop = (WhileLoopTree)block.getStatements().get(0); IfTree inner = make.If(make.Parenthesized(make.Literal(Boolean.TRUE)), loop.getStatement(), null); BlockTree nue = make.Block(Arrays.asList(body.getStatements().get(0), inner), false); workingCopy.rewrite(body, nue); } }; src.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); System.err.println(res); assertEquals(golden, res); }
public void test187616() throws Exception { testFile = new File(getWorkDir(), "Test.java"); TestUtilities.copyStringToFile(testFile, "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " public void taragui(String str) {\n" + " //blabla\n" + "\twhile(path.getLeaf().getKind() != Kind.CLASS) {\n" + " }\n" + " }\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " public void taragui(String str) {\n" + " //blabla\n" + "\twhile(!TreeUtilities.SET.contains(path.getLeaf().getKind())) {\n" + " }\n" + " }\n" + "}\n"; JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.PARSED); TreeMaker make = workingCopy.getTreeMaker(); CompilationUnitTree cut = workingCopy.getCompilationUnit(); ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0); MethodTree method = (MethodTree) clazz.getMembers().get(0); BlockTree body = method.getBody(); WhileLoopTree loop = (WhileLoopTree)body.getStatements().get(0); BinaryTree origCond = (BinaryTree) ((ParenthesizedTree) loop.getCondition()).getExpression(); ExpressionTree nueCondition = make.Unary(Tree.Kind.LOGICAL_COMPLEMENT, make.MethodInvocation(Collections.<ExpressionTree>emptyList(), make.MemberSelect(make.MemberSelect(make.Identifier("TreeUtilities"), "SET"), "contains"), Collections.singletonList(origCond.getLeftOperand()))); workingCopy.rewrite(origCond, nueCondition); } }; src.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); System.err.println(res); assertEquals(golden, res); }
@Override public Void visitWhileLoop(WhileLoopTree node, EnumSet<UseTypes> p) { scan(node.getCondition(), EnumSet.of(UseTypes.READ)); scan(node.getStatement(), p); return null; }
private List<int[]> detectBreakOrContinueTarget(CompilationInfo info, Document document, TreePath breakOrContinue, int caretPosition) { List<int[]> result = new ArrayList<int[]>(); StatementTree target = info.getTreeUtilities().getBreakContinueTarget(breakOrContinue); if (target == null) return null; TokenSequence<JavaTokenId> ts = info.getTokenHierarchy().tokenSequence(JavaTokenId.language()); ts.move((int) info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), target)); if (ts.moveNext()) { result.add(new int[] {ts.offset(), ts.offset() + ts.token().length()}); } StatementTree statement = target.getKind() == Kind.LABELED_STATEMENT ? ((LabeledStatementTree) target).getStatement() : target; Tree block = null; switch (statement.getKind()) { case SWITCH: block = statement; break; case WHILE_LOOP: if (((WhileLoopTree) statement).getStatement().getKind() == Kind.BLOCK) block = ((WhileLoopTree) statement).getStatement(); break; case FOR_LOOP: if (((ForLoopTree) statement).getStatement().getKind() == Kind.BLOCK) block = ((ForLoopTree) statement).getStatement(); break; case ENHANCED_FOR_LOOP: if (((EnhancedForLoopTree) statement).getStatement().getKind() == Kind.BLOCK) block = ((EnhancedForLoopTree) statement).getStatement(); break; case DO_WHILE_LOOP: if (((DoWhileLoopTree) statement).getStatement().getKind() == Kind.BLOCK) block = ((DoWhileLoopTree) statement).getStatement(); break; } if (block != null) { ts.move((int) info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), block)); if (ts.movePrevious() && ts.token().id() == JavaTokenId.RBRACE) { result.add(new int[] {ts.offset(), ts.offset() + ts.token().length()}); } } if (target.getKind() == Kind.LABELED_STATEMENT && isIn(caretPosition, Utilities.findIdentifierSpan(info, document, breakOrContinue))) { result.addAll(detectLabel(info, document, info.getTrees().getPath(info.getCompilationUnit(), target))); } return result; }
@Override public Boolean visitWhileLoop(WhileLoopTree node, Element p) { return null; }
@Override public Object visitWhileLoop(WhileLoopTree node, Object p) { loopCount++; return super.visitWhileLoop(node, p); }
@Override public Object visitWhileLoop(WhileLoopTree node, Object p) { statements++; return super.visitWhileLoop(node, p); }
@Hint(displayName="#LBL_Braces_While", description="#DSC_Braces_While", category="braces", id=BRACES_ID + "WHILE_LOOP", enabled=false, suppressWarnings={"", "ControlFlowStatementWithoutBraces"}) @TriggerTreeKind(Tree.Kind.WHILE_LOOP) public static ErrorDescription checkWhile(HintContext ctx) { WhileLoopTree wlt = (WhileLoopTree) ctx.getPath().getLeaf(); return checkStatement(ctx, "LBL_Braces_While", wlt.getStatement(), ctx.getPath()); }
@Override protected void performRewrite(TransformationContext ctx) { WorkingCopy copy = ctx.getWorkingCopy(); TreePath path = ctx.getPath(); if ( path != null ) { TreeMaker make = copy.getTreeMaker(); Tree oldTree = path.getLeaf(); oldTree = GeneratorUtilities.get(copy).importComments(oldTree, copy.getCompilationUnit()); switch( oldTree.getKind() ) { case FOR_LOOP: ForLoopTree oldFor = (ForLoopTree)oldTree; StatementTree oldBlock = oldFor.getStatement(); BlockTree newBlock = make.Block(Collections.<StatementTree>singletonList(oldBlock), false); copy.rewrite(oldBlock, newBlock); break; case ENHANCED_FOR_LOOP: EnhancedForLoopTree oldEnhancedFor = (EnhancedForLoopTree)oldTree; oldBlock = oldEnhancedFor.getStatement(); newBlock = make.Block(Collections.<StatementTree>singletonList(oldBlock), false); copy.rewrite(oldBlock, newBlock); break; case WHILE_LOOP: WhileLoopTree oldWhile = (WhileLoopTree)oldTree; oldBlock = oldWhile.getStatement(); newBlock = make.Block(Collections.<StatementTree>singletonList(oldBlock), false); copy.rewrite(oldBlock, newBlock); break; case DO_WHILE_LOOP: DoWhileLoopTree oldDoWhile = (DoWhileLoopTree)oldTree; oldBlock = oldDoWhile.getStatement(); newBlock = make.Block(Collections.<StatementTree>singletonList(oldBlock), false); copy.rewrite(oldBlock, newBlock); break; case IF: IfTree oldIf = (IfTree)oldTree; if ( fixThen ) { oldBlock = oldIf.getThenStatement(); newBlock = make.Block(Collections.<StatementTree>singletonList(oldBlock), false); copy.rewrite(oldBlock, newBlock); } if ( fixElse ) { oldBlock = oldIf.getElseStatement(); newBlock = make.Block(Collections.<StatementTree>singletonList(oldBlock), false); copy.rewrite(oldBlock, newBlock); } } } }