[AST] Allow limiting the scope of common AST traversals (getParents, RAV).
authorSam McCall <sam.mccall@gmail.com>
Wed, 14 Nov 2018 10:33:30 +0000 (10:33 +0000)
committerSam McCall <sam.mccall@gmail.com>
Wed, 14 Nov 2018 10:33:30 +0000 (10:33 +0000)
commit814e7974c64c977960c4913a117bf59af005865b
tree6c8d41ff6c78bfe57a649b4f1d3684ae72a63cca
parent49037d2b3c1bcae55cc3ec48034c9ab355cc17e0
[AST] Allow limiting the scope of common AST traversals (getParents, RAV).

Summary:
The goal is to allow analyses such as clang-tidy checks to run on a
subset of the AST, e.g. "only on main-file decls" for interactive tools.

Today, these become "problematically global" by running RecursiveASTVisitors
rooted at the TUDecl, or by navigating up via ASTContext::getParent().

The scope is restricted using a set of top-level-decls that RecursiveASTVisitors
should be rooted at. This also applies to the visitor that populates the
parent map, and so the top-level-decls are considered to have no parents.

This patch makes the traversal scope a mutable property of ASTContext.
The more obvious way to do this is to pass the top-level decls to
relevant functions directly, but this has some problems:
 - it's error-prone: accidentally mixing restricted and unrestricted
   scopes is a performance trap. Interleaving multiple analyses is
   common (many clang-tidy checks run matchers or RAVs from matcher callbacks)
 - it doesn't map well to the actual use cases, where we really do want
   *all* traversals to be restricted.
 - it involves a lot of plumbing in parts of the code that don't care
   about traversals.
This approach was tried out in D54259 and D54261, I wanted to like it
but it feels pretty awful in practice.

Caveats: to get scope-limiting behavior of RecursiveASTVisitors, callers
have to call the new TraverseAST(Ctx) function instead of TraverseDecl(TU).
I think this is an improvement to the API regardless.

Reviewers: klimek, ioeric

Subscribers: mgorny, cfe-commits

Differential Revision: https://reviews.llvm.org/D54309

llvm-svn: 346847
clang/include/clang/AST/ASTContext.h
clang/include/clang/AST/RecursiveASTVisitor.h
clang/lib/AST/ASTContext.cpp
clang/lib/ASTMatchers/ASTMatchFinder.cpp
clang/unittests/AST/ASTContextParentMapTest.cpp
clang/unittests/Tooling/CMakeLists.txt
clang/unittests/Tooling/RecursiveASTVisitorTests/TraversalScope.cpp [new file with mode: 0644]