com.sun.source.tree.BlockTree Java Examples

The following examples show how to use com.sun.source.tree.BlockTree. 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: AsyncConverter.java    From netbeans with 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 #2
Source File: CopyFinder.java    From netbeans with 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 #3
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 #4
Source File: JUnit5TestGenerator.java    From netbeans with 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 #5
Source File: JavaInputAstVisitor.java    From google-java-format with 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 #6
Source File: AssignResultToVariable.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private StatementTree findMatchingMethodInvocation(CompilationInfo info, BlockTree block, int offset) {
    for (StatementTree t : block.getStatements()) {
        if (t.getKind() != Kind.EXPRESSION_STATEMENT) continue;

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

        if (offset < statementStart) return null;

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

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

    return null;
}
 
Example #7
Source File: NullAway.java    From NullAway with 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 #8
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 #9
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with 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 #10
Source File: ForLoopToFunctionalHint.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@TriggerTreeKind(Tree.Kind.ENHANCED_FOR_LOOP)
@Messages("ERR_ForLoopToFunctionalHint=Can use functional operations")
public static ErrorDescription computeWarning(HintContext ctx) {
    if (ctx.getInfo().getElements().getTypeElement("java.util.stream.Streams") == null && !DISABLE_CHECK_FOR_STREAM) return null;
    
    PreconditionsChecker pc = new PreconditionsChecker(ctx.getPath().getLeaf(), ctx.getInfo());
    if (pc.isSafeToRefactor()) {
        EnhancedForLoopTree eflt = (EnhancedForLoopTree)ctx.getPath().getLeaf();
        StatementTree stmt = eflt.getStatement();
        if (stmt == null) {
            return null;
        }
        if (stmt.getKind() == Tree.Kind.BLOCK) {
            BlockTree bt = (BlockTree)stmt;
            if (bt.getStatements() == null || bt.getStatements().isEmpty()) {
                return null;
            }
        }
        Fix fix = new FixImpl(ctx.getInfo(), ctx.getPath(), null).toEditorFix();
        return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_ForLoopToFunctionalHint(), fix);
    }
    return null;
}
 
Example #11
Source File: DoubleCheck.java    From netbeans with 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 #12
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static List<TreePath> getStatementPaths(TreePath firstLeaf) {
    switch (firstLeaf.getParentPath().getLeaf().getKind()) {
        case BLOCK:
            return getTreePaths(firstLeaf.getParentPath(), ((BlockTree) firstLeaf.getParentPath().getLeaf()).getStatements());
        case CASE:
            return getTreePaths(firstLeaf.getParentPath(), ((CaseTree) firstLeaf.getParentPath().getLeaf()).getStatements());
        default:
            return Collections.singletonList(firstLeaf);
    }
}
 
Example #13
Source File: FinalizeDoesNotCallSuper.java    From netbeans with 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 #14
Source File: JavacParserTest.java    From hottub with 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 #15
Source File: MethodTest2.java    From netbeans with 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 #16
Source File: PartialReparserService.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public BlockTree reflowMethodBody(CompilationUnitTree topLevel, ClassTree ownerClass, MethodTree methodToReparse) {
    Flow flow = Flow.instance(context);
    TreeMaker make = TreeMaker.instance(context);
    flow.reanalyzeMethod(make.forToplevel((JCCompilationUnit)topLevel),
            (JCClassDecl)ownerClass);
    return methodToReparse.getBody();
}
 
Example #17
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 #18
Source File: LambdaTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testLambdaFullBody2Expression() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public static void taragui() {\n" +
        "        ChangeListener l = (e) -> {return 1;};\n" + 
        "    }\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public static void taragui() {\n" +
        "        ChangeListener l = (e) -> 1;\n" + 
        "    }\n" +
        "}\n";
    JavaSource src = getJavaSource(testFile);
    
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(final WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            final TreeMaker make = workingCopy.getTreeMaker();
            new ErrorAwareTreeScanner<Void, Void>() {
                @Override public Void visitLambdaExpression(LambdaExpressionTree node, Void p) {
                    ReturnTree t = (ReturnTree) ((BlockTree) node.getBody()).getStatements().get(0);
                    workingCopy.rewrite(node, make.setLambdaBody(node, t.getExpression()));
                    return super.visitLambdaExpression(node, p);
                }
            }.scan(workingCopy.getCompilationUnit(), null);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example #19
Source File: ToStringGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static BlockTree createToStringMethodBody(TreeMaker make, String typeName, Iterable<? extends VariableElement> fields, boolean useStringBuilder) {
    List<StatementTree> statements;
    if (useStringBuilder) {
        statements = createToStringMethodBodyWithStringBuilder(make, typeName, fields);
    } else {
        statements = createToStringMethodBodyWithPlusOperator(make, typeName, fields);
    }
    BlockTree body = make.Block(statements, false);
    return body;
}
 
Example #20
Source File: ToStringGenerator.java    From netbeans with 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
}
 
Example #21
Source File: TreeUtilitiesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testIsEndOfCompoundVariableDeclaration() throws Exception {
    prepareTest("Test", "package test; public class Test {public Test(){int i = 10, j = 11;}}");
    TreePath tp = info.getTreeUtilities().pathFor(47);
    BlockTree bt = (BlockTree) tp.getLeaf();
    assertFalse(info.getTreeUtilities().isEndOfCompoundVariableDeclaration(bt.getStatements().get(1)));
    assertTrue(info.getTreeUtilities().isEndOfCompoundVariableDeclaration(bt.getStatements().get(2)));
}
 
Example #22
Source File: Refactorer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean isReturningIf( IfTree ifTree) {
    StatementTree then = ifTree.getThenStatement();
    if (then.getKind() == Tree.Kind.RETURN) {
        return true;
    } else if (then.getKind() == Tree.Kind.BLOCK) {
        BlockTree block = (BlockTree) then;
        if (block.getStatements().size() == 1 && block.getStatements().get(0).getKind() == Tree.Kind.RETURN) {
            return true;
        }
    }
    return false;
}
 
Example #23
Source File: NullabilityUtil.java    From NullAway with 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 #24
Source File: DataFlow.java    From NullAway with MIT License 5 votes vote down vote up
/**
 * Get the dataflow result at exit for a given method (or lambda, or initializer block)
 *
 * @param path path to method (or lambda, or initializer block)
 * @param context Javac context
 * @param transfer transfer functions
 * @param <A> values in abstraction
 * @param <S> store type
 * @param <T> transfer function type
 * @return dataflow result at exit of method
 */
public <A extends AbstractValue<A>, S extends Store<S>, T extends TransferFunction<A, S>>
    S finalResult(TreePath path, Context context, T transfer) {
  final Tree leaf = path.getLeaf();
  Preconditions.checkArgument(
      leaf instanceof MethodTree
          || leaf instanceof LambdaExpressionTree
          || leaf instanceof BlockTree
          || leaf instanceof VariableTree,
      "Leaf of methodPath must be of type MethodTree, LambdaExpressionTree, BlockTree, or VariableTree, but was %s",
      leaf.getClass().getName());

  return dataflow(path, context, transfer).getAnalysis().getRegularExitStore();
}
 
Example #25
Source File: MagicSurroundWithTryCatchFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public @Override Void visitBlock(BlockTree bt, Void p) {
    List<CatchTree> catches = createCatches(info, make, thandles, statement);
    
    //#89379: if inside a constructor, do not wrap the "super"/"this" call:
    //please note that the "super" or "this" call is supposed to be always
    //in the constructor body
    BlockTree toUse = bt;
    StatementTree toKeep = null;
    Tree parent = getCurrentPath().getParentPath().getLeaf();
    
    if (parent.getKind() == Kind.METHOD && bt.getStatements().size() > 0) {
        MethodTree mt = (MethodTree) parent;
        
        if (mt.getReturnType() == null) {
            toKeep = bt.getStatements().get(0);
            toUse = make.Block(bt.getStatements().subList(1, bt.getStatements().size()), false);
        }
    }
    
    if (!streamAlike) {
        info.rewrite(bt, createBlock(bt.isStatic(), toKeep, make.Try(toUse, catches, null)));
    } else {
        VariableTree originalDeclaration = (VariableTree) statement.getLeaf();
        VariableTree declaration = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), originalDeclaration.getName(), originalDeclaration.getType(), make.Identifier("null"));
        StatementTree assignment = make.ExpressionStatement(make.Assignment(make.Identifier(originalDeclaration.getName()), originalDeclaration.getInitializer()));
        BlockTree finallyTree = make.Block(Collections.singletonList(createFinallyCloseBlockStatement(originalDeclaration)), false);
        
        info.rewrite(originalDeclaration, assignment);
        info.rewrite(bt, createBlock(bt.isStatic(), toKeep, declaration, make.Try(toUse, catches, finallyTree)));
    }
    
    return null;
}
 
Example #26
Source File: JavaDocGenerator.java    From vertx-docgen with Apache License 2.0 5 votes vote down vote up
/**
 * Render the source fragment for the Java language. Java being the pivot language, we consider this method as the
 * _default_ behavior. This method is final as it must not be overridden by any extension.
 *
 * @param elt    the element
 * @param source the source
 * @return the fragment
 */
@Override
public String renderSource(ExecutableElement elt, String source) {
  // Get block
  TreePath path = docTrees.getPath(elt);
  MethodTree methodTree = (MethodTree) path.getLeaf();
  BlockTree blockTree = methodTree.getBody();
  List<? extends StatementTree> statements = blockTree.getStatements();
  if (statements.size() > 0) {
    return renderSource(path, statements, source);
  } else {
    return null;
  }
}
 
Example #27
Source File: TreeUtilitiesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testStaticBlock() throws Exception {
    ClassPath boot = ClassPathSupport.createClassPath(SourceUtilsTestUtil.getBootClassPath().toArray(new URL[0]));
    JavaSource js = JavaSource.create(ClasspathInfo.create(boot, ClassPath.EMPTY, ClassPath.EMPTY));
    js.runUserActionTask(new Task<CompilationController>() {
        @Override
        public void run(CompilationController parameter) throws Exception {
            final SourcePositions[] sp = new SourcePositions[1];
            BlockTree block = parameter.getTreeUtilities().parseStaticBlock("static { }", sp);
            assertNotNull(block);
            assertEquals(0, sp[0].getStartPosition(null, block));
            assertEquals(10, sp[0].getEndPosition(null, block));
            assertNull(parameter.getTreeUtilities().parseStaticBlock("static", new SourcePositions[1]));
        }
    }, true);
}
 
Example #28
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static @NonNull Collection<? extends TreePath> resolveFieldGroup(@NonNull CompilationInfo info, @NonNull TreePath variable) {
    Tree leaf = variable.getLeaf();

    if (leaf.getKind() != Kind.VARIABLE) {
        return Collections.singleton(variable);
    }

    TreePath parentPath = variable.getParentPath();
    Iterable<? extends Tree> children;

    switch (parentPath.getLeaf().getKind()) {
        case BLOCK: children = ((BlockTree) parentPath.getLeaf()).getStatements(); break;
        case ANNOTATION_TYPE:
        case CLASS:
        case ENUM:
        case INTERFACE:
            children = ((ClassTree) parentPath.getLeaf()).getMembers(); break;
        case CASE:  children = ((CaseTree) parentPath.getLeaf()).getStatements(); break;
        default:    children = Collections.singleton(leaf); break;
    }

    List<TreePath> result = new LinkedList<TreePath>();
    ModifiersTree currentModifiers = ((VariableTree) leaf).getModifiers();

    for (Tree c : children) {
        if (c.getKind() != Kind.VARIABLE) continue;

        if (((VariableTree) c).getModifiers() == currentModifiers) {
            result.add(new TreePath(parentPath, c));
        }
    }
    
    return result;
}
 
Example #29
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 #30
Source File: FmtCodeGeneration.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected void doModification(ResultIterator resultIterator) throws Exception {
    WorkingCopy copy = WorkingCopy.get(resultIterator.getParserResult());
    copy.toPhase(Phase.RESOLVED);
    TreeMaker tm = copy.getTreeMaker();
    GeneratorUtilities gu = GeneratorUtilities.get(copy);
    CompilationUnitTree cut = copy.getCompilationUnit();
    ClassTree ct = (ClassTree) cut.getTypeDecls().get(0);
    VariableTree field = (VariableTree)ct.getMembers().get(1);
    List<Tree> members = new ArrayList<Tree>();
    AssignmentTree stat = tm.Assignment(tm.Identifier("name"), tm.Literal("Name")); //NOI18N
    BlockTree init = tm.Block(Collections.singletonList(tm.ExpressionStatement(stat)), false);
    members.add(init);
    members.add(gu.createConstructor(ct, Collections.<VariableTree>emptyList()));
    members.add(gu.createGetter(field));
    ModifiersTree mods = tm.Modifiers(EnumSet.of(Modifier.PRIVATE));
    ClassTree inner = tm.Class(mods, "Inner", Collections.<TypeParameterTree>emptyList(), null, Collections.<Tree>emptyList(), Collections.<Tree>emptyList()); //NOI18N
    members.add(inner);
    mods = tm.Modifiers(EnumSet.of(Modifier.PRIVATE, Modifier.STATIC));
    ClassTree nested = tm.Class(mods, "Nested", Collections.<TypeParameterTree>emptyList(), null, Collections.<Tree>emptyList(), Collections.<Tree>emptyList()); //NOI18N
    members.add(nested);
    IdentifierTree nestedId = tm.Identifier("Nested"); //NOI18N
    VariableTree staticField = tm.Variable(mods, "instance", nestedId, null); //NOI18N
    members.add(staticField);
    NewClassTree nct = tm.NewClass(null, Collections.<ExpressionTree>emptyList(), nestedId, Collections.<ExpressionTree>emptyList(), null);
    stat = tm.Assignment(tm.Identifier("instance"), nct); //NOI18N
    BlockTree staticInit = tm.Block(Collections.singletonList(tm.ExpressionStatement(stat)), true);
    members.add(staticInit);
    members.add(gu.createGetter(staticField));
    ClassTree newCT = gu.insertClassMembers(ct, members);
    copy.rewrite(ct, newCT);
}