Java Code Examples for com.sun.source.tree.BlockTree#getStatements()

The following examples show how to use com.sun.source.tree.BlockTree#getStatements() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ForLoopToFunctionalHint.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@TriggerTreeKind(Tree.Kind.ENHANCED_FOR_LOOP)
@Messages("ERR_ForLoopToFunctionalHint=Can use functional operations")
public static ErrorDescription computeWarning(HintContext ctx) {
    if (ctx.getInfo().getElements().getTypeElement("java.util.stream.Streams") == null && !DISABLE_CHECK_FOR_STREAM) return null;
    
    PreconditionsChecker pc = new PreconditionsChecker(ctx.getPath().getLeaf(), ctx.getInfo());
    if (pc.isSafeToRefactor()) {
        EnhancedForLoopTree eflt = (EnhancedForLoopTree)ctx.getPath().getLeaf();
        StatementTree stmt = eflt.getStatement();
        if (stmt == null) {
            return null;
        }
        if (stmt.getKind() == Tree.Kind.BLOCK) {
            BlockTree bt = (BlockTree)stmt;
            if (bt.getStatements() == null || bt.getStatements().isEmpty()) {
                return null;
            }
        }
        Fix fix = new FixImpl(ctx.getInfo(), ctx.getPath(), null).toEditorFix();
        return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_ForLoopToFunctionalHint(), fix);
    }
    return null;
}
 
Example 2
Source File: Flow.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 3
Source File: AssignResultToVariable.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private StatementTree findExactStatement(CompilationInfo info, BlockTree block, int offset, boolean start) {
    if (offset == (-1)) return null;
    
    SourcePositions sp = info.getTrees().getSourcePositions();
    CompilationUnitTree cut = info.getCompilationUnit();
    
    for (StatementTree t : block.getStatements()) {
        long pos = start ? sp.getStartPosition(info.getCompilationUnit(), t) : sp.getEndPosition( cut, t);

        if (offset == pos) {
            return t;
        }
    }

    return null;
}
 
Example 4
Source File: AssignResultToVariable.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private StatementTree findMatchingMethodInvocation(CompilationInfo info, BlockTree block, int offset) {
    for (StatementTree t : block.getStatements()) {
        if (t.getKind() != Kind.EXPRESSION_STATEMENT) continue;

        long statementStart = info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), t);

        if (offset < statementStart) return null;

        ExpressionStatementTree est = (ExpressionStatementTree) t;
        long statementEnd = info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), t);
        long expressionEnd = info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), est.getExpression());

        if (expressionEnd <= offset && offset < statementEnd) {
            return t;
        }
    }

    return null;
}
 
Example 5
Source File: LocalClassScanner.java    From annotation-tools with MIT License 6 votes vote down vote up
@Override
public Void visitBlock(BlockTree node, Integer level) {
  if (level < 1) {
    // Visit blocks since a local class can only be in a block. Then visit each
    // statement of the block to see if any are the correct local class.
    for (StatementTree statement : node.getStatements()) {
      if (!found && statement.getKind() == Tree.Kind.CLASS) {
        ClassTree c = (ClassTree) statement;
        if (localClass == statement) {
          found = true;
        } else if (c.getSimpleName().equals(localClass.getSimpleName())) {
          index++;
        }
      }
    }
    super.visitBlock(node, level + 1);
  }
  return null;
}
 
Example 6
Source File: Refactorer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 7
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
/** does the constructor invoke another constructor in the same class via this(...)? */
private boolean constructorInvokesAnother(MethodTree constructor, VisitorState state) {
  BlockTree body = constructor.getBody();
  List<? extends StatementTree> statements = body.getStatements();
  if (statements.size() > 0) {
    StatementTree statementTree = statements.get(0);
    if (isThisCall(statementTree, state)) {
      return true;
    }
  }
  return false;
}
 
Example 8
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
/**
 * @param blockTree block of statements
 * @param state visitor state
 * @return Elements of safe init methods that are invoked as top-level statements in the method
 */
private Set<Element> getSafeInitMethods(
    BlockTree blockTree, Symbol.ClassSymbol classSymbol, VisitorState state) {
  Set<Element> result = new LinkedHashSet<>();
  List<? extends StatementTree> statements = blockTree.getStatements();
  for (StatementTree stmt : statements) {
    Element privMethodElem = getInvokeOfSafeInitMethod(stmt, classSymbol, state);
    if (privMethodElem != null) {
      result.add(privMethodElem);
    }
    // Hack: If we see a try{...}finally{...} statement, without a catch, we consider the methods
    // inside both blocks
    // as "top level" for the purposes of finding initialization methods. Any exception happening
    // there is also an
    // exception of the full method.
    if (stmt.getKind().equals(Tree.Kind.TRY)) {
      TryTree tryTree = (TryTree) stmt;
      if (tryTree.getCatches().size() == 0) {
        if (tryTree.getBlock() != null) {
          result.addAll(getSafeInitMethods(tryTree.getBlock(), classSymbol, state));
        }
        if (tryTree.getFinallyBlock() != null) {
          result.addAll(getSafeInitMethods(tryTree.getFinallyBlock(), classSymbol, state));
        }
      }
    }
  }
  return result;
}
 
Example 9
Source File: CompletenessStressTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 10
Source File: TreeConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private TreeNode convertBlock(BlockTree node, TreePath parent) {
  TreePath path = getTreePath(parent, node);
  Block newNode = new Block();
  for (StatementTree stmt : node.getStatements()) {
    TreeNode tree = convert(stmt, path);
    if (tree instanceof AbstractTypeDeclaration) {
      tree = new TypeDeclarationStatement().setDeclaration((AbstractTypeDeclaration) tree);
    }
    newNode.addStatement((Statement) tree);
  }
  return newNode;
}
 
Example 11
Source File: JavaDocGenerator.java    From vertx-docgen with Apache License 2.0 5 votes vote down vote up
/**
 * Render the source fragment for the Java language. Java being the pivot language, we consider this method as the
 * _default_ behavior. This method is final as it must not be overridden by any extension.
 *
 * @param elt    the element
 * @param source the source
 * @return the fragment
 */
@Override
public String renderSource(ExecutableElement elt, String source) {
  // Get block
  TreePath path = docTrees.getPath(elt);
  MethodTree methodTree = (MethodTree) path.getLeaf();
  BlockTree blockTree = methodTree.getBody();
  List<? extends StatementTree> statements = blockTree.getStatements();
  if (statements.size() > 0) {
    return renderSource(path, statements, source);
  } else {
    return null;
  }
}
 
Example 12
Source File: MagicSurroundWithTryCatchFix.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public @Override Void visitTry(TryTree tt, Void p) {
    List<CatchTree> catches = new ArrayList<CatchTree>();
            
    catches.addAll(tt.getCatches());
    catches.addAll(createCatches(info, make, thandles, statement));
    
    if (!streamAlike) {
        info.rewrite(tt, make.Try(tt.getResources(), tt.getBlock(), catches, tt.getFinallyBlock()));
    } else {
        VariableTree originalDeclaration = (VariableTree) statement.getLeaf();
        VariableTree declaration = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), originalDeclaration.getName(), originalDeclaration.getType(), make.Literal(null));
        StatementTree assignment = make.ExpressionStatement(make.Assignment(make.Identifier(originalDeclaration.getName()), originalDeclaration.getInitializer()));
        List<StatementTree> finallyStatements = new ArrayList<StatementTree>(tt.getFinallyBlock() != null ? tt.getFinallyBlock().getStatements() : Collections.<StatementTree>emptyList());
        
        finallyStatements.add(createFinallyCloseBlockStatement(originalDeclaration));
        
        BlockTree finallyTree = make.Block(finallyStatements, false);
        
        info.rewrite(originalDeclaration, assignment);
        
        TryTree nueTry = make.Try(tt.getResources(), tt.getBlock(), catches, finallyTree);
        
        TreePath currentBlockCandidate = statement;
        
        while (currentBlockCandidate.getLeaf() != tt) {
            currentBlockCandidate = currentBlockCandidate.getParentPath();
        }

        currentBlockCandidate = currentBlockCandidate.getParentPath();
        
        if (currentBlockCandidate.getLeaf().getKind() == Kind.BLOCK) {
            BlockTree originalTree = (BlockTree) currentBlockCandidate.getLeaf();
            List<StatementTree> statements = new ArrayList<StatementTree>(originalTree.getStatements());
            int index = statements.indexOf(tt);
            
            statements.remove(index);
            statements.add(index, nueTry);
            statements.add(index, declaration);
            info.rewrite(originalTree, make.Block(statements, originalTree.isStatic()));
        } else {
            BlockTree nueBlock = make.Block(Arrays.asList(declaration, nueTry), false);
            
            info.rewrite(tt, nueBlock);
        }
    }
    
    return null;
}
 
Example 13
Source File: NullAway.java    From NullAway with MIT License 4 votes vote down vote up
/**
 * computes those fields always initialized by callee safe init methods before a read operation
 * (pathToRead) is invoked. See <a
 * href="https://github.com/uber/NullAway/wiki/Error-Messages#initializer-method-does-not-guarantee-nonnull-field-is-initialized--nonnull-field--not-initialized">the
 * docs</a> for what is considered a safe initializer method.
 */
private ImmutableSet<Element> safeInitByCalleeBefore(
    TreePath pathToRead, VisitorState state, TreePath enclosingBlockPath) {
  Set<Element> safeInitMethods = new LinkedHashSet<>();
  Tree enclosingBlockOrMethod = enclosingBlockPath.getLeaf();
  if (enclosingBlockOrMethod instanceof VariableTree) {
    return ImmutableSet.of();
  }
  ImmutableSet.Builder<Element> resultBuilder = ImmutableSet.builder();
  BlockTree blockTree =
      enclosingBlockOrMethod instanceof BlockTree
          ? (BlockTree) enclosingBlockOrMethod
          : ((MethodTree) enclosingBlockOrMethod).getBody();
  List<? extends StatementTree> statements = blockTree.getStatements();
  Tree readExprTree = pathToRead.getLeaf();
  int readStartPos = getStartPos((JCTree) readExprTree);
  TreePath classTreePath = enclosingBlockPath;
  // look for the parent ClassTree node, which represents the enclosing class / enum / interface
  while (!(classTreePath.getLeaf() instanceof ClassTree)) {
    classTreePath = classTreePath.getParentPath();
    if (classTreePath == null) {
      throw new IllegalStateException(
          "could not find enclosing class / enum / interface for "
              + state.getSourceForNode(enclosingBlockPath.getLeaf()));
    }
  }
  Symbol.ClassSymbol classSymbol = ASTHelpers.getSymbol((ClassTree) classTreePath.getLeaf());
  for (int i = 0; i < statements.size(); i++) {
    StatementTree curStmt = statements.get(i);
    if (getStartPos((JCTree) curStmt) <= readStartPos) {
      Element privMethodElem = getInvokeOfSafeInitMethod(curStmt, classSymbol, state);
      if (privMethodElem != null) {
        safeInitMethods.add(privMethodElem);
      }
      // Hack: Handling try{...}finally{...} statement, see getSafeInitMethods
      if (curStmt.getKind().equals(Tree.Kind.TRY)) {
        TryTree tryTree = (TryTree) curStmt;
        // ToDo: Should we check initialization inside tryTree.getResources ? What is the scope of
        // that initialization?
        if (tryTree.getCatches().size() == 0) {
          if (tryTree.getBlock() != null) {
            resultBuilder.addAll(
                safeInitByCalleeBefore(
                    pathToRead, state, new TreePath(enclosingBlockPath, tryTree.getBlock())));
          }
          if (tryTree.getFinallyBlock() != null) {
            resultBuilder.addAll(
                safeInitByCalleeBefore(
                    pathToRead,
                    state,
                    new TreePath(enclosingBlockPath, tryTree.getFinallyBlock())));
          }
        }
      }
    }
  }
  addGuaranteedNonNullFromInvokes(
      state, getTreesInstance(state), safeInitMethods, getNullnessAnalysis(state), resultBuilder);
  return resultBuilder.build();
}