Java 类com.sun.source.tree.StatementTree 实例源码

项目:incubator-netbeans    文件:AssignResultToVariable.java   
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;
}
项目:openjdk-jdk10    文件:TreeDissector.java   
StatementTree firstStatement() {
    if (targetClass != null) {
        for (Tree mem : targetClass.getMembers()) {
            if (mem.getKind() == Tree.Kind.METHOD) {
                MethodTree mt = (MethodTree) mem;
                if (isDoIt(mt.getName())) {
                    List<? extends StatementTree> stmts = mt.getBody().getStatements();
                    if (!stmts.isEmpty()) {
                        return stmts.get(0);
                    }
                }
            }
        }
    }
    return null;
}
项目:incubator-netbeans    文件:EqualsHashCodeGenerator.java   
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
}
项目:javaide    文件:JavaInputAstVisitor.java   
private void visitStatements(List<? extends StatementTree> statements) {
    boolean first = true;
    PeekingIterator<StatementTree> it =
            Iterators.<StatementTree>peekingIterator(statements.iterator());
    dropEmptyDeclarations();
    while (it.hasNext()) {
        StatementTree tree = it.next();
        builder.forcedBreak();
        if (!first) {
            builder.blankLineWanted(BlankLineWanted.PRESERVE);
        }
        markForPartialFormat();
        first = false;
        List<VariableTree> fragments = variableFragments(it, tree);
        if (!fragments.isEmpty()) {
            visitVariables(
                    fragments,
                    DeclarationKind.NONE,
                    canLocalHaveHorizontalAnnotations(fragments.get(0).getModifiers()));
        } else {
            scan(tree, null);
        }
    }
}
项目:incubator-netbeans    文件:NCLOCVisitor.java   
@Override
public Object visitVariable(VariableTree node, Object p) {
    TreePath path = getCurrentPath();
    Tree parent = path.getParentPath().getLeaf();
    if (parent instanceof StatementTree) {
        boolean count = true;
        if (parent instanceof ForLoopTree) {
            count = !((ForLoopTree)parent).getInitializer().contains(node);
        } else if (parent instanceof EnhancedForLoopTree) {
            count = ((EnhancedForLoopTree)parent).getVariable() != node;
        }
        if (count) {
            statements++;
        }
    }
    return super.visitVariable(node, p);
}
项目:incubator-netbeans    文件:AddJavaFXPropertyMaker.java   
private MethodTree createSetter(ModifiersTree mods, TypeMirror valueType) {
    StringBuilder getterName = GeneratorUtils.getCapitalizedName(config.getName());
    getterName.insert(0, "set");
    Tree valueTree;
    if (valueType.getKind() == TypeKind.DECLARED) {
        valueTree = make.QualIdent(((DeclaredType) valueType).asElement());
    } else if (valueType.getKind().isPrimitive()) {
        valueTree = make.PrimitiveType(valueType.getKind());
    } else {
        valueTree = make.Identifier(valueType.toString());
    }
    StatementTree statement = make.ExpressionStatement(make.MethodInvocation(Collections.EMPTY_LIST, make.MemberSelect(make.Identifier(config.getName()), hasGet ? "set" : "setValue"), Collections.singletonList(make.Identifier("value"))));
    BlockTree getterBody = make.Block(Collections.singletonList(statement), false);
    VariableTree var = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "value", valueTree, null);
    MethodTree getter = make.Method(mods, getterName, make.PrimitiveType(TypeKind.VOID), Collections.EMPTY_LIST, Collections.singletonList(var), Collections.EMPTY_LIST, getterBody, null);
    return getter;
}
项目:incubator-netbeans    文件:ForLoopToFunctionalHint.java   
@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;
}
项目:java-code-templates    文件:Util.java   
/**
 * Helper method to determine if the given {@link ExecutableElement} refers
 * to a default constructor.
 * 
 * @param element
 * @param trees
 * @return
 */
static boolean isDefaultConstructor(final ExecutableElement element, final Trees trees) {
    // Front-load the cheapest checks to fail quickly

    // Default constructor: no parameters and one statement consisting only of "super();"
    if (element.getKind() != ElementKind.CONSTRUCTOR) {
        return false;
    }

    if (!element.getParameters().isEmpty()) {
        return false;
    }

    final List<? extends StatementTree> statements = trees.getTree(element).getBody().getStatements();
    if (statements.size() != 1) {
        return false;
    }

    return DEFAULT_CTOR_METHOD_BODY_PATTERN.matcher(statements.get(0).toString()).matches();
}
项目:incubator-netbeans    文件:PreconditionsChecker.java   
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());
    }


}
项目:incubator-netbeans    文件:CreateMethodFix.java   
private static BlockTree createDefaultMethodBody(WorkingCopy wc, TreePath targetTree, TypeMirror returnType, String name) {
    TreeUtilities tu = wc.getTreeUtilities();
    TypeElement targetClazz = (TypeElement)wc.getTrees().getElement(targetTree);
    StatementTree st = tu.parseStatement("{class ${abstract " + (returnType != null ? returnType.toString() : "void") + " " + ("<init>".equals(name) ? targetClazz.getSimpleName() : name) + "();}}", new SourcePositions[1]); //NOI18N
    Trees trees = wc.getTrees();
    List<? extends Tree> members = ((ClassTree) targetTree.getLeaf()).getMembers();
    Scope scope = members.isEmpty() ? trees.getScope(targetTree) : trees.getScope(new TreePath(targetTree, members.get(0)));
    tu.attributeTree(st, scope);
    Tree first = null;
    for(Tree t : ((ClassTree)((BlockTree)st).getStatements().get(0)).getMembers()) {
        if (t.getKind() == Tree.Kind.METHOD && !"<init>".contentEquals(((MethodTree)t).getName())) { //NOI19N
            first = t;
            break;
        }
    }
    ExecutableElement ee = (ExecutableElement) wc.getTrees().getElement(new TreePath(targetTree, first));
    return GeneratorUtilities.get(wc).createAbstractMethodImplementation(targetClazz, ee).getBody();
}
项目:incubator-netbeans    文件:Ifs.java   
@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);
}
项目:javaide    文件:JavaInputAstVisitor.java   
/**
 * 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();
    }
}
项目:incubator-netbeans    文件:Utilities.java   
private static List<? extends StatementTree> getRealStatements(CompilationInfo info, TreePath path) {
    assert path.getLeaf().getKind() == Tree.Kind.BLOCK;
    BlockTree bt = (BlockTree)path.getLeaf();
    List<? extends StatementTree> stats = bt.getStatements();
    if (stats.isEmpty()) {
        return stats;
    }
    List<StatementTree> newStats = null;
    for (int i = 0; i < stats.size(); i++) {
        StatementTree t = stats.get(i);
        TreePath stPath = new TreePath(path, t);
        if (info.getTreeUtilities().isSynthetic(stPath)) {
            newStats = new ArrayList<>(stats.size());
        } else {
            newStats = new ArrayList<>(stats.size());
            newStats.addAll(stats.subList(i, stats.size()));
            break;
        }
    }
    return newStats == null ? stats : newStats;
}
项目:incubator-netbeans    文件:EvaluatorVisitor.java   
@Override
public Mirror visitBlock(BlockTree arg0, EvaluationContext evaluationContext) {
    Mirror lastResult = null;
    try {
        evaluationContext.pushBlock();
        for (StatementTree statementTree : arg0.getStatements()) {
            Mirror res = statementTree.accept(this, evaluationContext);
            if (res != null) {
                lastResult = res;
            }
            if (res instanceof CommandMirror) {
                break;
            }
        }
    } finally {
        evaluationContext.popBlock();
    }
    return lastResult;
}
项目:incubator-netbeans    文件:Flow.java   
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;
}
项目:incubator-netbeans    文件:MagicSurroundWithTryCatchFix.java   
private static StatementTree createRethrowAsRuntimeExceptionStatement(WorkingCopy info, TreeMaker make, String name) {
    if (!ErrorFixesFakeHint.isRethrowAsRuntimeException(ErrorFixesFakeHint.getPreferences(info.getFileObject(), FixKind.SURROUND_WITH_TRY_CATCH))) {
        return null;
    }

    TypeElement runtimeException = info.getElements().getTypeElement("java.lang.RuntimeException");

    if (runtimeException == null) {
        return null;
    }

    ExpressionTree exceptionName = make.QualIdent(runtimeException);
    StatementTree result = make.Throw(make.NewClass(null, Collections.<ExpressionTree>emptyList(), exceptionName, Arrays.asList(make.Identifier(name)), null));

    info.tag(exceptionName, Utilities.TAG_SELECT);

    return result;
}
项目:incubator-netbeans    文件:IntroduceMethodFix.java   
private void generateMethodContents(List<StatementTree> methodStatements) {
    Iterator<TypeMirrorHandle> additionalType = additionalLocalTypes.iterator();
    Iterator<String> additionalName = additionalLocalNames.iterator();
    while (additionalType.hasNext() && additionalName.hasNext()) {
        TypeMirror tm = additionalType.next().resolve(copy);
        if (tm == null) {
            //XXX:
            return;
        }
        Tree type = make.Type(tm);
        methodStatements.add(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), additionalName.next(), type, null));
    }
    if (from == to && statements.get(from).getKind() == Tree.Kind.BLOCK) {
        methodStatements.addAll(((BlockTree) statements.get(from)).getStatements());
    } else {
        methodStatements.addAll(statements.subList(from, to + 1));
    }
}
项目:incubator-netbeans    文件:IntroduceMethodFix.java   
/**
 * Replaces former exit points by returns and/or adds a return with value at the end of the method
 */
private void makeReturnsFromExtractedMethod(List<StatementTree> methodStatements) {
    if (returnSingleValue) {
        return;
    }
    if (resolvedExits != null) {
        for (TreePath resolved : resolvedExits) {
            ReturnTree r = makeExtractedReturn(true);
            GeneratorUtilities.get(copy).copyComments(resolved.getLeaf(), r, false);
            GeneratorUtilities.get(copy).copyComments(resolved.getLeaf(), r, true);
            copy.rewrite(resolved.getLeaf(), r);
        }
        // the default exit path, should return false
        if (outcomeVariable == null && !exitsFromAllBranches) {
            methodStatements.add(make.Return(make.Literal(false)));
        }
    } else {
        ReturnTree ret = makeExtractedReturn(false);
        if (ret != null) {
            methodStatements.add(ret);
        }
    }
}
项目:incubator-netbeans    文件:AssignResultToVariable.java   
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;
}
项目:incubator-netbeans    文件:TreeUtils.java   
static TreePath findBlockOrStatement(TreePath statementPath, boolean statement) {
    CYCLE: while (statementPath != null) {
        Tree leaf = statementPath.getLeaf();
        if (statement && StatementTree.class.isAssignableFrom(leaf.getKind().asInterface())) {
            break;
        }
        if (statementPath.getParentPath() != null) {
            switch (statementPath.getParentPath().getLeaf().getKind()) {
                case BLOCK:
                case CASE:
                case LAMBDA_EXPRESSION:
                    break CYCLE;
            }
        }
        if (TreeUtilities.CLASS_TREE_KINDS.contains(statementPath.getLeaf().getKind())) {
            return null;
        }
        statementPath = statementPath.getParentPath();
    }
    return statementPath;
}
项目:incubator-netbeans    文件:RemoveSurroundingCodeAction.java   
private int[] getBounds(TreeUtilities tu, SourcePositions sp, CompilationUnitTree cut, Tree tree) {
    int[] bounds = {-1, -1};
    if (tree != null) {
        if (tree.getKind() == Tree.Kind.BLOCK) {
            List<? extends StatementTree> stats = ((BlockTree) tree).getStatements();
            if (stats != null && !stats.isEmpty()) {
                bounds[0] = getStart(tu, sp, cut, stats.get(0));
                bounds[1] = getEnd(tu, sp, cut, stats.get(stats.size() - 1));
            }
        } else {
            bounds[0] = getStart(tu, sp, cut, tree);
            bounds[1] = getEnd(tu, sp, cut, tree);
        }
    }
    return bounds;
}
项目:incubator-netbeans    文件:AbstractTestGenerator.java   
/**
 * 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);
}
项目:incubator-netbeans    文件:AbstractTestGenerator.java   
protected BlockTree generateStubTestMethodBody(WorkingCopy workingCopy) {
    TreeMaker maker = workingCopy.getTreeMaker();
    List<StatementTree> statements = new ArrayList<StatementTree>(8);


    if (setup.isGenerateDefMethodBody()) {
        ExpressionStatementTree exprStatementTree =
                                         generateDefMethodBody(maker);
        statements.add(exprStatementTree);
    }

    return maker.Block(statements, false);
}
项目:incubator-netbeans    文件:TestGenerator.java   
/**
 * Generates a set-up or a tear-down method.
 * The generated method will have no arguments, void return type
 * and a declaration that it may throw {@code java.lang.Exception}.
 * The method will have a declared protected member access.
 * The method contains call of the corresponding super method, i.e.
 * {@code super.setUp()} or {@code super.tearDown()}.
 *
 * @param  methodName  name of the method to be created
 * @return  created method
 */
private MethodTree generateInitMethod(String methodName,
                                      String annotationClassName,
                                      boolean isStatic,
                                      WorkingCopy workingCopy) {
    Set<Modifier> methodModifiers
            = isStatic ? createModifierSet(PUBLIC, STATIC)
                       : Collections.<Modifier>singleton(PUBLIC);
    ModifiersTree modifiers = createModifiersTree(annotationClassName,
                                                  methodModifiers,
                                                  workingCopy);
    TreeMaker maker = workingCopy.getTreeMaker();
    BlockTree methodBody = maker.Block(
            Collections.<StatementTree>emptyList(),
            false);
    MethodTree method = maker.Method(
            modifiers,              // modifiers
            methodName,             // name
            maker.PrimitiveType(TypeKind.VOID),         // return type
            Collections.<TypeParameterTree>emptyList(), // type params
            Collections.<VariableTree>emptyList(),      // parameters
            Collections.<ExpressionTree>singletonList(
                    maker.Identifier("Exception")),     // throws...//NOI18N
            methodBody,
            null);                                      // default value
    return method;
}
项目:NullAway    文件:NullAway.java   
private boolean isThisCall(StatementTree statementTree, VisitorState state) {
  if (statementTree.getKind().equals(EXPRESSION_STATEMENT)) {
    ExpressionTree expression = ((ExpressionStatementTree) statementTree).getExpression();
    return Matchers.methodInvocation(THIS_MATCHER).matches(expression, state);
  }
  return false;
}
项目:incubator-netbeans    文件:CopyFinder.java   
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;
}
项目:incubator-netbeans    文件:CopyFinder.java   
public static List<? extends StatementTree> getStatements(TreePath firstLeaf) {
    switch (firstLeaf.getParentPath().getLeaf().getKind()) {
        case BLOCK:
            return ((BlockTree) firstLeaf.getParentPath().getLeaf()).getStatements();
        case CASE:
            return ((CaseTree) firstLeaf.getParentPath().getLeaf()).getStatements();
        default:
            return Collections.singletonList((StatementTree) firstLeaf.getLeaf());
    }
}
项目:incubator-netbeans    文件:MethodModelSupportTest.java   
public void testCreateMethodTree() throws Exception {
    final MethodModel methodModel = MethodModel.create(
            "method",
            "void",
            "{ String name; }", // for now, Retouche requires those parenthesis (they won't appear in file)
            Collections.<MethodModel.Variable>emptyList(),
            Collections.<String>emptyList(),
            Collections.<Modifier>emptySet()
            );
    TestUtilities.copyStringToFileObject(testFO,
            "package foo;" +
            "public class TestClass {" +
            "}");
    runModificationTask(testFO, new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            MethodTree methodTree = MethodModelSupport.createMethodTree(workingCopy, methodModel);
            assertEquals(0, methodTree.getModifiers().getFlags().size());
            PrimitiveTypeTree returnTypeTree = (PrimitiveTypeTree) methodTree.getReturnType();
            assertTrue(TypeKind.VOID == returnTypeTree.getPrimitiveTypeKind());
            assertTrue(methodTree.getName().contentEquals("method"));
            assertEquals(0, methodTree.getParameters().size());
            assertEquals(0, methodTree.getThrows().size());
            List<? extends StatementTree> statements = methodTree.getBody().getStatements();
            assertEquals(1, statements.size());
        }
    });
}
项目:NullAway    文件:NullAway.java   
/**
 * @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);
    }
  }
  return result;
}
项目:incubator-netbeans    文件:IfTest.java   
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);
}
项目:incubator-netbeans    文件:AddParameterOrLocalFix.java   
private void resolveLocalVariable55(final WorkingCopy wc, TreePath tp, TreeMaker make, TypeMirror proposedType) {
    final String name = ((IdentifierTree) tp.getLeaf()).getName().toString();
    TreePath blockPath = findOutmostBlock(tp);

    if (blockPath == null) {
        return;
    }

    int index = 0;
    BlockTree block = ((BlockTree) blockPath.getLeaf());

    TreePath method = findMethod(tp);

    if (method != null && ((MethodTree) method.getLeaf()).getReturnType() == null && !block.getStatements().isEmpty()) {
        StatementTree stat = block.getStatements().get(0);

        if (stat.getKind() == Kind.EXPRESSION_STATEMENT) {
            Element thisMethodEl = wc.getTrees().getElement(method);
            TreePath pathToFirst = new TreePath(new TreePath(new TreePath(method, block), stat), ((ExpressionStatementTree) stat).getExpression());
            Element superCall = wc.getTrees().getElement(pathToFirst);

            if (thisMethodEl != null && superCall != null && thisMethodEl.getKind() == ElementKind.CONSTRUCTOR && superCall.getKind() == ElementKind.CONSTRUCTOR) {
                index = 1;
            }
        }
    }

    VariableTree vt = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), name, make.Type(proposedType), null);

    wc.rewrite(block, wc.getTreeMaker().insertBlockStatement(block, index, vt));
}
项目:incubator-netbeans    文件:SwitchTest.java   
public void test158129() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    String test = "public class Test { void m(int p) { switch (p) { ca|se 0: } } }";
    // XXX whitespace "public class Test { void m(int p) { switch (p) { case 0: break; } } }"
    String golden = "public class Test { void m(int p) { switch (p) { case 0:break;\n } } }";
    final int index = test.indexOf("|");
    assertTrue(index != -1);
    TestUtilities.copyStringToFile(testFile, test.replace("|", ""));
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy copy) throws IOException {
            if (copy.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) < 0) {
                return;
            }
            TreeMaker make = copy.getTreeMaker();
            TreePath node = copy.getTreeUtilities().pathFor(index);
            assertTrue(node.getLeaf().getKind() == Kind.CASE);
            CaseTree original = (CaseTree) node.getLeaf();
            List<StatementTree> st = new ArrayList<StatementTree>();
            st.addAll(original.getStatements());
            st.add(make.Break(null));
            CaseTree modified = make.Case(original.getExpression(), st);
            copy.rewrite(original, modified);
        }
    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
项目:openjdk-jdk10    文件:JavacParserTest.java   
@Test
void testErrorRecoveryForEnhancedForLoop142381() throws IOException {

    String code = "package test; class Test { " +
            "private void method() { " +
            "java.util.Set<String> s = null; for (a : s) {} } }";

    final List<Diagnostic<? extends JavaFileObject>> errors =
            new LinkedList<Diagnostic<? extends JavaFileObject>>();

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm,
            new DiagnosticListener<JavaFileObject>() {
        public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
            errors.add(diagnostic);
        }
    }, null, null, Arrays.asList(new MyFileObject(code)));

    CompilationUnitTree cut = ct.parse().iterator().next();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    StatementTree forStatement =
            ((MethodTree) clazz.getMembers().get(0)).getBody().getStatements().get(1);

    assertEquals("testErrorRecoveryForEnhancedForLoop142381",
            Kind.ENHANCED_FOR_LOOP, forStatement.getKind());
    assertFalse("testErrorRecoveryForEnhancedForLoop142381", errors.isEmpty());
}
项目:incubator-netbeans    文件:GeneratorUtilitiesTest.java   
public void testCommentsCopyingNull() throws Exception {//#165241
    performTest("package test;\npublic abstract class Test {\npublic abstract void test();\n }\n", new Task<WorkingCopy>() {
        @Override public void run(WorkingCopy parameter) throws Exception {
            parameter.toPhase(Phase.RESOLVED);
            ClassTree clazz = (ClassTree) parameter.getCompilationUnit().getTypeDecls().get(0);
            MethodTree mt = (MethodTree) clazz.getMembers().get(1);
            BlockTree nue = parameter.getTreeMaker().Block(Collections.<StatementTree>emptyList(), false);
            GeneratorUtilities.get(parameter).copyComments(mt.getBody(), nue, true);
        }
    }, new Validator() {
        public void validate(CompilationInfo info) {}
    });
}
项目:openjdk-jdk10    文件:CompletenessStressTest.java   
private boolean testBranch(StringWriter writer, SourcePositions sp, String text, CompilationUnitTree cut, StatementTree statementTree) {
    if (statementTree instanceof BlockTree) {
        return testBlock(writer, sp, text, cut, (BlockTree) statementTree);
    } else if (isLegal(statementTree)) {
        return testStatement(writer, sp, text, cut, statementTree);
    }
    return true;
}
项目:incubator-netbeans    文件:JUnit3TestGenerator.java   
/**
 * Generates a set-up or a tear-down method.
 * The generated method will have no arguments, void return type
 * and a declaration that it may throw {@code java.lang.Exception}.
 * The method will have a declared protected member access.
 * The method contains call of the corresponding super method, i.e.
 * {@code super.setUp()} or {@code super.tearDown()}.
 *
 * @param  methodName  name of the method to be created
 * @return  created method
 * @see  http://junit.sourceforge.net/javadoc/junit/framework/TestCase.html
 *       methods {@code setUp()} and {@code tearDown()}
 */
protected MethodTree generateInitMethod(String methodName,
                                        TreeMaker maker,
                                        WorkingCopy workingCopy) {
    Set<Modifier> modifiers = Collections.<Modifier>singleton(PROTECTED);
    ModifiersTree modifiersTree
            = useAnnotations
              ? createModifiersTree(OVERRIDE, modifiers, workingCopy)
              : maker.Modifiers(modifiers);
    ExpressionTree superMethodCall = maker.MethodInvocation(
            Collections.<ExpressionTree>emptyList(),    // type params.
            maker.MemberSelect(
                    maker.Identifier("super"), methodName),         //NOI18N
            Collections.<ExpressionTree>emptyList());
    BlockTree methodBody = maker.Block(
            Collections.<StatementTree>singletonList(
                    maker.ExpressionStatement(superMethodCall)),
            false);
    MethodTree method = maker.Method(
            modifiersTree,          // modifiers
            methodName,             // name
            maker.PrimitiveType(TypeKind.VOID),         // return type
            Collections.<TypeParameterTree>emptyList(), // type params
            Collections.<VariableTree>emptyList(),      // parameters
            Collections.<ExpressionTree>singletonList(
                    maker.Identifier("Exception")),     // throws...//NOI18N
            methodBody,
            null);                                      // default value
    return method;
}
项目:incubator-netbeans    文件:AbstractTestGenerator.java   
/**
 * 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);
}
项目:incubator-netbeans    文件:AbstractTestGenerator.java   
protected BlockTree generateStubTestMethodBody(WorkingCopy workingCopy) {
    TreeMaker maker = workingCopy.getTreeMaker();
    List<StatementTree> statements = new ArrayList<StatementTree>(8);


    if (setup.isGenerateDefMethodBody()) {
        ExpressionStatementTree exprStatementTree =
                                         generateDefMethodBody(maker);
        statements.add(exprStatementTree);
    }

    return maker.Block(statements, false);
}
项目:incubator-netbeans    文件:AbstractTestGenerator.java   
/**
 */
private StatementTree generateSystemOutPrintln(TreeMaker maker,
                                               String arg) {
    MethodInvocationTree methodInvocation = maker.MethodInvocation(
            Collections.<ExpressionTree>emptyList(),        //type args
            maker.MemberSelect(
                    maker.MemberSelect(
                            maker.Identifier("System"), "out"), "println"),//NOI18N
            Collections.<LiteralTree>singletonList(
                    maker.Literal(arg)));                   //args.
    return maker.ExpressionStatement(methodInvocation);
}
项目:incubator-netbeans    文件:AbstractTestGenerator.java   
private StatementTree generateEJBCleanUpCode(TreeMaker maker) {
    IdentifierTree container = maker.Identifier(CONTAINER_VAR_NAME);
    MethodInvocationTree invocation = maker.MethodInvocation(
        Collections.<ExpressionTree>emptyList(),
        maker.MemberSelect(container, "close"), // NOI18N
        Collections.<ExpressionTree>emptyList()
    );
    return maker.ExpressionStatement(invocation);
}