Java Code Examples for com.sun.source.tree.Tree.Kind#BLOCK

The following examples show how to use com.sun.source.tree.Tree.Kind#BLOCK . 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: CompilationUnitBuilder.java    From j2cl with Apache License 2.0 7 votes vote down vote up
private Block convertLambdaBody(JCTree lambdaBody, TypeDescriptor returnTypeDescriptor) {
  Block body;
  if (lambdaBody.getKind() == Kind.BLOCK) {
    body = convertBlock((JCBlock) lambdaBody);
  } else {
    checkArgument(lambdaBody instanceof JCExpression);
    Expression lambdaMethodBody = convertExpression((JCExpression) lambdaBody);
    Statement statement =
        AstUtils.createReturnOrExpressionStatement(
            getSourcePosition(lambdaBody), lambdaMethodBody, returnTypeDescriptor);
    body =
        Block.newBuilder()
            .setSourcePosition(getSourcePosition(lambdaBody))
            .setStatements(statement)
            .build();
  }
  return body;
}
 
Example 2
Source File: JavaPluginUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static TreePath findMethod(TreePath path) {
    while (path != null) {
        if (path.getLeaf().getKind() == Kind.METHOD) {
            return path;
        }

        if (path.getLeaf().getKind() == Kind.BLOCK
                && path.getParentPath() != null
                && TreeUtilities.CLASS_TREE_KINDS.contains(path.getParentPath().getLeaf().getKind())) {
            //initializer:
            return path;
        }

        path = path.getParentPath();
    }

    return null;
}
 
Example 3
Source File: IteratorToFor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@TriggerPattern(value = "java.util.Iterator $it = $coll.iterator(); while ($it.hasNext()) {$type $elem = ($type) $it.next(); $rest$;}", 
        constraints = @ConstraintVariableType(variable = "$coll", type = "java.lang.Iterable"))
public static ErrorDescription whileIdiom(HintContext ctx) {
    if (uses(ctx, ctx.getMultiVariables().get("$rest$"), ctx.getVariables().get("$it"))) {
        return null;
    }
    if (!iterable(ctx, ctx.getVariables().get("$coll"), ctx.getVariables().get("$type"))) {
        return null;
    }
    String colString = ctx.getVariables().containsKey("$coll") ? "$coll" : "this";
    Tree highlightTarget = ctx.getPath().getLeaf();
    TreePath elem = ctx.getVariables().get("$elem");
    if (elem.getParentPath() != null && elem.getParentPath().getLeaf().getKind() == Kind.BLOCK) elem = elem.getParentPath();
    if (elem.getParentPath() != null && elem.getParentPath().getLeaf().getKind() == Kind.WHILE_LOOP) highlightTarget = elem.getParentPath().getLeaf();
    return ErrorDescriptionFactory.forName(ctx, highlightTarget, Bundle.ERR_IteratorToFor(),
            JavaFixUtilities.rewriteFix(ctx, Bundle.FIX_IteratorToFor(), ctx.getPath(), "for ($type $elem : " + colString + ") {$rest$;}"));
}
 
Example 4
Source File: CopyFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isSingleStatemenBlockAndStatement(Tree t1, Tree t2) {
    Kind k1 = t1.getKind();
    Kind k2 = t2.getKind();

    if (k1 == Kind.BLOCK && ((BlockTree) t1).getStatements().size() == 1 && !((BlockTree) t1).isStatic()) {
        return StatementTree.class.isAssignableFrom(k2.asInterface());
    }

    return false;
}
 
Example 5
Source File: OrigSurroundWithTryCatchFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private TreePath findBlockOrCase(TreePath path) {
    while (path != null && path.getLeaf().getKind() != Kind.BLOCK && path.getLeaf().getKind() != Kind.CASE) {
        path = path.getParentPath();
    }
    
    return path;
}
 
Example 6
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Finds the top-level block or expression that contains the 'from' path.
 * The result could be a 
 * <ul>
 * <li>BlockTree representing method body
 * <li>ExpressionTree representing field initializer
 * <li>BlockTree representing class initializer
 * <li>ExpressionTree representing lambda expression
 * <li>BlockTree representing lambda expression
 * </ul>
 * @param from start from 
 * @return nearest enclosing top-level block/expression as defined above.
 */
public static TreePath findTopLevelBlock(TreePath from) {
    if (from.getLeaf().getKind() == Tree.Kind.COMPILATION_UNIT) {
        return null;
    }
    TreePath save = null;
    
    while (from != null) {
        Tree.Kind k = from.getParentPath().getLeaf().getKind();
        if (k == Kind.METHOD || k == Kind.LAMBDA_EXPRESSION) {
            return from;
        } else if (k == Kind.VARIABLE) {
            save = from;
        } else if (TreeUtilities.CLASS_TREE_KINDS.contains(k)) {
            if (save != null) {
                // variable initializer from the previous iteration
                return save;
            }
            if (from.getLeaf().getKind() == Kind.BLOCK) {
                // parent is class, from is block -> initializer
                return from;
            }
            return null;
        } else {
            save = null;
        }
        from = from.getParentPath();
    }
    return null;
}
 
Example 7
Source File: AddParameterOrLocalFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private TreePath findBlock(TreePath tp) {
    TreePath block = tp;

    while (block != null) {
        if (block.getLeaf().getKind() == Kind.BLOCK) {
            return block;
        }

        block = block.getParentPath();
    }

    return null;
}
 
Example 8
Source File: AddParameterOrLocalFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean isParent(TreePath parent, TreePath son) {
    TreePath parentBlock = findBlock(parent);
    TreePath block = son;

    while (block != null) {
        if (block.getLeaf().getKind() == Kind.BLOCK) {
            if (block.getLeaf().equals(parentBlock.getLeaf())) {
                return true;
            }
        }
        block = block.getParentPath();
    }

    return false;
}
 
Example 9
Source File: AddParameterOrLocalFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private TreePath findOutmostBlock(TreePath tp) {
    TreePath block = null;

    while (tp != null && !TreeUtilities.CLASS_TREE_KINDS.contains(tp.getLeaf().getKind())) {
        if (tp.getLeaf().getKind() == Kind.BLOCK) {
            block = tp;
        }

        tp = tp.getParentPath();
    }

    return block;
}
 
Example 10
Source File: TreeConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private TreeNode convertEnum(ClassTree node, TreePath parent) {
  TreePath path = getTreePath(parent, node);
  TypeElement element = (TypeElement) getElement(path);
  if (ElementUtil.isAnonymous(element)) {
    return convertClassDeclaration(node, parent).setPosition(getPosition(node));
  }
  EnumDeclaration newNode = new EnumDeclaration();
  convertBodyDeclaration(node, parent, node.getModifiers(), newNode);
  newNode
      .setName(convertSimpleName(element, getTypeMirror(path), getNamePosition(node)))
      .setTypeElement(element);
  for (Tree bodyDecl : node.getMembers()) {
    if (bodyDecl.getKind() == Kind.VARIABLE) {
      TreeNode var = convertVariableDeclaration((VariableTree) bodyDecl, path);
      if (var.getKind() == TreeNode.Kind.ENUM_CONSTANT_DECLARATION) {
        newNode.addEnumConstant((EnumConstantDeclaration) var);
      } else {
        newNode.addBodyDeclaration((BodyDeclaration) var);
      }
    } else if (bodyDecl.getKind() == Kind.BLOCK) {
      BlockTree javacBlock = (BlockTree) bodyDecl;
      Block block = (Block) convert(javacBlock, path);
      newNode.addBodyDeclaration(new Initializer(block, javacBlock.isStatic()));
    } else {
      newNode.addBodyDeclaration((BodyDeclaration) convert(bodyDecl, path));
    }
  }
  return newNode;
}
 
Example 11
Source File: Ifs.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 12
Source File: ConvertToARM.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static TreePath findEnclosingTryPath(final TreePath path) {
    TreePath parent = path.getParentPath();
    if (parent == null || parent.getLeaf().getKind() != Kind.BLOCK) {
        return null;
    }
    parent = parent.getParentPath();
    if (parent == null || parent.getLeaf().getKind() != Kind.TRY) {
        return null;
    }
    return parent;
}
 
Example 13
Source File: JavaPluginUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static TreePath findStatement(TreePath statementPath) {
    while (statementPath != null
            && (!StatementTree.class.isAssignableFrom(statementPath.getLeaf().getKind().asInterface())
            || (statementPath.getParentPath() != null
            && statementPath.getParentPath().getLeaf().getKind() != Kind.BLOCK))) {
        if (TreeUtilities.CLASS_TREE_KINDS.contains(statementPath.getLeaf().getKind())) {
            return null;
        }

        statementPath = statementPath.getParentPath();
    }

    return statementPath;
}
 
Example 14
Source File: TreePathHandle.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Kind getKind() {
    switch (el.getKind()) {
        case PACKAGE:
            return Kind.COMPILATION_UNIT;
            
        case ENUM:
        case CLASS:
        case ANNOTATION_TYPE:
        case INTERFACE:
            return Kind.CLASS;
            
        case ENUM_CONSTANT:
        case FIELD:
        case PARAMETER:
        case LOCAL_VARIABLE:
        case RESOURCE_VARIABLE:
        case EXCEPTION_PARAMETER:
            return Kind.VARIABLE;
            
        case METHOD:
        case CONSTRUCTOR:
            return Kind.METHOD;
            
        case STATIC_INIT:
        case INSTANCE_INIT:
            return Kind.BLOCK;
            
        case TYPE_PARAMETER:
            return Kind.TYPE_PARAMETER;
            
        case OTHER:
        default:
            return Kind.OTHER;
    }
}
 
Example 15
Source File: CopyFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean sameKind(Tree t1, Tree t2) {
    Kind k1 = t1.getKind();
    Kind k2 = t2.getKind();

    if (k1 == k2) {
        return true;
    }

    if (isSingleStatemenBlockAndStatement(t1, t2) || isSingleStatemenBlockAndStatement(t2, t1)) {
        return true;
    }

    if (k2 == Kind.BLOCK && StatementTree.class.isAssignableFrom(k1.asInterface())) {
        BlockTree bt = (BlockTree) t2;

        if (bt.isStatic()) {
            return false;
        }

        switch (bt.getStatements().size()) {
            case 1:
                return true;
            case 2:
                return    isMultistatementWildcardTree(bt.getStatements().get(0))
                       || isMultistatementWildcardTree(bt.getStatements().get(1));
            case 3:
                return    isMultistatementWildcardTree(bt.getStatements().get(0))
                       || isMultistatementWildcardTree(bt.getStatements().get(2));
        }

        return false;
    }

    if (    (k1 != Kind.MEMBER_SELECT && k1 != Kind.IDENTIFIER)
         || (k2 != Kind.MEMBER_SELECT && k2 != Kind.IDENTIFIER)) {
        return false;
    }

    return isPureMemberSelect(t1, true) && isPureMemberSelect(t2, true);
}
 
Example 16
Source File: Tiny.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Hint(displayName = "#DN_indentation", description = "#DESC_indentation", category="bugs", suppressWarnings="SuspiciousIndentAfterControlStatement", options=Options.QUERY)
@TriggerTreeKind({Kind.IF, Kind.WHILE_LOOP, Kind.FOR_LOOP, Kind.ENHANCED_FOR_LOOP})
public static ErrorDescription indentation(HintContext ctx) {
    Tree firstStatement;
    Tree found = ctx.getPath().getLeaf();
    
    switch (found.getKind()) {
        case IF:
            IfTree it = (IfTree) found;
            if (it.getElseStatement() != null) firstStatement = it.getElseStatement();
            else firstStatement = it.getThenStatement();
            break;
        case WHILE_LOOP:
            firstStatement = ((WhileLoopTree) found).getStatement();
            break;
        case FOR_LOOP:
            firstStatement = ((ForLoopTree) found).getStatement();
            break;
        case ENHANCED_FOR_LOOP:
            firstStatement = ((EnhancedForLoopTree) found).getStatement();
            break;
        default:
            return null;
    }
    
    if (firstStatement != null && firstStatement.getKind() == Kind.BLOCK) {
        return null;
    }
    
    Tree parent = ctx.getPath().getParentPath().getLeaf();
    List<? extends Tree> parentStatements;
    
    switch (parent.getKind()) {
        case BLOCK: parentStatements = ((BlockTree) parent).getStatements(); break;
        case CASE: parentStatements = ((CaseTree) parent).getStatements(); break;
        default: return null;
    }
    
    int index = parentStatements.indexOf(found);
    
    if (index < 0 || index + 1 >= parentStatements.size()) return null;
    
    Tree secondStatement = parentStatements.get(index + 1);
    int firstIndent = indent(ctx, firstStatement);
    int secondIndent = indent(ctx, secondStatement);
    
    if (firstIndent == (-1) || secondIndent == (-1) || firstIndent != secondIndent) return null;
    
    return ErrorDescriptionFactory.forTree(ctx, secondStatement, Bundle.ERR_indentation());
}
 
Example 17
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 18
Source File: IteratorToFor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private String assignedToVariable(TransformationContext ctx, TypeMirror variableType, TreePath forStatement, List<TreePath> toReplace) {
    if (forStatement.getLeaf().getKind() != Kind.BLOCK) return null;

    BlockTree block = (BlockTree) forStatement.getLeaf();

    if (block.getStatements().isEmpty()) return null;

    StatementTree first = block.getStatements().get(0);

    if (first.getKind() != Kind.VARIABLE) return null;

    VariableTree var = (VariableTree) first;
    TypeMirror varType = ctx.getWorkingCopy().getTrees().getTypeMirror(new TreePath(forStatement, var.getType()));

    if (varType == null || !ctx.getWorkingCopy().getTypes().isSameType(variableType, varType)) return null;

    for (TreePath tp : toReplace) {
        if (tp.getLeaf() == var.getInitializer()) return var.getName().toString();
    }

    return null;
}
 
Example 19
Source File: IntroduceParameterPlugin.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static BlockTree findAddPosition(CompilationInfo info, TreePath original, Set<? extends TreePath> candidates) {
    //find least common block holding all the candidates:
    TreePath statement = original;

    for (TreePath p : candidates) {
        Tree leaf = p.getLeaf();
        int leafStart = (int) info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), leaf);
        int stPathStart = (int) info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), statement.getLeaf());

        if (leafStart < stPathStart) {
            statement = p;
        }
    }

    List<TreePath> allCandidates = new LinkedList<TreePath>();

    allCandidates.add(original);
    allCandidates.addAll(candidates);

    statement = JavaPluginUtils.findStatement(statement);

    if (statement == null) {
        //XXX: well....
        return null;
    }

    while (statement.getParentPath() != null && !JavaPluginUtils.isParentOf(statement.getParentPath(), allCandidates)) {
        statement = statement.getParentPath();
    }

    //#126269: the common parent may not be block:
    while (statement.getParentPath() != null && statement.getParentPath().getLeaf().getKind() != Kind.BLOCK) {
        statement = statement.getParentPath();
    }

    if (statement.getParentPath() == null) {
        return null;//XXX: log
    }
    BlockTree statements = (BlockTree) statement.getParentPath().getLeaf();
    StatementTree statementTree = (StatementTree) statement.getLeaf();

    int index = statements.getStatements().indexOf(statementTree);

    if (index == (-1)) {
        //really strange...
        return null;
    }
    return statements;
}
 
Example 20
Source File: ErrorDescriptionFactory.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("fallthrough")
private static int[] computeNameSpan(Tree tree, HintContext context) {
    switch (tree.getKind()) {
        case LABELED_STATEMENT:
            return context.getInfo().getTreeUtilities().findNameSpan((LabeledStatementTree) tree);
        case METHOD:
            return context.getInfo().getTreeUtilities().findNameSpan((MethodTree) tree);
        case ANNOTATION_TYPE:
        case CLASS:
        case ENUM:
        case INTERFACE:
            return context.getInfo().getTreeUtilities().findNameSpan((ClassTree) tree);
        case VARIABLE:
            return context.getInfo().getTreeUtilities().findNameSpan((VariableTree) tree);
        case MEMBER_SELECT:
            //XXX:
            MemberSelectTree mst = (MemberSelectTree) tree;
            int[] span = context.getInfo().getTreeUtilities().findNameSpan(mst);

            if (span == null) {
                int end = (int) context.getInfo().getTrees().getSourcePositions().getEndPosition(context.getInfo().getCompilationUnit(), tree);
                span = new int[] {end - mst.getIdentifier().length(), end};
            }
            return span;
        case METHOD_INVOCATION:
            return computeNameSpan(((MethodInvocationTree) tree).getMethodSelect(), context);
        case BLOCK:
            Collection<? extends TreePath> prefix = context.getMultiVariables().get("$$1$");
            
            if (prefix != null) {
                BlockTree bt = (BlockTree) tree;
                
                if (bt.getStatements().size() > prefix.size()) {
                    return computeNameSpan(bt.getStatements().get(prefix.size()), context);
                }
            }
        default:
            int start = (int) context.getInfo().getTrees().getSourcePositions().getStartPosition(context.getInfo().getCompilationUnit(), tree);
            if (    StatementTree.class.isAssignableFrom(tree.getKind().asInterface())
                && tree.getKind() != Kind.EXPRESSION_STATEMENT
                && tree.getKind() != Kind.BLOCK) {
                TokenSequence<?> ts = context.getInfo().getTokenHierarchy().tokenSequence();
                ts.move(start);
                if (ts.moveNext()) {
                    return new int[] {ts.offset(), ts.offset() + ts.token().length()};
                }
            }
            return new int[] {
                start,
                Math.min((int) context.getInfo().getTrees().getSourcePositions().getEndPosition(context.getInfo().getCompilationUnit(), tree),
                         findLineEnd(context.getInfo(), start)),
            };
    }
}