private boolean isLastInControlFlow(TreePath pathToInstruction) { Tree currentTree = pathToInstruction.getLeaf(); Tree parentTree = pathToInstruction.getParentPath().getLeaf(); if (parentTree.equals(this.loop)) { return true; } else if (parentTree.getKind() == Tree.Kind.BLOCK) { List<? extends StatementTree> ls = ((BlockTree) parentTree).getStatements(); if (ls.get(ls.size() - 1).equals(currentTree)) { return isLastInControlFlow(pathToInstruction.getParentPath()); } else { return false; } } else if (parentTree.getKind() == Tree.Kind.AND.IF && ((IfTree) parentTree).getElseStatement() != null) { return false; } else { return this.isLastInControlFlow(pathToInstruction.getParentPath()); } }
List<ExpressionTree> getArguments() { VariableTree var; ExpressionTree lambda; Tree lambdaBody; if (this.correspondingTree.getKind() == Tree.Kind.BLOCK) { lambdaBody = this.correspondingTree; } else { if (this.opType == OperationType.FILTER || this.opType == OperationType.ANYMATCH || this.opType == OperationType.NONEMATCH) { lambdaBody = ((IfTree) this.correspondingTree).getCondition(); } else if (this.opType == OperationType.MAP) { lambdaBody = getLambdaForMap(); } else if (this.opType == OperationType.FOREACH) { lambdaBody = blockify(castToStatementTree(this.correspondingTree)); } else //if(this.opType== OperationType.REDUCE) { return getArgumentsForReducer(); } } var = getLambdaArguments(); lambda = treeMaker.LambdaExpression(Arrays.asList(var), lambdaBody); List<ExpressionTree> args = new ArrayList<ExpressionTree>(); args.add(lambda); return args; }
public Boolean visitBlock(BlockTree node, ConstructorData p) { List<? extends StatementTree> statements = new ArrayList<StatementTree>(node.getStatements()); for (int i = 0; i < statements.size(); i++) { StatementTree st = statements.get(i); if (st.getKind() == Kind.IF) { IfTree it = (IfTree) st; if (it.getElseStatement() == null && Utilities.exitsFromAllBranchers(info, new TreePath(new TreePath(getCurrentPath(), it), it.getThenStatement()))) { generalizedIf(it.getCondition(), it.getThenStatement(), statements.subList(i + 1, statements.size()), false); break; } } scan(st, null); } return null; }
@Hint(displayName = "#LBL_Empty_IF", description = "#DSC_Empty_IF", category = "empty", hintKind = Hint.Kind.INSPECTION, severity = Severity.VERIFIER, suppressWarnings = SUPPRESS_WARNINGS_KEY, id = "EmptyStatements_IF", enabled = false) @TriggerTreeKind(Tree.Kind.EMPTY_STATEMENT) public static ErrorDescription forIF(HintContext ctx) { final TreePath treePath = ctx.getPath(); Tree parent = treePath.getParentPath().getLeaf(); if (!EnumSet.of(Kind.IF).contains(parent.getKind())) { return null; } TreePath treePathForWarning = treePath; IfTree it = (IfTree) parent; if (it.getThenStatement() != null && it.getThenStatement().getKind() == Tree.Kind.EMPTY_STATEMENT) { treePathForWarning = treePath.getParentPath(); } if (it.getElseStatement() != null && it.getElseStatement().getKind() == Tree.Kind.EMPTY_STATEMENT) { treePathForWarning = treePath; } final List<Fix> fixes = new ArrayList<>(); fixes.add(FixFactory.createSuppressWarningsFix(ctx.getInfo(), treePathForWarning, SUPPRESS_WARNINGS_KEY)); return createErrorDescription(ctx, parent, fixes, parent.getKind()); }
@Hint(id="org.netbeans.modules.java.hints.suggestions.InvertIf", displayName = "#DN_InvertIf", description = "#DESC_InvertIf", category = "suggestions", hintKind= Hint.Kind.ACTION) @UseOptions(SHOW_ELSE_MISSING) @TriggerPattern(value = "if ($cond) $then; else $else$;") @Messages({"ERR_InvertIf=Invert If", "FIX_InvertIf=Invert If"}) public static ErrorDescription computeWarning(HintContext ctx) { TreePath cond = ctx.getVariables().get("$cond"); long conditionEnd = ctx.getInfo().getTrees().getSourcePositions().getEndPosition(cond.getCompilationUnit(), cond.getParentPath().getLeaf()); if (ctx.getCaretLocation() > conditionEnd) return null; // parenthesized, then if TreePath ifPath = cond.getParentPath().getParentPath(); if (ifPath.getLeaf().getKind() != Tree.Kind.IF) { return null; } IfTree iv = (IfTree)ifPath.getLeaf(); if (iv.getElseStatement() == null && !ctx.getPreferences().getBoolean(SHOW_ELSE_MISSING, SHOW_ELSE_MISSING_DEFAULT)) { return null; } return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_InvertIf(), new FixImpl(ctx.getInfo(), ctx.getPath()).toEditorFix()); }
@Override protected void performRewrite(final TransformationContext ctx) throws Exception { IfTree toRewrite = (IfTree) ctx.getPath().getLeaf(); StatementTree elseStatement = toRewrite.getElseStatement(); if (toRewrite.getCondition() == null || toRewrite.getCondition().getKind() != Tree.Kind.PARENTHESIZED) { return; } ParenthesizedTree ptt = (ParenthesizedTree)toRewrite.getCondition(); if (ptt.getExpression() == null) { return; } if (elseStatement == null) elseStatement = ctx.getWorkingCopy().getTreeMaker().Block(Collections.<StatementTree>emptyList(), false); ctx.getWorkingCopy().rewrite(toRewrite, ctx.getWorkingCopy().getTreeMaker().If(toRewrite.getCondition(), elseStatement, toRewrite.getThenStatement())); ExpressionTree negated = Utilities.negate( ctx.getWorkingCopy().getTreeMaker(), ptt.getExpression(), ptt); ctx.getWorkingCopy().rewrite(ptt.getExpression(), negated); }
@Override public Mirror visitIf(IfTree arg0, EvaluationContext evaluationContext) { boolean evaluatedCondition = evaluateCondition(arg0, evaluationContext, arg0.getCondition()); StatementTree statement; if (evaluatedCondition) { statement = arg0.getThenStatement(); } else { statement = arg0.getElseStatement(); } if (statement != null) { try { evaluationContext.pushBlock(); return statement.accept(this, evaluationContext); } finally { evaluationContext.popBlock(); } } else { return null; } }
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; }
@Override public Void visitIf(IfTree ifTree, List<ReformatOption> optionsToReformat) { StatementTree thenStatement = ifTree.getThenStatement(); if (thenStatement instanceof BlockTree) { addLeftBraceToList(optionsToReformat, ((BlockTree) thenStatement), PreferencesFormatOptions.BRACES_IN_OTHER_DECLARATION); } StatementTree elseStatement = ifTree.getElseStatement(); if (elseStatement instanceof EmptyStatementTree && thenStatement instanceof CompoundTree) { addRightBraceToList(optionsToReformat, ((CompoundTree) thenStatement), PreferencesFormatOptions.AFTER_OTHER_DECLARATION); } else if (elseStatement instanceof BlockTree) { addLeftBraceToList(optionsToReformat, ((BlockTree) elseStatement), PreferencesFormatOptions.BRACES_IN_OTHER_DECLARATION); } return null; }
@Test public void testVisitIf() throws ParseException, BadLocationException, IOException { List<ReformatOption> optionsToReformat = new ArrayList<>(); CompilationUnitTree unit = getCompilationUnitTree(INPUT_FILE); MethodTree methodTree = TreeNavigationUtils.findMethodTreeByName("doSomething", unit).get(0); IfTree IfTree = (IfTree) getStatementTreeByClassName(IfTree.class, methodTree); if (IfTree == null) { fail(ERROR_MESSAGE); } ReformatTreeVisitor reformatTreeVisitor = getReformatTreeVisitor(INPUT_FILE); reformatTreeVisitor.visitIf(IfTree, optionsToReformat); assertFalse(optionsToReformat.isEmpty()); }
@Test public void testVisitIfNotReformat() throws ParseException, BadLocationException, IOException { List<ReformatOption> optionsToReformat = new ArrayList<>(); CompilationUnitTree unit = getCompilationUnitTree(INPUT_FILE); MethodTree methodTree = TreeNavigationUtils.findMethodTreeByName("doSomething", unit).get(0); IfTree IfTree = (IfTree) getStatementTreeByClassName(IfTree.class, methodTree); if (IfTree == null) { fail(ERROR_MESSAGE); } ReformatTreeVisitor reformatTreeVisitor = getReformatTreeVisitor(INPUT_FILE, 0, 10); reformatTreeVisitor.visitIf(IfTree, optionsToReformat); assertTrue(optionsToReformat.isEmpty()); }
@Override public boolean matches(Tree tree, VisitorState state) { if (tree instanceof IfTree) { ExpressionTree conditionTree = ASTHelpers.stripParentheses(((IfTree) tree).getCondition()); if (conditionTree instanceof InstanceOfTree) { InstanceOfTree instanceOfTree = (InstanceOfTree) conditionTree; Types types = state.getTypes(); boolean isCastable = types.isCastable( types.erasure(ASTHelpers.getType(instanceOfTree.getType())), types.erasure(ASTHelpers.getType(typeTree))); boolean isSameExpression = instanceOfTree.getExpression().toString().equals(expressionTree.toString()); return isSameExpression && !isCastable; } } return false; }
private boolean isTerminating(StatementTree tree) { StatementTree first = firstStatement(tree); if (first instanceof ThrowTree) return true; if (first instanceof ReturnTree) return true; if (first instanceof IfTree) { IfTree ifTree = (IfTree)first; if (ifTree.getElseStatement() != null && isTerminating(ifTree.getThenStatement()) && isTerminating(ifTree.getElseStatement())) return true; } return false; }
/** * Case 5: get() is preceded by put-if-absent pattern */ private Matcher preceededByIfThenPut(final Element key, final VariableElement map) { return preceededBy(ofKind(Tree.Kind.IF, new Matcher() { @Override public Boolean visitIf(IfTree tree, Void p) { if (isNotContained(key, map, tree.getCondition())) { StatementTree first = firstStatement(tree.getThenStatement()); if (first != null && first.getKind() == Tree.Kind.EXPRESSION_STATEMENT && isInvocationOfPut(key, map, ((ExpressionStatementTree)first).getExpression())) { return true; } } return false; } })); }
@Override public boolean match(TreePath path) { TreePath prev = path, p = path.getParentPath(); while (p != null) { if (p.getLeaf().getKind() == Tree.Kind.IF) { IfTree ifTree = (IfTree)p.getLeaf(); ExpressionTree cond = TreeUtils.skipParens(ifTree.getCondition()); if (ifTree.getThenStatement() == prev.getLeaf() && matcher.match(new TreePath(p, cond))) return true; if (cond.getKind() == Tree.Kind.LOGICAL_COMPLEMENT && matcher.match(new TreePath(p, ((UnaryTree)cond).getExpression()))) return true; } prev = p; p = p.getParentPath(); } return false; }
@Override public Tree visitIf(IfTree tree, Void p) { IfTree n = make.If(tree.getCondition(), tree.getThenStatement(), tree.getElseStatement()); model.setType(n, model.getType(tree)); comments.copyComments(tree, n); model.setPos(n, model.getPos(tree)); return n; }
public Boolean visitIf(IfTree node, TreePath p) { if (p == null) return super.visitIf(node, p); IfTree t = (IfTree) p.getLeaf(); if (!scan(node.getCondition(), t.getCondition(), p)) return false; if (!scan(node.getThenStatement(), t.getThenStatement(), p)) return false; return scan(node.getElseStatement(), t.getElseStatement(), p); }
public void test159940() throws Exception { String test = "class Test {\n" + " void m(int p) {\n" + " i|f (p > 5);\n" + " }\n" + "}"; String golden = test.replace("|", ""); testFile = new File(getWorkDir(), "Test.java"); final int indexA = test.indexOf("|"); assertTrue(indexA != -1); TestUtilities.copyStringToFile(testFile, test.replace("|", "")); JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy copy) throws Exception { if (copy.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) < 0) { return; } Tree node = copy.getTreeUtilities().pathFor(indexA).getLeaf(); assertEquals(Kind.IF, node.getKind()); TreeMaker make = copy.getTreeMaker(); StatementTree original = ((IfTree) node).getThenStatement(); StatementTree modified = make.EmptyStatement(); System.out.println("original: " + original); System.out.println("modified: " + modified); copy.rewrite(original, modified); } }; src.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); assertEquals(golden, res); }
public void test158154OneIf() throws Exception { String source = "class Test {\n" + " void m1(boolean b) {\n" + " if (b) ; else System.out.println(\"hi\");\n" + " }\n" + "}"; String golden = "class Test {\n" + " void m1(boolean b) {\n" + " if (!(b)) System.out.println(\"hi\");\n" + " }\n" + "}"; testFile = new File(getWorkDir(), "Test.java"); TestUtilities.copyStringToFile(testFile, source); JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy copy) throws Exception { if (copy.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) < 0) { return; } TreeMaker make = copy.getTreeMaker(); ClassTree clazz = (ClassTree) copy.getCompilationUnit().getTypeDecls().get(0); MethodTree method = (MethodTree) clazz.getMembers().get(1); BlockTree block = method.getBody(); IfTree original = (IfTree) block.getStatements().get(0); IfTree modified = make.If( make.Parenthesized( make.Unary(Kind.LOGICAL_COMPLEMENT, original.getCondition())), original.getElseStatement(), null); copy.rewrite(original, modified); } }; src.runModificationTask(task).commit(); String res = TestUtilities.copyFileToString(testFile); System.out.println(res); assertEquals(golden, res); }
public void testBreak158130b() throws Exception { String test = "public class Test { void m(int p) { loop: while (true) { i|f (p == 0) { break loop; } else { break ; } } } }"; String golden = "public class Test { void m(int p) { loop: while (true) { if (p == 0) { break ; } } } }"; testHelper(test, golden, Kind.IF, new Delegate() { public void run(WorkingCopy copy, Tree tree) { IfTree original = (IfTree) tree; IfTree modified = copy.getTreeMaker().If(original.getCondition(), original.getElseStatement(), null); copy.rewrite(original, modified); } }); }
public void testBreak158130c() throws Exception { String test = "public class Test { void m(int p) { loop: while (true) { i|f (p == 0) { break loop; } else { break; } } } }"; String golden = "public class Test { void m(int p) { loop: while (true) { if (p == 0) { break; } } } }"; testHelper(test, golden, Kind.IF, new Delegate() { public void run(WorkingCopy copy, Tree tree) { IfTree original = (IfTree) tree; IfTree modified = copy.getTreeMaker().If(original.getCondition(), original.getElseStatement(), null); copy.rewrite(original, modified); } }); }
@Override public Boolean visitIf(IfTree node, Stack<Tree> p) { scan(node.getCondition(), p); Boolean thenResult = scan(node.getThenStatement(), p); Boolean elseResult = scan(node.getElseStatement(), p); if (thenResult == Boolean.TRUE && elseResult == Boolean.TRUE) return Boolean.TRUE; return null; }
@Override public Void visitIf(IfTree node, EnumSet<UseTypes> p) { scan(node.getCondition(), EnumSet.of(UseTypes.READ)); scan(node.getThenStatement(), p); scan(node.getElseStatement(), p); return null; }
@Override public Number visitIf(IfTree node, Void p) { IfTree nue = make.If(node.getCondition(), node.getThenStatement(), resolveOptionalValue(node.getElseStatement())); rewrite(node, nue); return super.visitIf(nue, p); }
@Override public Object visitReturn(ReturnTree node, Object p) { TreePath path = getCurrentPath(); TreePath parentPath = path.getParentPath(); if (suppress) { return super.visitReturn(node, p); } if (ignoreGuards && parentPath != null) { Tree parentTree = parentPath.getLeaf(); TreePath branchPath = path; while (parentTree.getKind() == Tree.Kind.BLOCK) { branchPath = parentPath; parentPath = parentPath.getParentPath(); parentTree = parentPath.getLeaf(); } if (parentTree.getKind() == Tree.Kind.IF) { IfTree ifTree = (IfTree)parentTree; StatementTree trueTree = ifTree.getThenStatement() == branchPath.getLeaf() ? ifTree.getThenStatement() : ifTree.getElseStatement(); if (trueTree == node) { return super.visitReturn(node, p); } if (trueTree.getKind() == Tree.Kind.BLOCK) { BlockTree bt = (BlockTree)trueTree; if (bt.getStatements().size() == 1) { return super.visitReturn(node, p); } } } } returnCount++; return super.visitReturn(node, p); }
@Override public Object visitIf(IfTree node, Object p) { depth++; Object o = super.visitIf(node, p); depth--; return o; }
@Override public Void visitIf(IfTree tree, List<Node> d) { List<Node> below = new ArrayList<Node>(); addCorrespondingType(below); addCorrespondingComments(below); super.visitIf(tree, below); d.add(new TreeNode(info, getCurrentPath(), below)); return null; }
private boolean isReturningIf( IfTree ifTree) { StatementTree then = ifTree.getThenStatement(); if (then.getKind() == Tree.Kind.RETURN) { return true; } else if (then.getKind() == Tree.Kind.BLOCK) { BlockTree block = (BlockTree) then; if (block.getStatements().size() == 1 && block.getStatements().get(0).getKind() == Tree.Kind.RETURN) { return true; } } return false; }
private Boolean isIfWithContinue( IfTree ifTree) { StatementTree then = ifTree.getThenStatement(); if (then.getKind() == Tree.Kind.CONTINUE) { return true; } else if (then.getKind() == Tree.Kind.BLOCK) { List<? extends StatementTree> statements = ((BlockTree) then).getStatements(); if (statements.size() == 1 && statements.get(0).getKind() == Tree.Kind.CONTINUE) { return true; } } return false; }
private List<ProspectiveOperation> getBlockListRepresentation( StatementTree tree, boolean last) { List<ProspectiveOperation> ls = new ArrayList<ProspectiveOperation>(); BlockTree blockTree = (BlockTree) tree; List<? extends StatementTree> statements = blockTree.getStatements(); for ( int i = 0; i < statements.size(); i++) { StatementTree statement = statements.get(i); boolean l = last && i == statements.size() - 1; if (statement.getKind() == Tree.Kind.IF) { IfTree ifTree = (IfTree) statement; if (isIfWithContinue(ifTree)) { ifTree = refactorContinuingIf(ifTree, statements.subList(i + 1, statements.size())); // the if was refactored, so that all the statements are nested in it, so it became // the last (and single) statement within the parent ls.addAll(this.getListRepresentation(ifTree, last)); break; } else if (l) { ls.addAll(this.getListRepresentation(ifTree, true)); } else { if (this.isReturningIf(ifTree)) { this.untrasformable = true; } ls.addAll(ProspectiveOperation.createOperator(ifTree, ProspectiveOperation.OperationType.MAP, preconditionsChecker, workingCopy)); } } else { ls.addAll(getListRepresentation(statement, l)); } } return ls; }
private List<ProspectiveOperation> getIfListRepresentation( StatementTree tree, boolean last) { IfTree ifTree = (IfTree) tree; List<ProspectiveOperation> ls = new ArrayList<ProspectiveOperation>(); if (ifTree.getElseStatement() == null) { StatementTree then = ifTree.getThenStatement(); if (isOneStatementBlock(then)) { then = ((BlockTree) then).getStatements().get(0); } if (then.getKind() == Tree.Kind.RETURN) { ReturnTree returnTree = (ReturnTree) then; ExpressionTree returnExpression = returnTree.getExpression(); if (returnExpression.getKind() == Tree.Kind.BOOLEAN_LITERAL && ((LiteralTree) returnExpression).getValue().equals(true)) { ls.addAll(ProspectiveOperation.createOperator(ifTree, ProspectiveOperation.OperationType.ANYMATCH, this.preconditionsChecker, this.workingCopy)); } else if (returnExpression.getKind() == Tree.Kind.BOOLEAN_LITERAL && ((LiteralTree) returnExpression).getValue().equals(false)) { ls.addAll(ProspectiveOperation.createOperator(ifTree, ProspectiveOperation.OperationType.NONEMATCH, this.preconditionsChecker, this.workingCopy)); } } else { ls.addAll(ProspectiveOperation.createOperator(ifTree, ProspectiveOperation.OperationType.FILTER, this.preconditionsChecker, this.workingCopy)); ls.addAll(getListRepresentation(ifTree.getThenStatement(), last)); } } else { ls.addAll(ProspectiveOperation.createOperator(ifTree, ProspectiveOperation.OperationType.MAP, this.preconditionsChecker, this.workingCopy)); } return ls; }
private boolean thisIsMatcherReturn(Tree that, TreePath currentTreePath) { TreePath parentPath = currentTreePath.getParentPath(); Tree parent = parentPath.getLeaf(); if (parent.getKind() == Tree.Kind.BLOCK && ((BlockTree) parent).getStatements().size() == 1) { return thisIsMatcherReturn(parent, parentPath); } else if (parent.getKind() == Tree.Kind.IF && ((IfTree) parent).getElseStatement() == null) { return true; } return false; }
public void merge(ProspectiveOperation op) { if (this.opType == OperationType.FILTER) { this.opType = op.opType; IfTree ifTree = this.treeMaker.If(((IfTree) this.correspondingTree).getCondition(), (StatementTree) op.correspondingTree, null); this.correspondingTree = ifTree; } else { this.opType = op.opType; List<StatementTree> statements = new ArrayList<StatementTree>(); if (this.correspondingTree.getKind() == Tree.Kind.BLOCK) { statements.addAll(((BlockTree) this.correspondingTree).getStatements()); } else { statements.add(castToStatementTree(this.correspondingTree)); } if (op.correspondingTree.getKind() == Tree.Kind.BLOCK) { statements.addAll(((BlockTree) op.correspondingTree).getStatements()); } else { statements.add(castToStatementTree(op.correspondingTree)); } HashSet<Name> futureAvailable = new HashSet<Name>(); HashSet<Name> futureNeeded = new HashSet<Name>(); futureAvailable.addAll(this.getAvailableVariables()); futureAvailable.addAll(op.getAvailableVariables()); futureNeeded.addAll(op.getNeededVariables()); futureNeeded.removeAll(this.getAvailableVariables()); futureNeeded.addAll(this.getNeededVariables()); this.neededVariables = futureNeeded; this.availableVariables = futureAvailable; this.correspondingTree = this.treeMaker.Block(statements, false); } }
@Hint(displayName="#DN_JoinElseIf", description="#DESC_JoinElseIf", category="suggestions", hintKind=Hint.Kind.ACTION) @TriggerPattern("if ($cond1) $then1; else { if ($cond2) $then2; else $else$; }") @Messages({"ERR_JoinElseIf=", "FIX_JoinElseIf=Join nested if into the enclosing if"}) public static ErrorDescription joinElseIf(HintContext ctx) { IfTree it = (IfTree) ctx.getPath().getLeaf(); if (it.getElseStatement().getKind() != Kind.BLOCK) return null; if (!caretInsideToLevelElseKeyword(ctx)) return null; return ErrorDescriptionFactory.forSpan(ctx, ctx.getCaretLocation(), ctx.getCaretLocation(), Bundle.ERR_JoinElseIf(), new JoinIfFix(ctx.getInfo(), ctx.getPath()).toEditorFix()); }
private static boolean caretInsideToLevelElseKeyword(HintContext ctx) { IfTree it = (IfTree) ctx.getPath().getLeaf(); SourcePositions sp = ctx.getInfo().getTrees().getSourcePositions(); CompilationUnitTree cut = ctx.getInfo().getCompilationUnit(); int elsePos = (int) sp.getStartPosition(cut, it.getElseStatement()); return caretInsidePreviousToken(ctx, elsePos, JavaTokenId.ELSE); }
@Hint(id="org.netbeans.modules.java.hints.suggestions.Tiny.mergeIfs", displayName = "#DN_org.netbeans.modules.java.hints.suggestions.Tiny.mergeIfs", description = "#DESC_org.netbeans.modules.java.hints.suggestions.Tiny.mergeIfs", category="suggestions", hintKind=org.netbeans.spi.java.hints.Hint.Kind.ACTION, severity=Severity.HINT) @TriggerPattern(value="if ($firstCondition) if ($secondCondition) $body;") public static ErrorDescription mergeIfs(HintContext ctx) { int caret = ctx.getCaretLocation(); IfTree st = (IfTree) ctx.getPath().getLeaf(); int conditionEnd = (int) ctx.getInfo().getTrees().getSourcePositions().getEndPosition(ctx.getPath().getCompilationUnit(), st.getCondition()); if (caret > conditionEnd) return null; Fix f = JavaFixUtilities.rewriteFix(ctx, Bundle.FIX_org_netbeans_modules_java_hints_suggestions_Tiny_mergeIfs(), ctx.getPath(), "if ($firstCondition && $secondCondition) $body;"); return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_org_netbeans_modules_java_hints_suggestions_Tiny_mergeIfs(), f); }
/** * @return Returns boolean expression for if-conditional */ @Override public List<? extends TypeMirror> visitIf(IfTree node, Object p) { if (theExpression == null) { initExpression(node.getCondition()); } return booleanType(); }
public ChangeInfo implement() throws Exception { js.runModificationTask(new Task<WorkingCopy>() { public void run(WorkingCopy wc) throws Exception { wc.toPhase(Phase.RESOLVED); TreePath ifTP = ifHandle.resolve(wc); TreePath resolvedExpression = expression.resolve(wc); TypeMirror resolvedType = type.resolve(wc); if (ifTP == null || resolvedType == null || resolvedExpression == null) { return ; } IfTree ift = (IfTree) ifTP.getLeaf(); StatementTree then = ift.getThenStatement(); if (then.getKind() == Kind.ERRONEOUS) { return ; //TODO. } List<StatementTree> statements = new LinkedList<StatementTree>(); if (then.getKind() == Kind.BLOCK) { statements.addAll(((BlockTree) then).getStatements()); } else { statements.add(then); } TreeMaker make = wc.getTreeMaker(); VariableTree decl = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), name, make.Type(resolvedType), make.TypeCast(make.Type(resolvedType), (ExpressionTree) resolvedExpression.getLeaf())); statements.add(0, decl); BlockTree nue = make.Block(statements, false); wc.rewrite(then, nue); } }).commit(); return null; }
private boolean insideElse(CompilationController controller, IfTree ifTree, int caretPosition) { if (ifTree.getElseStatement() == null) { return false; } SourcePositions sp = controller.getTrees().getSourcePositions(); int end = (int) sp.getEndPosition(controller.getCompilationUnit(), ifTree.getThenStatement()); return end > 0 && caretPosition > end; }
@Override public List<Tree> visitIf(IfTree node, ExpressionScanner.ExpressionsInfo p) { List<Tree> cond = null; Tree lastCond = null; if (acceptsTree(node)) { cond = scan(node.getCondition(), p); if (cond != null) { lastCond = cond.get(cond.size() - 1); } } StatementTree thent = node.getThenStatement(); StatementTree elset = node.getElseStatement(); List<Tree> thenr = null; if (isCurrentTree(thent)) { thenr = scan(thent, p); if (lastCond != null && thenr != null) { p.addNextExpression(lastCond, thenr.get(0)); } } List<Tree> elser = null; if (isCurrentTree(elset)) { elser = scan(elset, p); if (lastCond != null && elser != null) { p.addNextExpression(lastCond, elser.get(0)); } } return reduce(reduce(cond, thenr), elser); }