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

项目:incubator-netbeans    文件:CopyFinder.java   
public Boolean visitBlock(BlockTree node, TreePath p) {
    if (p == null) {
        super.visitBlock(node, p);
        return false;
    }

    if (p.getLeaf().getKind() != Kind.BLOCK) {
        //single-statement blocks are considered to be equivalent to statements
        //TODO: some parents may need to be more strict, esp. synchronized and do-while
        assert node.getStatements().size() == 1;
        assert !node.isStatic();

        if (p.getLeaf() == searchingFor.getLeaf())
            return false;

        return checkLists(node.getStatements(), Collections.singletonList(p.getLeaf()), p.getParentPath());
    }

    BlockTree at = (BlockTree) p.getLeaf();

    if (node.isStatic() != at.isStatic()) {
        return false;
    }

    return checkLists(node.getStatements(), at.getStatements(), p);
}
项目: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    文件: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
}
项目: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    文件: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    文件: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    文件:JUnit3TestGenerator.java   
/**
 */
protected MethodTree composeNewTestMethod(String testMethodName,
                                          BlockTree testMethodBody,
                                          List<ExpressionTree> throwsList,
                                          WorkingCopy workingCopy) {
    TreeMaker maker = workingCopy.getTreeMaker();
    return maker.Method(
            maker.Modifiers(createModifierSet(PUBLIC)),
            testMethodName,
            maker.PrimitiveType(TypeKind.VOID),
            Collections.<TypeParameterTree>emptyList(),
            Collections.<VariableTree>emptyList(),
            throwsList,
            testMethodBody,
            null);          //default value - used by annotations
}
项目:incubator-netbeans    文件:AddJavaFXPropertyMaker.java   
private MethodTree createGetter(ModifiersTree mods, TypeMirror valueType) {
    StringBuilder getterName = GeneratorUtils.getCapitalizedName(config.getName());
    getterName.insert(0, valueType.getKind() == TypeKind.BOOLEAN ? "is" : "get");
    ReturnTree returnTree = make.Return(make.MethodInvocation(Collections.EMPTY_LIST, make.MemberSelect(make.Identifier(config.getName()), hasGet ? "get" : "getValue"), Collections.EMPTY_LIST));
    BlockTree getterBody = make.Block(Collections.singletonList(returnTree), false);
    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());
    }
    MethodTree getter = make.Method(mods, getterName, valueTree, Collections.EMPTY_LIST, Collections.EMPTY_LIST, Collections.EMPTY_LIST, getterBody, null);
    return getter;
}
项目: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;
}
项目: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;
}
项目: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());
    }


}
项目:NullAway    文件:NullabilityUtil.java   
/**
 * find the enclosing method, lambda expression or initializer block for the leaf of some tree
 * path
 *
 * @param path the tree path
 * @return the closest enclosing method / lambda
 */
@Nullable
public static TreePath findEnclosingMethodOrLambdaOrInitializer(TreePath path) {
  while (path != null) {
    if (path.getLeaf() instanceof MethodTree || path.getLeaf() instanceof LambdaExpressionTree) {
      return path;
    }
    TreePath parent = path.getParentPath();
    if (parent != null && parent.getLeaf() instanceof ClassTree) {
      if (path.getLeaf() instanceof BlockTree) {
        // found initializer block
        return path;
      }
      if (path.getLeaf() instanceof VariableTree
          && ((VariableTree) path.getLeaf()).getInitializer() != null) {
        // found field with an inline initializer
        return path;
      }
    }
    path = parent;
  }
  return null;
}
项目:incubator-netbeans    文件:InitializerCanBeStatic.java   
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    Tree t = ctx.getPath().getLeaf();
    if (t.getKind() != Tree.Kind.BLOCK) {
        return;
    }
    BlockTree bl = (BlockTree)t;
    WorkingCopy wc = ctx.getWorkingCopy();
    GeneratorUtilities gu = GeneratorUtilities.get(wc);
    gu.importComments(bl, wc.getCompilationUnit());
    TreeMaker mk = wc.getTreeMaker();
    BlockTree nbl = mk.Block(bl.getStatements(), true);
    gu.copyComments(bl, nbl, true);
    gu.copyComments(bl, nbl, false);
    wc.rewrite(bl, nbl);
}
项目:incubator-netbeans    文件:DoubleCheck.java   
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;
}
项目:incubator-netbeans    文件:IntroduceHint.java   
static boolean needsStaticRelativeTo(CompilationInfo info, TreePath targetClass, TreePath occurrence) {
    while (occurrence != null && targetClass.getLeaf() != occurrence.getLeaf()) {
        switch (occurrence.getLeaf().getKind()) {
            case METHOD:
                if (((MethodTree) occurrence.getLeaf()).getModifiers().getFlags().contains(Modifier.STATIC)) {
                    return true;
                }
                break;
            case BLOCK:
                if (((BlockTree) occurrence.getLeaf()).isStatic()) {
                    return true;
                }
                break;
            case INTERFACE:
                return true;
        }

        occurrence = occurrence.getParentPath();
    }

    return false;
}
项目:incubator-netbeans    文件:IntroduceHint.java   
static void removeFromParent(WorkingCopy parameter, TreePath what) throws IllegalAccessException {
    final TreeMaker make = parameter.getTreeMaker();
    Tree parentTree = what.getParentPath().getLeaf();
    Tree original = what.getLeaf();
    Tree newParent;

    switch (parentTree.getKind()) {
        case BLOCK:
            newParent = make.removeBlockStatement((BlockTree) parentTree, (StatementTree) original);
            break;
        case CASE:
            newParent = make.removeCaseStatement((CaseTree) parentTree, (StatementTree) original);
            break;
        case CLASS:
        case ENUM:
        case INTERFACE:
            newParent = make.removeClassMember((ClassTree)parentTree, original);
            break;
        default:
            throw new IllegalAccessException(parentTree.getKind().toString());
    }

    parameter.rewrite(parentTree, newParent);
}
项目: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    文件:ClassStructure.java   
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.ClassStructure.noopMethodInAbstractClass", description = "#DESC_org.netbeans.modules.java.hints.ClassStructure.noopMethodInAbstractClass", category = "class_structure", enabled = false, suppressWarnings = {"NoopMethodInAbstractClass"}, options=Options.QUERY) //NOI18N
@TriggerTreeKind(Kind.METHOD)
public static ErrorDescription noopMethodInAbstractClass(HintContext context) {
    final MethodTree mth = (MethodTree) context.getPath().getLeaf();
    final Tree parent = context.getPath().getParentPath().getLeaf();
    if (TreeUtilities.CLASS_TREE_KINDS.contains(parent.getKind()) && ((ClassTree) parent).getModifiers().getFlags().contains(Modifier.ABSTRACT)) {
        final BlockTree body = mth.getBody();
        if (body != null && body.getStatements().isEmpty()) {
            return ErrorDescriptionFactory.forName(context, mth, NbBundle.getMessage(ClassStructure.class, "MSG_NoopMethodInAbstractClass", mth.getName())); //NOI18N
        }
    }
    return null;
}
项目: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   
/**
 * computes those fields always initialized by callee safe init methods before a read operation
 * (pathToRead) is invoked. See <a
 * href="https://github.com/uber/NullAway/wiki/Error-Messages#initializer-method-does-not-guarantee-nonnull-field-is-initialized--nonnull-field--not-initialized">the
 * docs</a> for what is considered a safe initializer method.
 */
private Set<Element> safeInitByCalleeBefore(
    TreePath pathToRead, VisitorState state, TreePath enclosingBlockPath) {
  Set<Element> result = new LinkedHashSet<>();
  Set<Element> safeInitMethods = new LinkedHashSet<>();
  Tree enclosingBlockOrMethod = enclosingBlockPath.getLeaf();
  if (enclosingBlockOrMethod instanceof VariableTree) {
    return Collections.emptySet();
  }
  BlockTree blockTree =
      enclosingBlockOrMethod instanceof BlockTree
          ? (BlockTree) enclosingBlockOrMethod
          : ((MethodTree) enclosingBlockOrMethod).getBody();
  List<? extends StatementTree> statements = blockTree.getStatements();
  Tree readExprTree = pathToRead.getLeaf();
  int readStartPos = getStartPos((JCTree) readExprTree);
  Symbol.ClassSymbol classSymbol = enclosingClassSymbol(enclosingBlockPath);
  // bound loop at size-1 since the final statement cannot appear before the read
  for (int i = 0; i < statements.size() - 1; i++) {
    StatementTree curStmt = statements.get(i), nextStmt = statements.get(i + 1);
    if (getStartPos((JCTree) nextStmt) <= readStartPos) {
      Element privMethodElem = getInvokeOfSafeInitMethod(curStmt, classSymbol, state);
      if (privMethodElem != null) {
        safeInitMethods.add(privMethodElem);
      }
    }
  }
  addGuaranteedNonNullFromInvokes(
      state,
      Trees.instance(JavacProcessingEnvironment.instance(state.context)),
      safeInitMethods,
      getNullnessAnalysis(state),
      result);
  return result;
}
项目:NullAway    文件:NullAway.java   
private Symbol.ClassSymbol enclosingClassSymbol(TreePath enclosingBlockPath) {
  Tree leaf = enclosingBlockPath.getLeaf();
  if (leaf instanceof BlockTree) {
    // parent must be a ClassTree
    Tree parent = enclosingBlockPath.getParentPath().getLeaf();
    return ASTHelpers.getSymbol((ClassTree) parent);
  } else {
    return ASTHelpers.enclosingClass(ASTHelpers.getSymbol(leaf));
  }
}
项目:incubator-netbeans    文件:VeryPretty.java   
private java.util.List<? extends StatementTree> getStatements(Tree tree) {
    switch (tree.getKind()) {
        case BLOCK: return ((BlockTree) tree).getStatements();
        case CASE: return ((CaseTree) tree).getStatements();
        default: return null;
    }
}
项目: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    文件:GeneratorUtilities.java   
private static void doMoveComments(WorkingCopy wc, Tree from,  Tree to, int offset, List<Comment> comments, int fromIdx, int toIdx) {
    if (comments.isEmpty()) {
        return;
    }
    TreeMaker tm = wc.getTreeMaker();
    Tree tree = from;
    switch (from.getKind()) {
        case METHOD:
            tree = tm.setLabel(from, ((MethodTree)from).getName());
            break;
        case VARIABLE:
            tree = tm.setLabel(from, ((VariableTree)from).getName());
            break;
        case BLOCK:
            tree = tm.Block(((BlockTree)from).getStatements(), ((BlockTree)from).isStatic());
            GeneratorUtilities gu = GeneratorUtilities.get(wc);
            gu.copyComments(from, tree, true);
            gu.copyComments(from, tree, false);
            break;
    }
    boolean before = (int)wc.getTrees().getSourcePositions().getStartPosition(wc.getCompilationUnit(), from) >= offset;
    if (fromIdx >=0 && toIdx >= 0 && toIdx - fromIdx > 0) {
        for (int i = toIdx - 1; i >= fromIdx; i--) {
            tm.removeComment(tree, i, before);
        }
    }
    wc.rewrite(from, tree);
    for (Comment comment : comments) {
        tm.addComment(to, comment, comment.pos() <= offset);
    }
}
项目:incubator-netbeans    文件:GeneratorUtilities.java   
/**
 * Tags first method in the list, in order to select it later inside editor
 * @param methods list of methods to be implemented/overridden
 */
private void tagFirst(List<MethodTree> methods) {
    //tag first method body, if any
    if (methods.size() > 0) {
        BlockTree body = methods.get(0).getBody();
        if (body != null && !body.getStatements().isEmpty()) {
            copy.tag(body.getStatements().get(0), "methodBodyTag"); // NOI18N
        }
    }
}
项目:incubator-netbeans    文件:CodeStyle.java   
/**
 * Returns the group number of the class member. Elements with the same
 * number form a group. Groups with lower numbers should be positioned
 * higher in the class member list.
 * @param tree the member tree
 * @return the group number
 * @since 0.96
 */
public int getGroupId(Tree tree) {
    ElementKind kind = ElementKind.OTHER;
    Set<Modifier> modifiers = null;
    switch (tree.getKind()) {
        case ANNOTATION_TYPE:
        case CLASS:
        case ENUM:
        case INTERFACE:
            kind = ElementKind.CLASS;
            modifiers = ((ClassTree)tree).getModifiers().getFlags();
            break;
        case METHOD:
            MethodTree mt = (MethodTree)tree;
            if (mt.getName().contentEquals("<init>")) { //NOI18N
                kind = ElementKind.CONSTRUCTOR;
            } else {
                kind = ElementKind.METHOD;
            }
            modifiers = mt.getModifiers().getFlags();
            break;
        case VARIABLE:
            kind = ElementKind.FIELD;
            modifiers = ((VariableTree)tree).getModifiers().getFlags();
            break;
        case BLOCK:
            kind = ((BlockTree)tree).isStatic() ? ElementKind.STATIC_INIT : ElementKind.INSTANCE_INIT;
            break;
    }
    for (Info info : infos) {
        if (info.check(kind, modifiers))
            return info.groupId;
    }
    return infos.length;
}
项目:openjdk-jdk10    文件:LocalInAnonymous.java   
@Override
public Void visitBlock(BlockTree node, Void p) {
    if (getCurrentPath().getParentPath().getLeaf().getKind() != Tree.Kind.CLASS) {
        return super.visitBlock(node, p);
    }
    Element prevOwner = currentOwner;
    try {
        currentOwner = null;
        return super.visitBlock(node, p);
    } finally {
        currentOwner = prevOwner;
    }
}
项目:incubator-netbeans    文件:MethodTest2.java   
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);                    
}
项目:incubator-netbeans    文件:RemoveSurroundingCodeAction.java   
private void addStat(StatementTree stat, List<StatementTree> to) {
    if (stat != null) {
        if (stat.getKind() == Tree.Kind.BLOCK) {
            to.addAll(((BlockTree) stat).getStatements());
        } else {
            to.add(stat);
        }
    }
}
项目: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    文件:DeclarationForInstanceOf.java   
public ChangeInfo implement() throws Exception {
    js.runModificationTask(new Task<WorkingCopy>() {
        public void run(WorkingCopy wc) throws Exception {
            wc.toPhase(Phase.RESOLVED);

            TreePath ifTP = ifHandle.resolve(wc);
            TreePath resolvedExpression = expression.resolve(wc);
            TypeMirror resolvedType = type.resolve(wc);

            if (ifTP == null || resolvedType == null || resolvedExpression == null) {
                return ;
            }

            IfTree ift = (IfTree) ifTP.getLeaf();
            StatementTree then = ift.getThenStatement();

            if (then.getKind() == Kind.ERRONEOUS) {
                return ; //TODO.
            }

            List<StatementTree> statements = new LinkedList<StatementTree>();

            if (then.getKind() == Kind.BLOCK) {
                statements.addAll(((BlockTree) then).getStatements());
            } else {
                statements.add(then);
            }

            TreeMaker make = wc.getTreeMaker();
            VariableTree decl = make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), name, make.Type(resolvedType), make.TypeCast(make.Type(resolvedType), (ExpressionTree) resolvedExpression.getLeaf()));

            statements.add(0, decl);

            BlockTree nue = make.Block(statements, false);

            wc.rewrite(then, nue);
        }
    }).commit();
    return null;
}
项目:incubator-netbeans    文件:LambdaTest.java   
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);
}
项目:incubator-netbeans    文件:MemberAdditionTest.java   
public Void visitClass(ClassTree node, Object p) {
    TypeElement te = (TypeElement)model.getElement(node);
    if (te != null) {
        List<Tree> members = new ArrayList<Tree>(node.getMembers());
        int pos = putBefore != null ? members.indexOf(putBefore) + 1: members.size();

        Set<Modifier> mods = EnumSet.of(Modifier.PUBLIC);

        //create body:
        List<StatementTree> statements = new ArrayList();
        List<VariableTree> arguments = new ArrayList();

        for (VariableElement ve : fields) {
            AssignmentTree a = make.Assignment(make.MemberSelect(make.Identifier("this"), ve.getSimpleName()), make.Identifier(ve.getSimpleName()));

            statements.add(make.ExpressionStatement(a));
            arguments.add(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), ve.getSimpleName(), make.Type(ve.asType()), null));
        }

        BlockTree body = make.Block(statements, false);

        members.add(pos, make.Method(make.Modifiers(mods), "<init>", null, Collections.<TypeParameterTree> emptyList(), arguments, Collections.<ExpressionTree>emptyList(), body, null));
        ClassTree decl = make.Class(node.getModifiers(), node.getSimpleName(), node.getTypeParameters(), node.getExtendsClause(), (List<ExpressionTree>)node.getImplementsClause(), members);
        model.setElement(decl, te);
        model.setType(decl, model.getType(node));
        model.setPos(decl, model.getPos(node));
        copy.rewrite(node, decl);
    }
    return null;
}
项目:incubator-netbeans    文件:AbstractMethodCannotHaveBody.java   
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    MethodTree mt = (MethodTree) ctx.getPath().getLeaf();
    MethodTree nue = ctx.getWorkingCopy().getTreeMaker().Method(mt.getModifiers(), mt.getName(), mt.getReturnType(), mt.getTypeParameters(), mt.getParameters(), mt.getThrows(), (BlockTree) null, (ExpressionTree) mt.getDefaultValue());

    ctx.getWorkingCopy().rewrite(mt, nue);
}
项目:incubator-netbeans    文件:Utilities.java   
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;
}
项目: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    文件:JavacParserTest.java   
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, fm, 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));
    }
}
项目:incubator-netbeans    文件:JUnit4TestGenerator.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()}
 */
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;
}
项目: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;
}