ComplexityVisitor extends BaseTreeVisitor { public List<Tree> getNodes(Tree tree) { blame.clear(); root = tree; scan(tree); root = null; return blame; }  List<Tree> getNodes(Tree tree); @Override void visitMethod(MethodTree tree); @Override void visitClass(ClassTree tree); @Override void visitLambdaExpression(LambdaExpressionTree lambdaExpressionTree); @Override void visitCaseLabel(CaseLabelTree tree); @Override void visitForEachStatement(ForEachStatement tree); @Override void visitForStatement(ForStatementTree tree); @Override void visitWhileStatement(WhileStatementTree tree); @Override void visitDoWhileStatement(DoWhileStatementTree tree); @Override void visitIfStatement(IfStatementTree tree); @Override void visitConditionalExpression(ConditionalExpressionTree tree); @Override void visitBinaryExpression(BinaryExpressionTree tree);  }
@Test void lambda_complexity() throws Exception { CompilationUnitTree cut = JParserTestUtils.parse("class A { Function f = s -> {if(s.isEmpty()) return s; return new MyClass(){ void foo(){if(a) return;} };};}"); ExpressionTree lambda = ((VariableTree) ((ClassTree) cut.types().get(0)).members().get(0)).initializer(); List<Tree> nodes = new ComplexityVisitor().getNodes(lambda); assertThat(nodes).hasSize(2); }
@Test void method_complexity() throws Exception { CompilationUnitTree cut = JParserTestUtils.parse("class A {" + " Object foo(){" + " if(a) { " + " return new MyClass(){ " + " void foo(){" + " if(a) {return;} " + " } " + " };" + " } " + "}}"); MethodTree methodTree = (MethodTree) ((ClassTree) cut.types().get(0)).members().get(0); List<Tree> nodes = new ComplexityVisitor().getNodes(methodTree); assertThat(nodes).hasSize(2); }
@Test void switch_handling() throws Exception { CompilationUnitTree cut = JParserTestUtils.parse( "class A {" + " String foo(int a) {" + " switch (a) {" + " case 0:" + " return \"none\";" + " case 1:" + " return \"one\";" + " case 2:" + " return \"many\";" + " default:" + " return \"it's complicated\";" + " }" + " }" + "}"); MethodTree methodTree = (MethodTree) ((ClassTree) cut.types().get(0)).members().get(0); List<Tree> nodes = new ComplexityVisitor().getNodes(methodTree); assertThat(nodes).hasSize(4); }