@Nullable private static JCMethodDecl findSurroundingMethod(TreePath path) { while (path.getLeaf().getKind() != Kind.METHOD) { if (path.getLeaf().getKind() == Kind.LAMBDA_EXPRESSION) { // Ignore return statements in lambda expressions. There's no method declaration to suggest // annotations for anyway. return null; } path = path.getParentPath(); } return (JCMethodDecl) path.getLeaf(); } }
/** * Given a TreePath, finds the first enclosing node of the given type and returns the path from * the enclosing node to the top-level {@code CompilationUnitTree}. */ public static <T> TreePath findPathFromEnclosingNodeToTopLevel(TreePath path, Class<T> klass) { if (path != null) { do { path = path.getParentPath(); } while (path != null && !(klass.isInstance(path.getLeaf()))); } return path; }
private static boolean isInPrivateScope(VisitorState state) { TreePath treePath = state.getPath(); do { Tree currentLeaf = treePath.getLeaf(); if (currentLeaf instanceof ClassTree) { ClassTree currentClassTree = (ClassTree) currentLeaf; if (currentClassTree.getModifiers().getFlags().contains(PRIVATE)) { return true; } } treePath = treePath.getParentPath(); } while (treePath != null); return false; } }
@Override public IdentifierTree visitIdentifier(IdentifierTree node, Void aVoid) { Symbol nodeSymbol = ASTHelpers.getSymbol(node); if (symbols.contains(nodeSymbol) && !isSuppressed(node)) { if (getCurrentPath().getParentPath().getLeaf().getKind() != Kind.CASE) { builder.prefixWith(node, enclosingReplacement); moveTypeAnnotations(node); return node; } } return super.visitIdentifier(node, aVoid); }
private boolean relevantInitializerMethodOrBlock( TreePath enclosingBlockPath, VisitorState state) { Tree methodLambdaOrBlock = enclosingBlockPath.getLeaf(); if (methodLambdaOrBlock instanceof LambdaExpressionTree) { return false; } else if (methodLambdaOrBlock instanceof MethodTree) { MethodTree methodTree = (MethodTree) methodLambdaOrBlock; if (isConstructor(methodTree) && !constructorInvokesAnother(methodTree, state)) return true; if (ASTHelpers.getSymbol(methodTree).isStatic()) { Set<MethodTree> staticInitializerMethods = class2Entities.get(enclosingClassSymbol(enclosingBlockPath)).staticInitializerMethods(); return staticInitializerMethods.size() == 1 && staticInitializerMethods.contains(methodTree); } else { Set<MethodTree> instanceInitializerMethods = class2Entities .get(enclosingClassSymbol(enclosingBlockPath)) .instanceInitializerMethods(); return instanceInitializerMethods.size() == 1 && instanceInitializerMethods.contains(methodTree); } } else { // initializer or field declaration return true; } }
private void typeUsed(Element decl, TreePath expr, boolean methodInvocation) { if (decl != null && (expr == null || expr.getLeaf().getKind() == Kind.IDENTIFIER || expr.getLeaf().getKind() == Kind.PARAMETERIZED_TYPE)) { if (!isErroneous(decl)) { ImportTree imp = element2Import.get(decl); if (imp != null) { addUsage(imp); if (isStar(imp)) { //TODO: explain handleUnresolvableImports(decl, methodInvocation, false); } } } else { handleUnresolvableImports(decl, methodInvocation, true); for (Entry<Element, ImportTree> e : element2Import.entrySet()) { if (importedBySingleImport.contains(e.getKey())) continue; if (e.getKey().getSimpleName().equals(decl.getSimpleName())) { import2Highlight.remove(e.getValue()); } } } } }
@Override public void onMatchReturn(NullAway analysis, ReturnTree tree, VisitorState state) { // Figure out the enclosing method node TreePath enclosingMethodOrLambda = NullabilityUtil.findEnclosingMethodOrLambdaOrInitializer(state.getPath()); if (enclosingMethodOrLambda == null) { throw new RuntimeException("no enclosing method, lambda or initializer!"); } if (!(enclosingMethodOrLambda.getLeaf() instanceof MethodTree || enclosingMethodOrLambda.getLeaf() instanceof LambdaExpressionTree)) { throw new RuntimeException( "return statement outside of a method or lambda! (e.g. in an initializer block)"); } Tree leaf = enclosingMethodOrLambda.getLeaf(); if (filterMethodOrLambdaSet.contains(leaf)) { returnToEnclosingMethodOrLambda.put(tree, leaf); // We need to manually trigger the dataflow analysis to run on the filter method, // this ensures onDataflowVisitReturn(...) gets called for all return statements in this // method before // onDataflowInitialStore(...) is called for all successor methods in the observable chain. // Caching should prevent us from re-analyzing any given method. AccessPathNullnessAnalysis nullnessAnalysis = analysis.getNullnessAnalysis(state); nullnessAnalysis.forceRunOnMethod(new TreePath(state.getPath(), leaf), state.context); } }
public static ErrorDescription computeWarning(HintContext context) { final TreePath tp = context.getPath(); final MethodTree method = (MethodTree) tp.getLeaf(); if (method.getModifiers().getFlags().contains(Modifier.PRIVATE)) { return null; SourcePositions sourcePositions = info.getTrees().getSourcePositions(); int startPos = (int) sourcePositions.getStartPosition(tp.getCompilationUnit(), method); int caret = context.getCaretLocation();
private boolean canSkip(TreePath path) { if (cinfo.getTreeUtilities().isSynthetic(path)) { return false; } Element el = cinfo.getTrees().getElement(path); if (el != null && elementAndNames.containsKey(el)) { TreePath declPath = cinfo.getTrees().getPath(el); if(declPath.getLeaf().equals(path.getLeaf())) { return true; } } return false; }
path = new TreePath(taskEvent.getCompilationUnit()); verify(seen.add(path.getLeaf()), "Duplicate FLOW event for: %s", taskEvent.getTypeElement()); Context subContext = new SubContext(context); subContext.put(ErrorProneOptions.class, errorProneOptions); return; if (path.getLeaf().getKind() == Tree.Kind.COMPILATION_UNIT) { transformer.get().apply(new TreePath(compilation), subContext, countingDescriptionListener);
private static ExpressionTree findImplementIdentifier (Trees trees, TreePath classTreePath, String fullyQualifiedName) { ClassTree clazz = (ClassTree) classTreePath.getLeaf (); for (Tree tree : clazz.getImplementsClause ()) { Element element = trees.getElement (new TreePath (classTreePath, tree)); if (equalsElementWithFQN (element, fullyQualifiedName)) return (ExpressionTree) tree; } return null; }
/** */ public void handleDeclaration() { Element found = trees.getElement(getCurrentPath()); if (element.equals(found)) { declTree = getCurrentPath().getLeaf(); } }
public static ErrorDescription computeWarning(HintContext context) { TreePath tp = context.getPath(); ClassTree cls = (ClassTree) tp.getLeaf(); CompilationInfo info = context.getInfo(); SourcePositions sourcePositions = info.getTrees().getSourcePositions(); int startPos = (int) sourcePositions.getStartPosition(tp.getCompilationUnit(), cls); int caret = context.getCaretLocation();
@Override public Description matchVariable(VariableTree tree, VisitorState state) { ExpressionTree initializer = stripNullCheck(tree.getInitializer(), state); Tree parent = state.getPath().getParentPath().getLeaf(); // must be a static class variable with member select initializer if (initializer == null || initializer.getKind() != MEMBER_SELECT || parent.getKind() != CLASS || !tree.getModifiers().getFlags().contains(STATIC)) { return Description.NO_MATCH; } MemberSelectTree rhs = (MemberSelectTree) initializer; Symbol rhsClass = ASTHelpers.getSymbol(rhs.getExpression()); Symbol lhsClass = ASTHelpers.getSymbol(parent); if (rhsClass != null && lhsClass != null && rhsClass.equals(lhsClass) && rhs.getIdentifier().contentEquals(tree.getName())) { return describeForVarDecl(tree, state); } return Description.NO_MATCH; }
while (path != null && !(path.getLeaf() instanceof MethodTree)) { path = path.getParentPath(); MethodTree methodDecl = (MethodTree) path.getLeaf(); for (VariableTree param : methodDecl.getParameters()) { if (symbols.contains(ASTHelpers.getSymbol(param))) { return true;
return NO_MATCH; if (!requiresJavadoc(docTreePath.getTreePath().getLeaf(), state)) { return Description.NO_MATCH; return NO_MATCH; Symbol symbol = getSymbol(docTreePath.getTreePath().getLeaf()); if (symbol == null) { return NO_MATCH; if (!modifiers.contains(Modifier.PUBLIC) && !modifiers.contains(Modifier.PROTECTED)) { return NO_MATCH;
public static LinkedList<Diff> reformat(String text, TokenSequence<JavaTokenId> tokens, TreePath path, SourcePositions sp, CodeStyle cs, int rightMargin) { Pretty pretty = new Pretty(text, tokens, path, sp, cs, 0, text.length(), rightMargin); pretty.scan(path, null); CompilationUnitTree cut = (CompilationUnitTree) path.getLeaf(); List<? extends Tree> typeDecls = cut.getTypeDecls(); int size = typeDecls.size(); int cnt = size > 0 && org.netbeans.api.java.source.TreeUtilities.CLASS_TREE_KINDS.contains(typeDecls.get(size - 1).getKind()) ? cs.getBlankLinesAfterClass() : 1; if (cnt < 1) cnt = 1; String s = pretty.getNewlines(cnt); tokens.moveEnd(); tokens.movePrevious(); if (tokens.token().id() != WHITESPACE) pretty.diffs.addFirst(new Diff(text.length(), text.length(), s)); else if (!s.contentEquals(tokens.token().text())) pretty.diffs.addFirst(new Diff(tokens.offset(), tokens.offset() + tokens.token().length(), s)); return pretty.diffs; }
private static boolean isPartOfMethodInvocation(TreePath idPath) { Kind parentKind = idPath.getParentPath().getLeaf().getKind(); if (parentKind == Kind.METHOD_INVOCATION) { // must be an argument return true; } if (parentKind == Kind.MEMBER_SELECT) { Tree maybeMethodInvocation = idPath.getParentPath().getParentPath().getLeaf(); // likely the target of the method invocation return maybeMethodInvocation.getKind() == Kind.METHOD_INVOCATION; } return false; }
private static boolean isEnhancedForLoopVar(TreePath variablePath) { Tree tree = variablePath.getLeaf(); Tree parent = variablePath.getParentPath().getLeaf(); return parent instanceof EnhancedForLoopTree && ((EnhancedForLoopTree) parent).getVariable() == tree; }
public void handleDeclaration() { Element found = info.getTrees().getElement(getCurrentPath()); if ( element.equals( found ) ) { declTree = getCurrentPath().getLeaf(); } }