Java Code Examples for com.sun.source.tree.Tree

The following examples show how to use com.sun.source.tree.Tree. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: netbeans   Source File: Utilities.java    License: 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 2
Source Project: javaide   Source File: JavaInputAstVisitor.java    License: GNU General Public License v3.0 6 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 3
Source Project: netbeans   Source File: NCLOCVisitor.java    License: 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 4
Source Project: netbeans   Source File: ElementOverlay.java    License: 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 5
Source Project: openjdk-jdk9   Source File: Eval.java    License: 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 6
@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 7
Source Project: netbeans   Source File: MethodMetrics.java    License: 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 8
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 Project: NullAway   Source File: DataFlow.java    License: 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 10
@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 11
Source Project: netbeans   Source File: InterfaceServiceName.java    License: 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 12
Source Project: netbeans   Source File: Braces.java    License: 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 13
@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 14
Source Project: besu   Source File: DoNotReturnNullOptionals.java    License: 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 15
Source Project: netbeans   Source File: AnnotationProcessors.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks if the annotation types are reachable, initializes
 * types and elements for the API types.
 * @return false if the code is not in good shape.
 */
public boolean initialize() {
    Element e = info.getTrees().getElement(processorPath);
    if (e == null || e.getKind() != ElementKind.CLASS) {
        return false;
    }
    processor = (TypeElement)e;
    if (processorPath.getLeaf().getKind() != Tree.Kind.CLASS) {
        return false;
    }

    abstractProcessor = info.getElements().getTypeElement(ABSTRACT_PROCESSOR_TYPE);
    if (!Utilities.isValidElement(abstractProcessor)) {
        return false;
    }
    abstractProcessorType = abstractProcessor.asType();
    baseProcessor = info.getElements().getTypeElement(PROCESSOR_TYPE);
    if (!Utilities.isValidElement(baseProcessor)) {
        return false;
    }
    baseProcessorType = baseProcessor.asType();
    supportedSource = info.getElements().getTypeElement(SUPPORTED_SOURCE_TYPE);
    if (!Utilities.isValidElement(supportedSource)) {
        return false;
    }
    supportedSourceType = supportedSource.asType();
    if (!Utilities.isValidType(supportedSourceType)) {
        return false;
    }
    ExecutableElement ee = findGetSupported(abstractProcessor);
    if (ee == null) {
        return false;
    }
    abstractGetSupported = ee;
    
    return info.getTypes().isSubtype(processor.asType(), abstractProcessor.getSuperclass());
}
 
Example 16
Source Project: netbeans   Source File: PointlessBitwiseExpression.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    TreePath tp = ctx.getPath();
    Tree vt = tp.getLeaf();
    BinaryTree e = (BinaryTree) vt;
    wc.rewrite (vt, left ? e.getLeftOperand () : e.getRightOperand ());
}
 
Example 17
/** Return true iff this tree is a child of some annotation. */
public static boolean isInAnnotation(Env<?> env, JCTree tree) {
    TreePath tp = TreePath.getPath(env.toplevel, tree);
    if (tp != null) {
        for (Tree t : tp) {
            if (t.getKind() == Tree.Kind.ANNOTATION)
                return true;
        }
    }
    return false;
}
 
Example 18
@Override
public Tree visitVariable(VariableTree variableDeclTree, Trees trees) {

    //check for shadowed variable
    if (shadowsVariable(variableDeclTree.getName())) {
        foundShadowedVariable = true;
    }
    return super.visitVariable(variableDeclTree, trees);
}
 
Example 19
Source Project: netbeans   Source File: TreeUtilitiesTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testIsEnumConstant() throws Exception {
    prepareTest("Test", "package test; public enum Test {B; private static final int ii = 0;}");
    ClassTree clazz = (ClassTree) info.getCompilationUnit().getTypeDecls().get(0);
    Tree b = clazz.getMembers().get(1);
    assertTrue(info.getTreeUtilities().isEnumConstant((VariableTree) b));
    Tree ii = clazz.getMembers().get(2);
    assertFalse(info.getTreeUtilities().isEnumConstant((VariableTree) ii));
}
 
Example 20
Source Project: netbeans   Source File: ControllerGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isUsed(Tree memberTree, ModifiersTree mods) {
    if (!mods.getFlags().contains(Modifier.PRIVATE)) {
        // I don't want to search the world, better to ignore
        return true;
    }
    TreePath t = new TreePath(getControllerPath(), memberTree);
    TreePathHandle hnd = TreePathHandle.create(t, wcopy);
    WhereUsedQuery a = new WhereUsedQuery(Lookups.fixed(hnd));
    RefactoringSession session = RefactoringSession.create("Find usages");
    a.prepare(session);
    boolean used = !session.getRefactoringElements().isEmpty();
    session.finished();
    
    return used;
}
 
Example 21
Source Project: netbeans   Source File: CancellableTreeScanner.java    License: Apache License 2.0 5 votes vote down vote up
/** @inheritDoc
 */
public R scan(Iterable<? extends Tree> trees, P p) {
    if (isCanceled())
        return null;
    
    return super.scan(trees, p);
}
 
Example 22
Source Project: netbeans   Source File: FmtCodeGeneration.java    License: 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);
}
 
Example 23
Source Project: compile-testing   Source File: BreadcrumbsTest.java    License: Apache License 2.0 5 votes vote down vote up
private LiteralTree literalTree() {
   // Checked implicitly in CompilationTestUtils by Tree.Kind parameter
  @SuppressWarnings("unchecked")
  LiteralTree ret =
      (LiteralTree) MoreTrees.findSubtree(baseTree(), Tree.Kind.STRING_LITERAL, "literal");
  return ret;
}
 
Example 24
List<String> getErroneousTreeValues(ErroneousTree node) {

        List<String> values = new ArrayList<>();
        if (node.getErrorTrees() != null) {
            for (Tree t : node.getErrorTrees()) {
                values.add(t.toString());
            }
        } else {
            throw new RuntimeException("ERROR: No Erroneous tree "
                    + "has been created.");
        }
        return values;
    }
 
Example 25
Source Project: buck   Source File: TreeContextScanner.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public R scan(Tree tree, @Nullable P p) {
  if (tree == null) {
    return null;
  }

  TreePath previousPath = currentPath;
  Element previousEnclosingElement = enclosingElement;

  currentPath = new TreePath(currentPath, tree);
  switch (tree.getKind()) {
    case ANNOTATION_TYPE:
    case CLASS:
    case COMPILATION_UNIT:
    case ENUM:
    case INTERFACE:
    case METHOD:
    case VARIABLE:
    case TYPE_PARAMETER:
      enclosingElement = Objects.requireNonNull(trees.getElement(currentPath));
      break;
      // $CASES-OMITTED$
    default:
      break;
  }
  try {
    // This super call will actually visit the tree, now with all the context set up
    return super.scan(tree, p);
  } finally {
    currentPath = previousPath;
    enclosingElement = previousEnclosingElement;
  }
}
 
Example 26
Source Project: netbeans   Source File: LegalCombinationOfAnnotations.java    License: Apache License 2.0 5 votes vote down vote up
void check(ProblemContext ctx,
        HintContext hc,
        Element elem,
        Collection<ErrorDescription> errorList,
        Collection<String> annotations) {

    for (String ann : annotations) {
        if (set1.contains(ann)) {
            for (String forbiddenAnn : set2) {
                if (annotations.contains(forbiddenAnn)) {
                    Tree elementTree = ctx.getCompilationInfo().getTrees().getTree(elem);

                    Utilities.TextSpan underlineSpan = Utilities.getUnderlineSpan(
                            ctx.getCompilationInfo(), elementTree);

                    ErrorDescription error = ErrorDescriptionFactory.forSpan(
                            hc,
                            underlineSpan.getStartOffset(),
                            underlineSpan.getEndOffset(),
                            NbBundle.getMessage(LegalCombinationOfAnnotations.class, "MSG_IllegalAnnotationCombination", ModelUtils.shortAnnotationName(ann), ModelUtils.shortAnnotationName(forbiddenAnn)));

                    errorList.add(error);
                }
            }
        }
    }
}
 
Example 27
Source Project: compile-testing   Source File: TreeDiffer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Void visitTry(TryTree expected, Tree actual) {
  Optional<TryTree> other = checkTypeAndCast(expected, actual);
  if (!other.isPresent()) {
    addTypeMismatch(expected, actual);
    return null;
  }

  scan(expected.getBlock(), other.get().getBlock());
  parallelScan(expected.getCatches(), other.get().getCatches());
  scan(expected.getFinallyBlock(), other.get().getFinallyBlock());
  return null;
}
 
Example 28
Source Project: annotation-tools   Source File: ParamCriterion.java    License: MIT License 5 votes vote down vote up
@Override
public boolean isSatisfiedBy(TreePath path) {

  if (path == null) {
    return false;
  }

  // no inner type location, want to annotate outermost type
  // i.e.   @Nullable List list;
  //        @Nullable List<String> list;
  Tree leaf = path.getLeaf();
  if (leaf instanceof VariableTree) {
    Tree parent = path.getParentPath().getLeaf();
    List<? extends VariableTree> params;
    switch (parent.getKind()) {
    case METHOD:
      params = ((MethodTree) parent).getParameters();
      break;
    case LAMBDA_EXPRESSION:
      params = ((LambdaExpressionTree) parent).getParameters();
      break;
    default:
      params = null;
      break;
    }
    return params != null && params.size() > paramPos
        && params.get(paramPos).equals(leaf);
  }

  return this.isSatisfiedBy(path.getParentPath());
}
 
Example 29
Source Project: netbeans   Source File: Move.java    License: Apache License 2.0 5 votes vote down vote up
private ExpressionTree transformInitializer(ExpressionTree initializer, Tree type, TreeMaker make) {
    if(initializer.getKind() == Tree.Kind.NEW_ARRAY) {
        NewArrayTree nat = (NewArrayTree) initializer;
        if(nat.getType() == null) {
            if(type.getKind() == Tree.Kind.ARRAY_TYPE) {
                ArrayTypeTree arrayTypeTree = (ArrayTypeTree) type;
                type = arrayTypeTree.getType();
            }
            return make.NewArray(type, nat.getDimensions(), nat.getInitializers());
        }
    }
    return initializer;
}
 
Example 30
Source Project: compile-testing   Source File: TreeDiffer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Void visitReturn(ReturnTree expected, Tree actual) {
  Optional<ReturnTree> other = checkTypeAndCast(expected, actual);
  if (!other.isPresent()) {
    addTypeMismatch(expected, actual);
    return null;
  }

  scan(expected.getExpression(), other.get().getExpression());
  return null;
}