com.sun.source.tree.StatementTree Java Examples

The following examples show how to use com.sun.source.tree.StatementTree. 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: CodeSnippetCompilerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testInferResultType() throws Exception {
    String code = "package test;\n class A { public void test(java.util.List<String> l) { } }";
    String watch = "l.stream().map(s -> s.length()).collect(java.util.stream.Collectors.toList());";
    int pos = code.indexOf("{", code.indexOf("{") + 1);
    FileObject java = createFile(root, "test/A.java", code);    //NOI18N
    JavaSource.forFileObject(java).runUserActionTask((CompilationController cc) -> {
        cc.toPhase(Phase.RESOLVED);
        TreePath posPath = cc.getTreeUtilities().pathFor(pos);
        StatementTree tree = cc.getTreeUtilities().parseStatement(
            watch,
            new SourcePositions[1]
        );
        cc.getTreeUtilities().attributeTree(tree, cc.getTrees().getScope(posPath));
        TreePath tp = new TreePath(posPath, tree);
        ClassToInvoke cti = CodeSnippetCompiler.compileToClass(cc, watch, 0, cc.getJavaSource(), java, -1, tp, tree, false);

        ClassFile cf = ClassFile.read(new ByteArrayInputStream(cti.bytecode));

        for (Method m : cf.methods) {
            if (cf.constant_pool.getUTF8Value(m.name_index).equals("invoke")) {
                assertEquals("(Ljava/util/List;)Ljava/util/List;", cf.constant_pool.getUTF8Value(m.descriptor.index));
            }
        }
    }, true);

}
 
Example #2
Source File: AddJavaFXPropertyMaker.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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.emptyList(), 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.emptyList(), Collections.singletonList(var), Collections.emptyList(), getterBody, null);
    return getter;
}
 
Example #3
Source File: IntroduceMethodFix.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether a duplicate intersects with some of the replacements already made
 */
boolean isDuplicateValid(TreePath duplicateRoot) {
    TreePath parent = duplicateRoot.getParentPath();
    List<Integer> repls = replacements.get(parent.getLeaf());
    if (repls == null) {
        return true;
    }
    List<? extends StatementTree> stmts = IntroduceHint.getStatements(duplicateRoot);
    int o = stmts.indexOf(duplicateRoot.getLeaf());
    int l = repls.size();
    for (int idx = 0; idx < l; idx += 2) {
        if (o < repls.get(idx)) {
            continue;
        }
        if (o <= repls.get(idx + 1)) {
            return false;
        }
    }
    return true;
}
 
Example #4
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.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 #5
Source File: EqualsHashCodeGenerator.java    From netbeans with 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 #6
Source File: Braces.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static ErrorDescription checkStatement(HintContext ctx, String dnKey, StatementTree statement, TreePath tp)  {
    if ( statement != null &&
         statement.getKind() != Tree.Kind.EMPTY_STATEMENT &&
         statement.getKind() != Tree.Kind.BLOCK &&
         statement.getKind() != Tree.Kind.TRY &&
         statement.getKind() != Tree.Kind.SYNCHRONIZED &&
         statement.getKind() != Tree.Kind.SWITCH &&
         statement.getKind() != Tree.Kind.ERRONEOUS &&
         !isErroneousExpression( statement )) {
        return ErrorDescriptionFactory.forTree(
                    ctx,
                    statement,
                    NbBundle.getMessage(Braces.class, dnKey),
                    new BracesFix(ctx.getInfo().getFileObject(), TreePathHandle.create(tp, ctx.getInfo())).toEditorFix());

    }
    return null;
}
 
Example #7
Source File: TreeDissector.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #8
Source File: Ifs.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #9
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 #10
Source File: IntroduceMethodFix.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example #11
Source File: TreeUtils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #12
Source File: TreeUtilitiesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testAttributingVar() throws Exception {
    ClassPath boot = ClassPathSupport.createClassPath(SourceUtilsTestUtil.getBootClassPath().toArray(new URL[0]));
    FileObject testFile = FileUtil.createData(FileUtil.createMemoryFileSystem().getRoot(), "Test.java");
    try (Writer w = new OutputStreamWriter(testFile.getOutputStream())) {
        w.append("public class Test { private static int I; }");
    }
    JavaSource js = JavaSource.create(ClasspathInfo.create(boot, ClassPath.EMPTY, ClassPath.EMPTY), testFile);
    js.runUserActionTask(new Task<CompilationController>() {
        @Override
        public void run(CompilationController parameter) throws Exception {
            parameter.toPhase(Phase.RESOLVED);
            TreePath clazzPath = new TreePath(new TreePath(new TreePath(parameter.getCompilationUnit()),
                                              parameter.getCompilationUnit().getTypeDecls().get(0)),
                    ((ClassTree) parameter.getCompilationUnit().getTypeDecls().get(0)).getMembers().get(1));
            Scope scope = parameter.getTrees().getScope(clazzPath);
            StatementTree st = parameter.getTreeUtilities().parseStatement("{ String s; }", new SourcePositions[1]);
            assertEquals(Kind.BLOCK, st.getKind());
            StatementTree var = st.getKind() == Kind.BLOCK ? ((BlockTree) st).getStatements().get(0) : st;
            parameter.getTreeUtilities().attributeTree(st, scope);
            checkType(parameter, clazzPath, var);
        }
    }, true);
}
 
Example #13
Source File: RemoveSurroundingCodeAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #14
Source File: PreconditionsChecker.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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());
    }


}
 
Example #15
Source File: ToStringGenerator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static List<StatementTree> createToStringMethodBodyWithPlusOperator(TreeMaker make, String typeName, Iterable<? extends VariableElement> fields) {
    ExpressionTree exp = make.Literal(typeName + '{');
    boolean first = true;
    for (VariableElement variableElement : fields) {
        StringBuilder sb = new StringBuilder();
        if (!first) {
            sb.append(", ");
        }
        sb.append(variableElement.getSimpleName().toString()).append('=');
        exp = make.Binary(Tree.Kind.PLUS, exp, make.Literal(sb.toString()));
        exp = make.Binary(Tree.Kind.PLUS, exp, make.Identifier(variableElement.getSimpleName()));
        first = false;
    }
    StatementTree stat = make.Return(make.Binary(Tree.Kind.PLUS, exp, make.Literal('}'))); //NOI18N
    return Collections.singletonList(stat);
}
 
Example #16
Source File: MagicSurroundWithTryCatchFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static StatementTree createRethrow(WorkingCopy info, TreeMaker make, String name) {
    if (!ErrorFixesFakeHint.isRethrow(ErrorFixesFakeHint.getPreferences(info.getFileObject(), FixKind.SURROUND_WITH_TRY_CATCH))) {
        return null;
    }

    ThrowTree result = make.Throw(make.Identifier(name));

    info.tag(result.getExpression(), Utilities.TAG_SELECT);

    return result;
}
 
Example #17
Source File: Tiny.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    TreePath tp = ctx.getPath();
    Tree parent = tp.getParentPath().getLeaf();
    List<? extends StatementTree> statements;

    switch (parent.getKind()) {
        case BLOCK: statements = ((BlockTree) parent).getStatements(); break;
        case CASE: statements = ((CaseTree) parent).getStatements(); break;
        default: throw new IllegalStateException(parent.getKind().name());
    }

    VariableTree var = (VariableTree) tp.getLeaf();
    int current = statements.indexOf(tp.getLeaf());
    TreeMaker make = wc.getTreeMaker();
    List<StatementTree> newStatements = new ArrayList<StatementTree>();

    newStatements.addAll(statements.subList(0, current));
    newStatements.add(
        make.asReplacementOf(
            make.Variable(var.getModifiers(), var.getName(), var.getType(), null),
            var)
    );
    newStatements.add(make.ExpressionStatement(make.Assignment(make.Identifier(var.getName()), var.getInitializer())));
    newStatements.addAll(statements.subList(current + 1, statements.size()));

    Tree target;

    switch (parent.getKind()) {
        case BLOCK: target = make.Block(newStatements, ((BlockTree) parent).isStatic()); break;
        case CASE: target = make.Case(((CaseTree) parent).getExpression(), newStatements); break;
        default: throw new IllegalStateException(parent.getKind().name());
    }

    wc.rewrite(parent, target);
}
 
Example #18
Source File: JavacParserTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
void testPositionBrokenSource126732a() throws IOException {
    String[] commands = new String[]{
        "return Runnable()",
        "do { } while (true)",
        "throw UnsupportedOperationException()",
        "assert true",
        "1 + 1",};

    for (String command : commands) {

        String code = "package test;\n"
                + "public class Test {\n"
                + "    public static void test() {\n"
                + "        " + command + " {\n"
                + "                new Runnable() {\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 =
                method.getBody().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 #19
Source File: AbstractTestGenerator.java    From netbeans with 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 #20
Source File: ProspectiveOperation.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static List<ProspectiveOperation> createOperator(StatementTree tree,
        OperationType operationType, PreconditionsChecker precond, WorkingCopy workingCopy) {
    List<ProspectiveOperation> ls = new ArrayList<ProspectiveOperation>();
    if (OperationType.REDUCE == operationType) {
        return createProspectiveReducer(tree, workingCopy, operationType, precond, ls);
    } else {
        ProspectiveOperation operation = new ProspectiveOperation(tree, operationType, precond.getInnerVariables(), workingCopy, precond.getVarToName());
        operation.getNeededVariables();
        ls.add(operation);
        return ls;
    }
}
 
Example #21
Source File: JUnit3TestGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #22
Source File: JUnit4TestGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 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()}
 */
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;
}
 
Example #23
Source File: JUnit5TestGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 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()}
 */
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;
}
 
Example #24
Source File: ProspectiveOperation.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private StatementTree castToStatementTree(Tree currentTree) {
    if (currentTree instanceof StatementTree) {
        return (StatementTree) currentTree;
    } else {
        return this.treeMaker.ExpressionStatement((ExpressionTree) currentTree);
    }
}
 
Example #25
Source File: TreeUtilitiesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void checkType(CompilationInfo info, TreePath base, StatementTree st) {
    TreePath tp = new TreePath(base, st);
    Element el = info.getTrees().getElement(tp);

    assertNotNull(el);
    assertEquals("s", el.toString());
}
 
Example #26
Source File: IntroduceClass.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static List<? extends StatementTree> getStatements(TreePath firstLeaf) {
    Tree parentsLeaf = firstLeaf.getLeaf();
    List<? extends StatementTree> statements;
    switch (parentsLeaf.getKind()) {
        case BLOCK:
            statements = ((BlockTree) parentsLeaf).getStatements();
            break;
        case CASE:
            statements = ((CaseTree) parentsLeaf).getStatements();
            break;
        default:
            Tree first = firstLeaf.getLeaf();
            if (Tree.Kind.EXPRESSION_STATEMENT.equals(first.getKind())) {
                statements = Collections.singletonList((StatementTree) firstLeaf.getLeaf());
            } else {
                statements = Collections.emptyList();
            }
    }
    int s = statements.size();
    boolean haveOriginalStatements = true;
    while (s > 0 && ";".equals(statements.get(--s).toString().trim())) {
        if (haveOriginalStatements) {
            statements = new ArrayList<>(statements);
            haveOriginalStatements = false;
        }
        statements.remove(s);
    }
    return statements;
}
 
Example #27
Source File: Refactorer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Boolean isIfWithContinue( IfTree ifTree) {
    StatementTree then = ifTree.getThenStatement();
    if (then.getKind() == Tree.Kind.CONTINUE) {
        return true;
    } else if (then.getKind() == Tree.Kind.BLOCK) {
        List<? extends StatementTree> statements = ((BlockTree) then).getStatements();
        if (statements.size() == 1 && statements.get(0).getKind() == Tree.Kind.CONTINUE) {
            return true;
        }

    }
    return false;
}
 
Example #28
Source File: IntroduceFieldFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Adds or rewrites assignment or expression usage in the body of 'method'
 * @param parameter working copy
 * @param method 
 * @param target
 * @param assignment 
 */
private void insertStatement(WorkingCopy parameter, 
        TreePath target, Tree anchor, StatementTree assignment, boolean replace) {
    if ((variableRewrite || expressionStatementRewrite) && replace) {
        parameter.rewrite(toRemoveFromParent.getLeaf(), assignment);
        toRemoveFromParent = null;
    } else {
        Utilities.insertStatement(parameter, target, anchor, Collections.singletonList(assignment), null, 0);
    }
}
 
Example #29
Source File: JavacParserTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
void testPositionBrokenSource126732a() throws IOException {
    String[] commands = new String[]{
        "return Runnable()",
        "do { } while (true)",
        "throw UnsupportedOperationException()",
        "assert true",
        "1 + 1",};

    for (String command : commands) {

        String code = "package test;\n"
                + "public class Test {\n"
                + "    public static void test() {\n"
                + "        " + command + " {\n"
                + "                new Runnable() {\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 =
                method.getBody().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 #30
Source File: AbstractTestGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 */
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);
}