Java Code Examples for com.sun.source.tree.BlockTree

The following examples show how to use com.sun.source.tree.BlockTree. These examples are extracted from open source projects. 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
/**
 * Helper method for statements.
 */
private void visitStatement(
        StatementTree node,
        CollapseEmptyOrNot collapseEmptyOrNot,
        AllowLeadingBlankLine allowLeadingBlank,
        AllowTrailingBlankLine allowTrailingBlank) {
    sync(node);
    switch (node.getKind()) {
        case BLOCK:
            builder.space();
            visitBlock((BlockTree) node, collapseEmptyOrNot, allowLeadingBlank, allowTrailingBlank);
            break;
        default:
            builder.open(plusTwo);
            builder.breakOp(" ");
            scan(node, null);
            builder.close();
    }
}
 
Example 2
Source Project: netbeans   Source File: AssignResultToVariable.java    License: 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 3
Source Project: netbeans   Source File: CopyFinder.java    License: Apache License 2.0 6 votes vote down vote up
public static List<? extends StatementTree> getStatements(TreePath firstLeaf) {
    switch (firstLeaf.getParentPath().getLeaf().getKind()) {
        case BLOCK:
            return ((BlockTree) firstLeaf.getParentPath().getLeaf()).getStatements();
        case CASE:
            CaseTree caseTree = (CaseTree) firstLeaf.getParentPath().getLeaf();
            if (caseTree.getStatements() != null) {
                return caseTree.getStatements();
            } else if (TreeShims.getBody(caseTree) instanceof StatementTree) {
                return Collections.singletonList((StatementTree) TreeShims.getBody(caseTree));
            } else {
                return null;
            }
        default:
            return Collections.singletonList((StatementTree) firstLeaf.getLeaf());
    }
}
 
Example 4
Source Project: netbeans   Source File: EqualsHashCodeGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private static MethodTree createHashCodeMethod(WorkingCopy wc, Iterable<? extends VariableElement> hashCodeFields, Scope scope) {
    TreeMaker make = wc.getTreeMaker();
    Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC);        

    int startNumber = generatePrimeNumber(2, 10);
    int multiplyNumber = generatePrimeNumber(10, 100);
    List<StatementTree> statements = new ArrayList<>();
    //int hash = <startNumber>;
    statements.add(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "hash", make.PrimitiveType(TypeKind.INT), make.Literal(startNumber))); //NOI18N        
    for (VariableElement ve : hashCodeFields) {
        TypeMirror tm = ve.asType();
        ExpressionTree variableRead = prepareExpression(wc, HASH_CODE_PATTERNS, tm, ve, scope);
        statements.add(make.ExpressionStatement(make.Assignment(make.Identifier("hash"), make.Binary(Tree.Kind.PLUS, make.Binary(Tree.Kind.MULTIPLY, make.Literal(multiplyNumber), make.Identifier("hash")), variableRead)))); //NOI18N
    }
    statements.add(make.Return(make.Identifier("hash"))); //NOI18N        
    BlockTree body = make.Block(statements, false);
    ModifiersTree modifiers = prepareModifiers(wc, mods,make);
    
    return make.Method(modifiers, "hashCode", make.PrimitiveType(TypeKind.INT), Collections.<TypeParameterTree> emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), body, null); //NOI18N
}
 
Example 5
Source Project: netbeans   Source File: AssignResultToVariable.java    License: 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 6
Source Project: netbeans   Source File: DoubleCheck.java    License: Apache License 2.0 6 votes vote down vote up
private static TreePath findOuterIf(HintContext ctx, TreePath treePath) {
    while (!ctx.isCanceled()) {
        treePath = treePath.getParentPath();
        if (treePath == null) {
            break;
        }
        Tree leaf = treePath.getLeaf();
        
        if (leaf.getKind() == Kind.IF) {
            return treePath;
        }
        
        if (leaf.getKind() == Kind.BLOCK) {
            BlockTree b = (BlockTree)leaf;
            if (b.getStatements().size() == 1) {
                // ok, empty blocks can be around synchronized(this) 
                // statements
                continue;
            }
        }
        
        return null;
    }
    return null;
}
 
Example 7
Source Project: netbeans   Source File: ForLoopToFunctionalHint.java    License: 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 8
Source Project: NullAway   Source File: NullAway.java    License: MIT License 6 votes vote down vote up
static FieldInitEntities create(
    Symbol.ClassSymbol classSymbol,
    Set<Symbol> nonnullInstanceFields,
    Set<Symbol> nonnullStaticFields,
    List<BlockTree> instanceInitializerBlocks,
    List<BlockTree> staticInitializerBlocks,
    Set<MethodTree> constructors,
    Set<MethodTree> instanceInitializerMethods,
    Set<MethodTree> staticInitializerMethods) {
  return new AutoValue_NullAway_FieldInitEntities(
      classSymbol,
      ImmutableSet.copyOf(nonnullInstanceFields),
      ImmutableSet.copyOf(nonnullStaticFields),
      ImmutableList.copyOf(instanceInitializerBlocks),
      ImmutableList.copyOf(staticInitializerBlocks),
      ImmutableSet.copyOf(constructors),
      ImmutableSet.copyOf(instanceInitializerMethods),
      ImmutableSet.copyOf(staticInitializerMethods));
}
 
Example 9
Source Project: netbeans   Source File: JUnit5TestGenerator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 */
@Override
protected MethodTree composeNewTestMethod(String testMethodName,
                                          BlockTree testMethodBody,
                                          List<ExpressionTree> throwsList,
                                          WorkingCopy workingCopy) {
    TreeMaker maker = workingCopy.getTreeMaker();
    return maker.Method(
            createModifiersTree(ANN_TEST,
                                createModifierSet(PUBLIC),
                                workingCopy),
            testMethodName,
            maker.PrimitiveType(TypeKind.VOID),
            Collections.<TypeParameterTree>emptyList(),
            Collections.<VariableTree>emptyList(),
            throwsList,
            testMethodBody,
            null);          //default value - used by annotations
}
 
Example 10
Source Project: netbeans   Source File: AsyncConverter.java    License: Apache License 2.0 6 votes vote down vote up
private ClassTree moveRestMethod( TreeMaker maker, String movedName,
        MethodTree method, WorkingCopy copy, ClassTree classTree)
{
    List<? extends VariableTree> parameters = method.getParameters();
    Tree returnType = method.getReturnType();
    BlockTree body = method.getBody();  
    
    ModifiersTree modifiers = maker.Modifiers(EnumSet.of(Modifier.PRIVATE));
    MethodTree newMethod = maker.Method(modifiers, movedName, 
            returnType,
            Collections.<TypeParameterTree> emptyList(),
            parameters,
            Collections.<ExpressionTree> emptyList(),body,null);
    
    ClassTree newClass = maker.addClassMember(classTree, newMethod);
    newClass = maker.removeClassMember(newClass, method);
    return newClass;
}
 
Example 11
Source Project: google-java-format   Source File: JavaInputAstVisitor.java    License: Apache License 2.0 6 votes vote down vote up
/** Helper method for statements. */
private void visitStatement(
    StatementTree node,
    CollapseEmptyOrNot collapseEmptyOrNot,
    AllowLeadingBlankLine allowLeadingBlank,
    AllowTrailingBlankLine allowTrailingBlank) {
  sync(node);
  switch (node.getKind()) {
    case BLOCK:
      builder.space();
      visitBlock((BlockTree) node, collapseEmptyOrNot, allowLeadingBlank, allowTrailingBlank);
      break;
    default:
      builder.open(plusTwo);
      builder.breakOp(" ");
      scan(node, null);
      builder.close();
  }
}
 
Example 12
Source Project: NullAway   Source File: NullabilityUtil.java    License: MIT License 5 votes vote down vote up
/**
 * find the enclosing method, lambda expression or initializer block for the leaf of some tree
 * path
 *
 * @param path the tree path
 * @param others also stop and return in case of any of these tree kinds
 * @return the closest enclosing method / lambda
 */
@Nullable
public static TreePath findEnclosingMethodOrLambdaOrInitializer(
    TreePath path, ImmutableSet<Tree.Kind> others) {
  TreePath curPath = path.getParentPath();
  while (curPath != null) {
    if (curPath.getLeaf() instanceof MethodTree
        || curPath.getLeaf() instanceof LambdaExpressionTree
        || others.contains(curPath.getLeaf().getKind())) {
      return curPath;
    }
    TreePath parent = curPath.getParentPath();
    if (parent != null && parent.getLeaf() instanceof ClassTree) {
      if (curPath.getLeaf() instanceof BlockTree) {
        // found initializer block
        return curPath;
      }
      if (curPath.getLeaf() instanceof VariableTree
          && ((VariableTree) curPath.getLeaf()).getInitializer() != null) {
        // found field with an inline initializer
        return curPath;
      }
    }
    curPath = parent;
  }
  return null;
}
 
Example 13
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));
    }
}
 
Example 14
Source Project: netbeans   Source File: InitializerCanBeStatic.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    Tree t = ctx.getPath().getLeaf();
    if (t.getKind() != Tree.Kind.BLOCK) {
        return;
    }
    BlockTree bl = (BlockTree)t;
    WorkingCopy wc = ctx.getWorkingCopy();
    GeneratorUtilities gu = GeneratorUtilities.get(wc);
    gu.importComments(bl, wc.getCompilationUnit());
    TreeMaker mk = wc.getTreeMaker();
    BlockTree nbl = mk.Block(bl.getStatements(), true);
    gu.copyComments(bl, nbl, true);
    gu.copyComments(bl, nbl, false);
    wc.rewrite(bl, nbl);
}
 
Example 15
Source Project: netbeans   Source File: AbstractTestGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generates a simple implementation of an abstract method declared
 * in a supertype.
 *
 * @param abstractMethod  the method whose implementation is to be generated
 */
private static MethodTree generateAbstractMethodImpl(
                                        ExecutableElement abstractMethod,
                                        WorkingCopy workingCopy) {
    final TreeMaker maker = workingCopy.getTreeMaker();

    TypeMirror returnType = abstractMethod.getReturnType();
    List<? extends StatementTree> content;
    if (returnType.getKind() == TypeKind.VOID) {
        content = Collections.<StatementTree>emptyList();
    } else {
        content = Collections.singletonList(
                        maker.Return(getDefaultValue(maker, returnType)));
    }
    BlockTree body = maker.Block(content, false);

    return maker.Method(
            maker.Modifiers(Collections.singleton(PUBLIC)),
            abstractMethod.getSimpleName(),
            maker.Type(returnType),
            makeTypeParamsCopy(abstractMethod.getTypeParameters(), maker),
            makeParamsCopy(abstractMethod.getParameters(), maker),
            makeDeclaredTypesCopy((List<? extends DeclaredType>)
                                          abstractMethod.getThrownTypes(),
                                  maker),
            body,
            null);
}
 
Example 16
Source Project: netbeans   Source File: ConvertToARM.java    License: Apache License 2.0 5 votes vote down vote up
private static BlockTree rewriteFinallyBlock(
        final TreeMaker tm,
        final Collection<? extends TreePath> paths) {
    if (paths == null || paths.isEmpty()) {
        return null;
    }
    final List<StatementTree> statements = new ArrayList<StatementTree>(paths.size());
    for (TreePath stp : paths) {
        statements.add((StatementTree)stp.getLeaf());
    }
    final BlockTree result = tm.Block(statements, false);
    return result;
}
 
Example 17
Source Project: netbeans   Source File: FinalizeDoesNotCallSuper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    final TreeMaker tm = wc.getTreeMaker();
    TreePath tp = ctx.getPath();
    final BlockTree oldBody = ((MethodTree)tp.getLeaf()).getBody();
    if (oldBody == null) {
        return;
    }
    final List<StatementTree> newStatements = new ArrayList<StatementTree>(2);
    BlockTree superFinalize = tm.Block(
                                Collections.singletonList(
                                    tm.ExpressionStatement(
                                        tm.MethodInvocation(Collections.<ExpressionTree>emptyList(),
                                            tm.MemberSelect(
                                                tm.Identifier(SUPER),
                                                FINALIZE), Collections.<ExpressionTree>emptyList()))),
                                false);
    if (oldBody.getStatements().isEmpty()) {
        wc.rewrite(oldBody, superFinalize);
    } else {
        TryTree soleTry = soleTryWithoutFinally(oldBody);
        
        if (soleTry != null) {
            wc.rewrite(soleTry, tm.Try(soleTry.getBlock(), soleTry.getCatches(), superFinalize));
        } else {
            wc.rewrite(oldBody, tm.Block(Collections.singletonList(tm.Try(oldBody, Collections.<CatchTree>emptyList(), superFinalize)), false));
        }
    }
}
 
Example 18
Source Project: netbeans   Source File: VeryPretty.java    License: Apache License 2.0 5 votes vote down vote up
private java.util.List<? extends StatementTree> getStatements(Tree tree) {
    switch (tree.getKind()) {
        case BLOCK: return ((BlockTree) tree).getStatements();
        case CASE: return ((CaseTree) tree).getStatements();
        default: return null;
    }
}
 
Example 19
Source Project: netbeans   Source File: FinalizeDoesNotCallSuper.java    License: Apache License 2.0 5 votes vote down vote up
private TryTree soleTryWithoutFinally(BlockTree block) {
    if (block.getStatements().size() != 1) return null;
    StatementTree first = block.getStatements().get(0);
    if (first.getKind() != Kind.TRY) return null;
    TryTree tt = (TryTree) first;
    if (tt.getFinallyBlock() != null) return null;
    return tt;
}
 
Example 20
Source Project: openjdk-8   Source File: JavacParserTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
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));
    }
}
 
Example 21
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 22
Source Project: netbeans   Source File: VanillaPartialReparser.java    License: Apache License 2.0 5 votes vote down vote up
public BlockTree reflowMethodBody(Context context, CompilationUnitTree topLevel, ClassTree ownerClass, MethodTree methodToReparse) {
    Flow flow = Flow.instance(context);
    TreeMaker make = TreeMaker.instance(context);
    Enter enter = Enter.instance(context);
    flow.analyzeTree(enter.getEnv(((JCTree.JCClassDecl) ownerClass).sym), make);
    return methodToReparse.getBody();
}
 
Example 23
Source Project: netbeans   Source File: GeneratorUtilities.java    License: Apache License 2.0 5 votes vote down vote up
private static void doMoveComments(WorkingCopy wc, Tree from,  Tree to, int offset, List<Comment> comments, int fromIdx, int toIdx) {
    if (comments.isEmpty()) {
        return;
    }
    TreeMaker tm = wc.getTreeMaker();
    Tree tree = from;
    switch (from.getKind()) {
        case METHOD:
            tree = tm.setLabel(from, ((MethodTree)from).getName());
            break;
        case VARIABLE:
            tree = tm.setLabel(from, ((VariableTree)from).getName());
            break;
        case BLOCK:
            tree = tm.Block(((BlockTree)from).getStatements(), ((BlockTree)from).isStatic());
            GeneratorUtilities gu = GeneratorUtilities.get(wc);
            gu.copyComments(from, tree, true);
            gu.copyComments(from, tree, false);
            break;
    }
    boolean before = (int)wc.getTrees().getSourcePositions().getStartPosition(wc.getCompilationUnit(), from) >= offset;
    if (fromIdx >=0 && toIdx >= 0 && toIdx - fromIdx > 0) {
        for (int i = toIdx - 1; i >= fromIdx; i--) {
            tm.removeComment(tree, i, before);
        }
    }
    wc.rewrite(from, tree);
    for (Comment comment : comments) {
        tm.addComment(to, comment, comment.pos() <= offset);
    }
}
 
Example 24
Source Project: netbeans   Source File: PreconditionsChecker.java    License: Apache License 2.0 5 votes vote down vote up
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;


}
 
Example 25
Source Project: netbeans   Source File: GeneratorUtilities.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tags first method in the list, in order to select it later inside editor
 * @param methods list of methods to be implemented/overridden
 */
private void tagFirst(List<MethodTree> methods) {
    //tag first method body, if any
    if (methods.size() > 0) {
        BlockTree body = methods.get(0).getBody();
        if (body != null && !body.getStatements().isEmpty()) {
            copy.tag(body.getStatements().get(0), "methodBodyTag"); // NOI18N
        }
    }
}
 
Example 26
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));
    }
}
 
Example 27
@Override
public Tree visitBlock(BlockTree blockTree, Trees trees) {
    TreePath path = getCurrentPath();
    if (path.getParentPath().getLeaf() == lambdaMethodTree && blockTree.getStatements().size() == 1) {
        singleStatementLambdaMethodBody = blockTree;
    }
    return super.visitBlock(blockTree, trees);
}
 
Example 28
Source Project: hottub   Source File: JavacParserTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
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));
    }
}
 
Example 29
Source Project: netbeans   Source File: MethodTest2.java    License: Apache License 2.0 5 votes vote down vote up
public MethodTree makeMethod() {
    Set<Modifier> emptyModifs = Collections.emptySet();
    List<TypeParameterTree> emptyTpt= Collections.emptyList();
    List<VariableTree> emptyVt = Collections.emptyList();
    List<ExpressionTree> emptyEt = Collections.emptyList();
    return make.Method(
              make.Modifiers(emptyModifs),
              (CharSequence)"",
              (ExpressionTree) null,
              emptyTpt,
              emptyVt,
              emptyEt,
              (BlockTree) null,
              (ExpressionTree)null);                    
}
 
Example 30
Source Project: netbeans   Source File: ToStringGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private static MethodTree createToStringMethod(WorkingCopy wc, Iterable<? extends VariableElement> fields, String typeName, boolean useStringBuilder) {
    TreeMaker make = wc.getTreeMaker();
    Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC);
    List<AnnotationTree> annotations = new LinkedList<>();
    if (GeneratorUtils.supportsOverride(wc)) {
        TypeElement override = wc.getElements().getTypeElement("java.lang.Override"); //NOI18N
        if (override != null) {
            annotations.add(wc.getTreeMaker().Annotation(wc.getTreeMaker().QualIdent(override), Collections.<ExpressionTree>emptyList()));
        }
    }
    ModifiersTree modifiers = make.Modifiers(mods, annotations);
    BlockTree body = createToStringMethodBody(make, typeName, fields, useStringBuilder);
    return make.Method(modifiers, "toString", make.Identifier("String"), Collections.<TypeParameterTree>emptyList(), Collections.<VariableTree>emptyList(), Collections.<ExpressionTree>emptyList(), body, null); //NOI18N
}