com.sun.source.tree.Tree Java Examples

The following examples show how to use com.sun.source.tree.Tree. 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: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 7 votes vote down vote up
/**
 * Helper methods for method invocations.
 */
void addTypeArguments(List<? extends Tree> typeArguments, Indent plusIndent) {
    if (typeArguments == null || typeArguments.isEmpty()) {
        return;
    }
    token("<");
    builder.open(plusIndent);
    boolean first = true;
    for (Tree typeArgument : typeArguments) {
        if (!first) {
            token(",");
            builder.breakToFill(" ");
        }
        scan(typeArgument, null);
        first = false;
    }
    builder.close();
    token(">");
}
 
Example #2
Source File: NCLOCVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Object visitVariable(VariableTree node, Object p) {
    TreePath path = getCurrentPath();
    Tree parent = path.getParentPath().getLeaf();
    if (parent instanceof StatementTree) {
        boolean count = true;
        if (parent instanceof ForLoopTree) {
            count = !((ForLoopTree)parent).getInitializer().contains(node);
        } else if (parent instanceof EnhancedForLoopTree) {
            count = ((EnhancedForLoopTree)parent).getVariable() != node;
        }
        if (count) {
            statements++;
        }
    }
    return super.visitVariable(node, p);
}
 
Example #3
Source File: Utilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static TreePath findOwningExecutable(TreePath from, boolean lambdaOrInitializer) {
    Tree.Kind k = null;
    
    OUTER: while (from != null && !(TreeUtilities.CLASS_TREE_KINDS.contains(k = from.getLeaf().getKind()))) {
        switch (k) {
            case METHOD:
                break OUTER;
            case LAMBDA_EXPRESSION:
                return lambdaOrInitializer ? from : null;
            case BLOCK: {
                TreePath par = from.getParentPath();
                Tree l = par.getLeaf();
                if (TreeUtilities.CLASS_TREE_KINDS.contains(l.getKind())) {
                    return lambdaOrInitializer ? from : null;
                }
            }
        }
        from = from.getParentPath();
    }
    return (from == null || k != Kind.METHOD) ?
            null : from;
}
 
Example #4
Source File: SessionSynchImplementedBySFSBOnly.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@TriggerTreeKind(Tree.Kind.CLASS)
public static Collection<ErrorDescription> run(HintContext hintContext) {
    final List<ErrorDescription> problems = new ArrayList<>();
    final EJBProblemContext ctx = HintsUtils.getOrCacheContext(hintContext);
    if (ctx == null) {
        return problems;
    }

    if (ctx.getEjb() instanceof Session) {
        if (Session.SESSION_TYPE_STATEFUL.equals(ctx.getEjbData().getSessionType())) {
            return problems; // OK, stateful session bean
        }
    }
    for (TypeMirror iface : ctx.getClazz().getInterfaces()) {
        String ifaceName = JavaUtils.extractClassNameFromType(iface);
        if (EJBAPIAnnotations.SESSION_SYNCHRONIZATION.equals(ifaceName)) {
            ErrorDescription err = HintsUtils.createProblem(ctx.getClazz(), hintContext.getInfo(), Bundle.SessionSynchImplementedBySFSBOnly_err());
            problems.add(err);
        }
    }

    return problems;
}
 
Example #5
Source File: MethodMetrics.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Hint(category = "metrics",
      displayName = "#DN_MethodTooComplex",
      description = "#DESC_MethodTooComplex",
      options = { Hint.Options.QUERY, Hint.Options.HEAVY },
      enabled = false
)
@TriggerTreeKind(Tree.Kind.METHOD)
@UseOptions(value = { OPTION_COMPLEXITY_TRESHOLD })
public static ErrorDescription methodTooComplex(HintContext ctx) {
    Tree t = ctx.getPath().getLeaf();
    MethodTree method = (MethodTree)t;
    CyclomaticComplexityVisitor v = new CyclomaticComplexityVisitor();
    v.scan(ctx.getPath(), v);
    int complexity = v.getComplexity();
    
    int treshold = ctx.getPreferences().getInt(OPTION_COMPLEXITY_TRESHOLD, DEFAULT_COMPLEXITY_LIMIT);
    if (complexity <= treshold) {
        return null;
    }
    return ErrorDescriptionFactory.forName(ctx, t, 
            methodOrConstructor(ctx) ?
            TEXT_ConstructorTooComplex(complexity) :
            TEXT_MethodTooComplex(method.getName().toString(), complexity)
    );
}
 
Example #6
Source File: Eval.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private Kind kindOfTree(Tree tree) {
    switch (tree.getKind()) {
        case IMPORT:
            return Kind.IMPORT;
        case VARIABLE:
            return Kind.VAR;
        case EXPRESSION_STATEMENT:
            return Kind.EXPRESSION;
        case CLASS:
        case ENUM:
        case ANNOTATION_TYPE:
        case INTERFACE:
            return Kind.TYPE_DECL;
        case METHOD:
            return Kind.METHOD;
        default:
            return Kind.STATEMENT;
    }
}
 
Example #7
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 #8
Source File: EntityManagerGenerationStrategySupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private String makeUnique(String methodName){
    List <? extends Tree> members=getClassTree().getMembers();
    String name=methodName;
    int add=1;
    boolean found=false;
    do
    {
        found=false;
        for(Tree membr:members) {
            if(Tree.Kind.METHOD.equals(membr.getKind())){
                MethodTree mt = membr instanceof MethodTree ? (MethodTree) membr : null;
                if(mt!=null && name.equals(mt.getName().toString())) {
                    found = true;
                    name = methodName + add++;
                }
            }
        }
    }while(found);
    return name;
}
 
Example #9
Source File: AbstractCodingRulesAnalyzer.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void finished(TaskEvent taskEvent) {
    if (taskEvent.getKind().equals(eventKind)) {
        TypeElement typeElem = taskEvent.getTypeElement();
        Tree tree = trees.getTree(typeElem);
        if (tree != null) {
            JavaFileObject prevSource = log.currentSourceFile();
            try {
                log.useSource(taskEvent.getCompilationUnit().getSourceFile());
                treeVisitor.scan((JCTree)tree);
            } finally {
                log.useSource(prevSource);
            }
        }
    }
}
 
Example #10
Source File: ElementOverlay.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private String fqnFor(Tree t) {
    Element el = ASTService.getElementImpl(t);

    if (el != null) {
        if (el.getKind().isClass() || el.getKind().isInterface() || el.getKind() == ElementKind.PACKAGE) {
            return ((QualifiedNameable) el).getQualifiedName().toString();
        } else {
            Logger.getLogger(ElementOverlay.class.getName()).log(Level.SEVERE, "Not a QualifiedNameable: {0}", el);
            return null;
        }
    } else if (t instanceof QualIdentTree) {
        return ((QualIdentTree) t).getFQN();
    } else if (t.getKind() == Kind.PARAMETERIZED_TYPE) {
        return fqnFor(((ParameterizedTypeTree) t).getType());
    } else {
        Logger.getLogger(ElementOverlay.class.getName()).log(Level.FINE, "No element and no QualIdent");
        return null;
    }
}
 
Example #11
Source File: DataFlow.java    From NullAway with MIT License 6 votes vote down vote up
private <A extends AbstractValue<A>, S extends Store<S>, T extends TransferFunction<A, S>>
    AnalysisResult<A, S> resultFor(TreePath exprPath, Context context, T transfer) {
  final TreePath enclosingPath =
      NullabilityUtil.findEnclosingMethodOrLambdaOrInitializer(exprPath);
  if (enclosingPath == null) {
    throw new RuntimeException("expression is not inside a method, lambda or initializer block!");
  }

  final Tree method = enclosingPath.getLeaf();
  if (method instanceof MethodTree && ((MethodTree) method).getBody() == null) {
    // expressions can occur in abstract methods, for example {@code Map.Entry} in:
    //
    //   abstract Set<Map.Entry<K, V>> entries();
    return null;
  }
  // Calling getValue() on the AnalysisResult (as opposed to calling it on the Analysis itself)
  // ensures we get the result for expr
  // *before* any unboxing operations (like invoking intValue() on an Integer).  This is
  // important,
  // e.g., for actually checking that the unboxing operation is legal.
  return dataflow(enclosingPath, context, transfer).getAnalysis().getResult();
}
 
Example #12
Source File: InterfaceServiceName.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override public ErrorDescription[] apply(TypeElement subject, ProblemContext ctx){
    if(subject.getKind() == ElementKind.INTERFACE) {
        AnnotationMirror annEntity = Utilities.findAnnotation(subject,ANNOTATION_WEBSERVICE);
        AnnotationTree annotationTree = (AnnotationTree) ctx.getCompilationInfo().
                getTrees().getTree(subject, annEntity);
        //serviceName not allowed
        if(Utilities.getAnnotationAttrValue(annEntity, ANNOTATION_ATTRIBUTE_SERVICE_NAME)!=null) {
            String label = NbBundle.getMessage(InterfaceServiceName.class, "MSG_IF_ServiceNameNotAllowed");
            Fix fix = new RemoveAnnotationArgument(ctx.getFileObject(),
                    subject, annEntity, ANNOTATION_ATTRIBUTE_SERVICE_NAME);
            Tree problemTree = Utilities.getAnnotationArgumentTree(annotationTree, ANNOTATION_ATTRIBUTE_SERVICE_NAME);
            ctx.setElementToAnnotate(problemTree);
            ErrorDescription problem = createProblem(subject, ctx, label, fix);
            ctx.setElementToAnnotate(null);
            return new ErrorDescription[]{problem};
        }
    }        
    return null;
}
 
Example #13
Source File: AbstractCodingRulesAnalyzer.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void finished(TaskEvent taskEvent) {
    if (taskEvent.getKind().equals(eventKind)) {
        TypeElement typeElem = taskEvent.getTypeElement();
        Tree tree = trees.getTree(typeElem);
        if (tree != null) {
            JavaFileObject prevSource = log.currentSourceFile();
            try {
                log.useSource(taskEvent.getCompilationUnit().getSourceFile());
                treeVisitor.scan((JCTree)tree);
            } finally {
                log.useSource(prevSource);
            }
        }
    }
}
 
Example #14
Source File: MethodExitDetector.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean visitIf(IfTree node, Stack<Tree> p) {
    scan(node.getCondition(), p);
    Boolean thenResult = scan(node.getThenStatement(), p);
    Boolean elseResult = scan(node.getElseStatement(), p);
    
    if (thenResult == Boolean.TRUE && elseResult == Boolean.TRUE)
        return Boolean.TRUE;
    
    return null;
}
 
Example #15
Source File: JpaControllerUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static ClassTree modifyDefaultConstructor(ClassTree classTree, ClassTree modifiedClassTree, WorkingCopy wc, MethodInfo modifiedConstructorInfo) {
    if (!"<init>".equals(modifiedConstructorInfo.getName())) {
        throw new IllegalArgumentException("modifiedConstructorInfo name must be <init>");
    }
    
    MethodTree modifiedConstructor = createMethod(wc, modifiedConstructorInfo);
    MethodTree constructor = null;
    for(Tree tree : modifiedClassTree.getMembers()) {
        if(Tree.Kind.METHOD == tree.getKind()) {
            MethodTree mtree = (MethodTree)tree;
            List<? extends VariableTree> mTreeParameters = mtree.getParameters();
            if(mtree.getName().toString().equals("<init>") &&
                    (mTreeParameters == null || mTreeParameters.isEmpty()) &&
                    !wc.getTreeUtilities().isSynthetic(wc.getTrees().getPath(wc.getCompilationUnit(), classTree))) {
                    constructor = mtree;
                    break;
            }
        }
    }
    if (constructor == null) {
        modifiedClassTree = wc.getTreeMaker().addClassMember(modifiedClassTree, modifiedConstructor);
    }
    else {
        wc.rewrite(constructor, modifiedConstructor);
    }
    return modifiedClassTree;
}
 
Example #16
Source File: JavaSourceHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Tree createParameterizedTypeTree(WorkingCopy copy, String type, String[] typeArgs) {
    TreeMaker maker = copy.getTreeMaker();
    Tree typeTree = createTypeTree(copy, type);
    List<ExpressionTree> typeArgTrees = new ArrayList<ExpressionTree>();

    for (String arg : typeArgs) {
        typeArgTrees.add((ExpressionTree) createTypeTree(copy, arg));
    }

    return maker.ParameterizedType(typeTree, typeArgTrees);
}
 
Example #17
Source File: DoNotReturnNullOptionals.java    From besu with Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(final Tree tree, final VisitorState state) {
  if ((tree instanceof ReturnTree) && (((ReturnTree) tree).getExpression() != null)) {
    return ((ReturnTree) tree).getExpression().getKind() == NULL_LITERAL;
  }
  return false;
}
 
Example #18
Source File: Eval.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private List<Snippet> processMethod(String userSource, Tree unitTree, String compileSource, ParseTask pt) {
    TreeDependencyScanner tds = new TreeDependencyScanner();
    tds.scan(unitTree);
    TreeDissector dis = TreeDissector.createByFirstClass(pt);

    MethodTree mt = (MethodTree) unitTree;
    String name = mt.getName().toString();
    String parameterTypes
            = mt.getParameters()
            .stream()
            .map(param -> dis.treeToRange(param.getType()).part(compileSource))
            .collect(Collectors.joining(","));
    Tree returnType = mt.getReturnType();
    DiagList modDiag = modifierDiagnostics(mt.getModifiers(), dis, true);
    MethodKey key = state.keyMap.keyForMethod(name, parameterTypes);
    // Corralling mutates.  Must be last use of pt, unitTree, mt
    Wrap corralled = new Corraller(key.index(), pt.getContext()).corralMethod(mt);

    if (modDiag.hasErrors()) {
        return compileFailResult(modDiag, userSource, Kind.METHOD);
    }
    Wrap guts = Wrap.classMemberWrap(compileSource);
    Range typeRange = dis.treeToRange(returnType);
    String signature = "(" + parameterTypes + ")" + typeRange.part(compileSource);

    Snippet snip = new MethodSnippet(key, userSource, guts,
            name, signature,
            corralled, tds.declareReferences(), tds.bodyReferences(), modDiag);
    return singletonList(snip);
}
 
Example #19
Source File: ExpressionScanner.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<Tree> visitSwitch(SwitchTree node, ExpressionScanner.ExpressionsInfo p) {
    List<Tree> result = null;
    if (acceptsTree(node)) {
        result = scan(node.getExpression(), p);
    }
    return reduce(result, scan(node.getCases(), p));
}
 
Example #20
Source File: JavaRefactoringUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Tree visitMemberSelect(MemberSelectTree node, ElementHandle p) {
    assert cc != null;
    Element e = p.resolve(cc);
    addIfMatch(getCurrentPath(), node, e);
    return super.visitMemberSelect(node, p);
}
 
Example #21
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 #22
Source File: ReferenceTransformer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void handleIdentifier(Tree node, Name id) {
    TreeMaker mk = copy.getTreeMaker();
    String nn = id.toString();
    if (nn.equals(name)) {
        Element res = copy.getTrees().getElement(getCurrentPath());
        if (res != null && res == shadowed) {
            if (res.getModifiers().contains(Modifier.STATIC)) {
                copy.rewrite(node, 
                        mk.MemberSelect(
                            mk.Identifier(shadowedGate), // NOI18N
                            res.getSimpleName().toString()
                        )
                );
            } else if (shadowedGate == target) {
                copy.rewrite(node, 
                        mk.MemberSelect(
                            mk.MemberSelect(mk.Identifier(target), "super"), // NOI18N
                            res.getSimpleName().toString()
                        )
                );
            } else {
                copy.rewrite(node, 
                        mk.MemberSelect(
                            mk.MemberSelect(mk.Identifier(shadowedGate), "this"), // NOI18N
                            res.getSimpleName().toString()
                        )
                );
            }
        }
    }
}
 
Example #23
Source File: ModelBuilder.java    From vertx-codetrans with Apache License 2.0 5 votes vote down vote up
@Override
public CodeModel visitForLoop(ForLoopTree node, VisitContext context) {
  if (node.getInitializer().size() != 1) {
    throw new UnsupportedOperationException();
  }
  if (node.getUpdate().size() != 1) {
    throw new UnsupportedOperationException();
  }
  StatementModel body = scan(node.getStatement(), context);
  if (node.getInitializer().size() == 1 &&
      node.getInitializer().get(0).getKind() == Tree.Kind.VARIABLE &&
      node.getCondition().getKind() == Tree.Kind.LESS_THAN &&
      node.getUpdate().size() == 1 &&
      node.getUpdate().get(0).getKind() == Tree.Kind.EXPRESSION_STATEMENT &&
      node.getUpdate().get(0).getExpression().getKind() == Tree.Kind.POSTFIX_INCREMENT) {
    VariableTree init = (VariableTree) node.getInitializer().get(0);
    BinaryTree lessThan = (BinaryTree) node.getCondition();
    UnaryTree increment = (UnaryTree) node.getUpdate().get(0).getExpression();
    if (lessThan.getLeftOperand().getKind() == Tree.Kind.IDENTIFIER &&
        increment.getExpression().getKind() == Tree.Kind.IDENTIFIER) {
      String id1 = init.getName().toString();
      String id2 = ((IdentifierTree) lessThan.getLeftOperand()).getName().toString();
      String id3 = ((IdentifierTree) increment.getExpression()).getName().toString();
      if (id1.equals(id2) && id2.equals(id3)) {
        ExpressionModel from = scan(init.getInitializer(), context);
        ExpressionModel to = scan(lessThan.getRightOperand(), context);
        return context.builder.sequenceForLoop(id1, from, to, body);
      }
    }
  }
  StatementModel initializer = scan(node.getInitializer().get(0), context);
  ExpressionModel update = scan(node.getUpdate().get(0).getExpression(), context);
  ExpressionModel condition = scan(node.getCondition(), context);
  return context.builder.forLoop(initializer, condition, update, body);
}
 
Example #24
Source File: InterfaceExtendsTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testRemoveTwoExtends() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n\n" +
        "import java.util.*;\n\n" +
        "public interface Test extends Serializable, Externalizable {\n" +
        "    public void taragui();\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "import java.util.*;\n\n" +
        "public interface Test {\n" +
        "    public void taragui();\n" +
        "}\n";
    JavaSource src = getJavaSource(testFile);
    
    Task task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();

            for (Tree typeDecl : cut.getTypeDecls()) {
                // ensure that it is correct type declaration, i.e. class
                if (TreeUtilities.CLASS_TREE_KINDS.contains(typeDecl.getKind())) {
                    ClassTree classTree = (ClassTree) typeDecl;
                    ClassTree copy = make.removeClassImplementsClause(classTree, 0);
                    copy = make.removeClassImplementsClause(copy, 0);
                    workingCopy.rewrite(classTree, copy);
                }
            }
        }
        
    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    assertEquals(golden, res);
}
 
Example #25
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
/**
 * The parser expands multi-variable declarations into separate single-variable declarations. All
 * of the fragments in the original declaration have the same start position, so we use that as a
 * signal to collect them and preserve the multi-variable declaration in the output.
 *
 * <p>e.g. {@code int x, y;} is parsed as {@code int x; int y;}.
 */
private List<VariableTree> variableFragments(PeekingIterator<? extends Tree> it, Tree first) {
  List<VariableTree> fragments = new ArrayList<>();
  if (first.getKind() == VARIABLE) {
    int start = getStartPosition(first);
    fragments.add((VariableTree) first);
    while (it.hasNext()
        && it.peek().getKind() == VARIABLE
        && getStartPosition(it.peek()) == start) {
      fragments.add((VariableTree) it.next());
    }
  }
  return fragments;
}
 
Example #26
Source File: Messages.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
protected void report(Group group, Diagnostic.Kind dkind, Tree tree, String code, Object... args) {
    if (options.isEnabled(group, env.currAccess)) {
        String msg = localize(code, args);
        env.trees.printMessage(dkind, msg, tree, env.currPath.getCompilationUnit());

        stats.record(group, dkind, code);
    }
}
 
Example #27
Source File: FieldEncapsulation.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static TypeElement getEnclosingClass (TreePath path, final Trees trees) {
    while (path != null && path.getLeaf().getKind() != Tree.Kind.COMPILATION_UNIT) {
        if (TreeUtilities.CLASS_TREE_KINDS.contains(path.getLeaf().getKind())) {
            return (TypeElement) trees.getElement(path);
        }
        path = path.getParentPath();
    }
    return null;
}
 
Example #28
Source File: TreeShims.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Tree SwitchExpression(TreeMaker make, ExpressionTree selector, List<? extends CaseTree> caseList) throws SecurityException {
    ListBuffer<JCTree.JCCase> cases = new ListBuffer<JCTree.JCCase>();
    for (CaseTree t : caseList) {
        cases.append((JCTree.JCCase) t);
    }
    try {
        Method getMethod = TreeMaker.class.getDeclaredMethod("SwitchExpression", JCTree.JCExpression.class, com.sun.tools.javac.util.List.class);
        return (Tree) getMethod.invoke(make, (JCTree.JCExpression) selector, cases.toList());
    } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
        throw TreeShims.<RuntimeException>throwAny(ex);
    }
}
 
Example #29
Source File: RenameTestClassPluginFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public RefactoringPlugin createInstance(AbstractRefactoring refactoring) {
    if (refactoring instanceof RenameRefactoring) {
        EnumSet<Tree.Kind> supported = EnumSet.of(Tree.Kind.CLASS, Tree.Kind.ENUM, Tree.Kind.INTERFACE, Tree.Kind.METHOD);
        TreePathHandle handle = refactoring.getRefactoringSource().lookup(TreePathHandle.class);
        if (handle!=null && supported.contains(handle.getKind())) {
            return new RenameTestClassRefactoringPlugin((RenameRefactoring) refactoring);
        }
    }
    return null;
}
 
Example #30
Source File: PullUpRefactoringUI.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static TreePath findSelectedClassMemberDeclaration(final TreePath path, final CompilationInfo javac) {
    TreePath currentPath = path;
    TreePath selection = null;
    while (currentPath != null && selection == null) {
        switch (currentPath.getLeaf().getKind()) {
            case ANNOTATION_TYPE:
            case CLASS:
            case ENUM:
            case INTERFACE:
            case NEW_CLASS:
            case METHOD:
                selection = currentPath;
                break;
            case VARIABLE:
                Element elm = javac.getTrees().getElement(currentPath);
                if (elm != null && elm.getKind().isField()) {
                    selection = currentPath;
                }
                break;
        }
        if (selection != null && javac.getTreeUtilities().isSynthetic(selection)) {
            selection = null;
        }
        if (selection == null) {
            currentPath = currentPath.getParentPath();
        }
    }
    
    if (selection == null && path != null) {
        List<? extends Tree> typeDecls = path.getCompilationUnit().getTypeDecls();
        if (!typeDecls.isEmpty() && typeDecls.get(0).getKind().asInterface() == ClassTree.class) {
            selection = TreePath.getPath(path.getCompilationUnit(), typeDecls.get(0));
        }
    }
    return selection;
}