blob: 38df2a199bdeac220bfb82c2ecbfae548874666a [file] [log] [blame]
Manuel Klimek4da21662012-07-06 05:48:52 +00001//===--- ASTMatchFinder.cpp - Structural query framework ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Implements an algorithm to efficiently search for matches on AST nodes.
11// Uses memoization to support recursive matches like HasDescendant.
12//
13// The general idea is to visit all AST nodes with a RecursiveASTVisitor,
14// calling the Matches(...) method of each matcher we are running on each
15// AST node. The matcher can recurse via the ASTMatchFinder interface.
16//
17//===----------------------------------------------------------------------===//
18
19#include "clang/ASTMatchers/ASTMatchFinder.h"
20#include "clang/AST/ASTConsumer.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/RecursiveASTVisitor.h"
23#include <set>
24
25namespace clang {
26namespace ast_matchers {
27namespace internal {
28namespace {
29
Manuel Klimeka78d0d62012-09-05 12:12:07 +000030typedef MatchFinder::MatchCallback MatchCallback;
31
Manuel Klimek579b1202012-09-07 09:26:10 +000032/// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
33/// parents as defined by the \c RecursiveASTVisitor.
34///
35/// Note that the relationship described here is purely in terms of AST
36/// traversal - there are other relationships (for example declaration context)
37/// in the AST that are better modeled by special matchers.
38///
39/// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
40class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
41public:
42 /// \brief Maps from a node to its parent.
43 typedef llvm::DenseMap<const void*, ast_type_traits::DynTypedNode> ParentMap;
44
45 /// \brief Builds and returns the translation unit's parent map.
46 ///
47 /// The caller takes ownership of the returned \c ParentMap.
48 static ParentMap *buildMap(TranslationUnitDecl &TU) {
49 ParentMapASTVisitor Visitor(new ParentMap);
50 Visitor.TraverseDecl(&TU);
51 return Visitor.Parents;
52 }
53
54private:
55 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
56
57 ParentMapASTVisitor(ParentMap *Parents) : Parents(Parents) {}
58
59 bool shouldVisitTemplateInstantiations() const { return true; }
60 bool shouldVisitImplicitCode() const { return true; }
61
62 template <typename T>
63 bool TraverseNode(T *Node, bool (VisitorBase::*traverse)(T*)) {
64 if (Node == NULL)
65 return true;
66 if (ParentStack.size() > 0)
67 (*Parents)[Node] = ParentStack.back();
68 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
69 bool Result = (this->*traverse)(Node);
70 ParentStack.pop_back();
71 return Result;
72 }
73
74 bool TraverseDecl(Decl *DeclNode) {
75 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
76 }
77
78 bool TraverseStmt(Stmt *StmtNode) {
79 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
80 }
81
82 ParentMap *Parents;
83 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
84
85 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
86};
87
Manuel Klimek4da21662012-07-06 05:48:52 +000088// We use memoization to avoid running the same matcher on the same
89// AST node twice. This pair is the key for looking up match
90// result. It consists of an ID of the MatcherInterface (for
91// identifying the matcher) and a pointer to the AST node.
Manuel Klimeka78d0d62012-09-05 12:12:07 +000092//
93// We currently only memoize on nodes whose pointers identify the
94// nodes (\c Stmt and \c Decl, but not \c QualType or \c TypeLoc).
95// For \c QualType and \c TypeLoc it is possible to implement
96// generation of keys for each type.
97// FIXME: Benchmark whether memoization of non-pointer typed nodes
98// provides enough benefit for the additional amount of code.
Manuel Klimek4da21662012-07-06 05:48:52 +000099typedef std::pair<uint64_t, const void*> UntypedMatchInput;
100
101// Used to store the result of a match and possibly bound nodes.
102struct MemoizedMatchResult {
103 bool ResultOfMatch;
104 BoundNodesTree Nodes;
105};
106
107// A RecursiveASTVisitor that traverses all children or all descendants of
108// a node.
109class MatchChildASTVisitor
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000110 : public RecursiveASTVisitor<MatchChildASTVisitor> {
Manuel Klimek4da21662012-07-06 05:48:52 +0000111public:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000112 typedef RecursiveASTVisitor<MatchChildASTVisitor> VisitorBase;
Manuel Klimek4da21662012-07-06 05:48:52 +0000113
114 // Creates an AST visitor that matches 'matcher' on all children or
115 // descendants of a traversed node. max_depth is the maximum depth
116 // to traverse: use 1 for matching the children and INT_MAX for
117 // matching the descendants.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000118 MatchChildASTVisitor(const DynTypedMatcher *Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000119 ASTMatchFinder *Finder,
120 BoundNodesTreeBuilder *Builder,
121 int MaxDepth,
122 ASTMatchFinder::TraversalKind Traversal,
123 ASTMatchFinder::BindKind Bind)
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000124 : Matcher(Matcher),
Manuel Klimek4da21662012-07-06 05:48:52 +0000125 Finder(Finder),
126 Builder(Builder),
Daniel Jaspera267cf62012-10-29 10:14:44 +0000127 CurrentDepth(0),
Manuel Klimek4da21662012-07-06 05:48:52 +0000128 MaxDepth(MaxDepth),
129 Traversal(Traversal),
130 Bind(Bind),
131 Matches(false) {}
132
133 // Returns true if a match is found in the subtree rooted at the
134 // given AST node. This is done via a set of mutually recursive
135 // functions. Here's how the recursion is done (the *wildcard can
136 // actually be Decl, Stmt, or Type):
137 //
138 // - Traverse(node) calls BaseTraverse(node) when it needs
139 // to visit the descendants of node.
140 // - BaseTraverse(node) then calls (via VisitorBase::Traverse*(node))
141 // Traverse*(c) for each child c of 'node'.
142 // - Traverse*(c) in turn calls Traverse(c), completing the
143 // recursion.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000144 bool findMatch(const ast_type_traits::DynTypedNode &DynNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000145 reset();
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000146 if (const Decl *D = DynNode.get<Decl>())
147 traverse(*D);
148 else if (const Stmt *S = DynNode.get<Stmt>())
149 traverse(*S);
Daniel Jaspera267cf62012-10-29 10:14:44 +0000150 else if (const QualType *Q = DynNode.get<QualType>())
151 traverse(*Q);
152 else if (const TypeLoc *T = DynNode.get<TypeLoc>())
153 traverse(*T);
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000154 // FIXME: Add other base types after adding tests.
Manuel Klimek4da21662012-07-06 05:48:52 +0000155 return Matches;
156 }
157
158 // The following are overriding methods from the base visitor class.
159 // They are public only to allow CRTP to work. They are *not *part
160 // of the public API of this class.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000161 bool TraverseDecl(Decl *DeclNode) {
Daniel Jaspera267cf62012-10-29 10:14:44 +0000162 ScopedIncrement ScopedDepth(&CurrentDepth);
Manuel Klimek4da21662012-07-06 05:48:52 +0000163 return (DeclNode == NULL) || traverse(*DeclNode);
164 }
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000165 bool TraverseStmt(Stmt *StmtNode) {
Daniel Jaspera267cf62012-10-29 10:14:44 +0000166 ScopedIncrement ScopedDepth(&CurrentDepth);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000167 const Stmt *StmtToTraverse = StmtNode;
Manuel Klimek4da21662012-07-06 05:48:52 +0000168 if (Traversal ==
169 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses) {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000170 const Expr *ExprNode = dyn_cast_or_null<Expr>(StmtNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000171 if (ExprNode != NULL) {
172 StmtToTraverse = ExprNode->IgnoreParenImpCasts();
173 }
174 }
175 return (StmtToTraverse == NULL) || traverse(*StmtToTraverse);
176 }
Daniel Jaspera267cf62012-10-29 10:14:44 +0000177 // We assume that the QualType and the contained type are on the same
178 // hierarchy level. Thus, we try to match either of them.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000179 bool TraverseType(QualType TypeNode) {
Daniel Jaspera267cf62012-10-29 10:14:44 +0000180 ScopedIncrement ScopedDepth(&CurrentDepth);
181 // Match the Type.
182 if (!match(*TypeNode))
183 return false;
184 // The QualType is matched inside traverse.
Manuel Klimek4da21662012-07-06 05:48:52 +0000185 return traverse(TypeNode);
186 }
Daniel Jaspera267cf62012-10-29 10:14:44 +0000187 // We assume that the TypeLoc, contained QualType and contained Type all are
188 // on the same hierarchy level. Thus, we try to match all of them.
189 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
190 ScopedIncrement ScopedDepth(&CurrentDepth);
191 // Match the Type.
192 if (!match(*TypeLocNode.getType()))
193 return false;
194 // Match the QualType.
195 if (!match(TypeLocNode.getType()))
196 return false;
197 // The TypeLoc is matched inside traverse.
198 return traverse(TypeLocNode);
199 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000200
201 bool shouldVisitTemplateInstantiations() const { return true; }
202 bool shouldVisitImplicitCode() const { return true; }
203
204private:
205 // Used for updating the depth during traversal.
206 struct ScopedIncrement {
207 explicit ScopedIncrement(int *Depth) : Depth(Depth) { ++(*Depth); }
208 ~ScopedIncrement() { --(*Depth); }
209
210 private:
211 int *Depth;
212 };
213
214 // Resets the state of this object.
215 void reset() {
216 Matches = false;
Daniel Jaspera267cf62012-10-29 10:14:44 +0000217 CurrentDepth = 0;
Manuel Klimek4da21662012-07-06 05:48:52 +0000218 }
219
220 // Forwards the call to the corresponding Traverse*() method in the
221 // base visitor class.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000222 bool baseTraverse(const Decl &DeclNode) {
223 return VisitorBase::TraverseDecl(const_cast<Decl*>(&DeclNode));
Manuel Klimek4da21662012-07-06 05:48:52 +0000224 }
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000225 bool baseTraverse(const Stmt &StmtNode) {
226 return VisitorBase::TraverseStmt(const_cast<Stmt*>(&StmtNode));
Manuel Klimek4da21662012-07-06 05:48:52 +0000227 }
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000228 bool baseTraverse(QualType TypeNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000229 return VisitorBase::TraverseType(TypeNode);
230 }
Daniel Jaspera267cf62012-10-29 10:14:44 +0000231 bool baseTraverse(TypeLoc TypeLocNode) {
232 return VisitorBase::TraverseTypeLoc(TypeLocNode);
233 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000234
Daniel Jaspera267cf62012-10-29 10:14:44 +0000235 // Sets 'Matched' to true if 'Matcher' matches 'Node' and:
236 // 0 < CurrentDepth <= MaxDepth.
237 //
238 // Returns 'true' if traversal should continue after this function
239 // returns, i.e. if no match is found or 'Bind' is 'BK_All'.
Manuel Klimek4da21662012-07-06 05:48:52 +0000240 template <typename T>
Daniel Jaspera267cf62012-10-29 10:14:44 +0000241 bool match(const T &Node) {
242 if (CurrentDepth == 0 || CurrentDepth > MaxDepth) {
243 return true;
Manuel Klimek4da21662012-07-06 05:48:52 +0000244 }
245 if (Bind != ASTMatchFinder::BK_All) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000246 if (Matcher->matches(ast_type_traits::DynTypedNode::create(Node),
247 Finder, Builder)) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000248 Matches = true;
249 return false; // Abort as soon as a match is found.
250 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000251 } else {
252 BoundNodesTreeBuilder RecursiveBuilder;
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000253 if (Matcher->matches(ast_type_traits::DynTypedNode::create(Node),
254 Finder, &RecursiveBuilder)) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000255 // After the first match the matcher succeeds.
256 Matches = true;
257 Builder->addMatch(RecursiveBuilder.build());
258 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000259 }
Daniel Jaspera267cf62012-10-29 10:14:44 +0000260 return true;
261 }
262
263 // Traverses the subtree rooted at 'Node'; returns true if the
264 // traversal should continue after this function returns.
265 template <typename T>
266 bool traverse(const T &Node) {
267 TOOLING_COMPILE_ASSERT(IsBaseType<T>::value,
268 traverse_can_only_be_instantiated_with_base_type);
269 if (!match(Node))
270 return false;
271 return baseTraverse(Node);
Manuel Klimek4da21662012-07-06 05:48:52 +0000272 }
273
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000274 const DynTypedMatcher *const Matcher;
Manuel Klimek4da21662012-07-06 05:48:52 +0000275 ASTMatchFinder *const Finder;
276 BoundNodesTreeBuilder *const Builder;
277 int CurrentDepth;
278 const int MaxDepth;
279 const ASTMatchFinder::TraversalKind Traversal;
280 const ASTMatchFinder::BindKind Bind;
281 bool Matches;
282};
283
284// Controls the outermost traversal of the AST and allows to match multiple
285// matchers.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000286class MatchASTVisitor : public RecursiveASTVisitor<MatchASTVisitor>,
Manuel Klimek4da21662012-07-06 05:48:52 +0000287 public ASTMatchFinder {
288public:
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000289 MatchASTVisitor(std::vector<std::pair<const internal::DynTypedMatcher*,
290 MatchCallback*> > *MatcherCallbackPairs)
291 : MatcherCallbackPairs(MatcherCallbackPairs),
Manuel Klimek4da21662012-07-06 05:48:52 +0000292 ActiveASTContext(NULL) {
293 }
294
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000295 void set_active_ast_context(ASTContext *NewActiveASTContext) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000296 ActiveASTContext = NewActiveASTContext;
297 }
298
299 // The following Visit*() and Traverse*() functions "override"
300 // methods in RecursiveASTVisitor.
301
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000302 bool VisitTypedefDecl(TypedefDecl *DeclNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000303 // When we see 'typedef A B', we add name 'B' to the set of names
304 // A's canonical type maps to. This is necessary for implementing
Daniel Jasper76dafa72012-09-07 12:48:17 +0000305 // isDerivedFrom(x) properly, where x can be the name of the base
Manuel Klimek4da21662012-07-06 05:48:52 +0000306 // class or any of its aliases.
307 //
308 // In general, the is-alias-of (as defined by typedefs) relation
309 // is tree-shaped, as you can typedef a type more than once. For
310 // example,
311 //
312 // typedef A B;
313 // typedef A C;
314 // typedef C D;
315 // typedef C E;
316 //
317 // gives you
318 //
319 // A
320 // |- B
321 // `- C
322 // |- D
323 // `- E
324 //
325 // It is wrong to assume that the relation is a chain. A correct
Daniel Jasper76dafa72012-09-07 12:48:17 +0000326 // implementation of isDerivedFrom() needs to recognize that B and
Manuel Klimek4da21662012-07-06 05:48:52 +0000327 // E are aliases, even though neither is a typedef of the other.
328 // Therefore, we cannot simply walk through one typedef chain to
329 // find out whether the type name matches.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000330 const Type *TypeNode = DeclNode->getUnderlyingType().getTypePtr();
331 const Type *CanonicalType = // root of the typedef tree
Manuel Klimek4da21662012-07-06 05:48:52 +0000332 ActiveASTContext->getCanonicalType(TypeNode);
Daniel Jasper20b802d2012-07-17 07:39:27 +0000333 TypeAliases[CanonicalType].insert(DeclNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000334 return true;
335 }
336
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000337 bool TraverseDecl(Decl *DeclNode);
338 bool TraverseStmt(Stmt *StmtNode);
339 bool TraverseType(QualType TypeNode);
340 bool TraverseTypeLoc(TypeLoc TypeNode);
Daniel Jaspera7564432012-09-13 13:11:25 +0000341 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS);
342 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Manuel Klimek4da21662012-07-06 05:48:52 +0000343
344 // Matches children or descendants of 'Node' with 'BaseMatcher'.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000345 bool memoizedMatchesRecursively(const ast_type_traits::DynTypedNode &Node,
346 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000347 BoundNodesTreeBuilder *Builder, int MaxDepth,
348 TraversalKind Traversal, BindKind Bind) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000349 const UntypedMatchInput input(Matcher.getID(), Node.getMemoizationData());
Daniel Jaspera267cf62012-10-29 10:14:44 +0000350
351 // For AST-nodes that don't have an identity, we can't memoize.
352 if (!input.second)
353 return matchesRecursively(Node, Matcher, Builder, MaxDepth, Traversal,
354 Bind);
355
Manuel Klimek4da21662012-07-06 05:48:52 +0000356 std::pair<MemoizationMap::iterator, bool> InsertResult
357 = ResultCache.insert(std::make_pair(input, MemoizedMatchResult()));
358 if (InsertResult.second) {
359 BoundNodesTreeBuilder DescendantBoundNodesBuilder;
360 InsertResult.first->second.ResultOfMatch =
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000361 matchesRecursively(Node, Matcher, &DescendantBoundNodesBuilder,
Manuel Klimek4da21662012-07-06 05:48:52 +0000362 MaxDepth, Traversal, Bind);
363 InsertResult.first->second.Nodes =
364 DescendantBoundNodesBuilder.build();
365 }
366 InsertResult.first->second.Nodes.copyTo(Builder);
367 return InsertResult.first->second.ResultOfMatch;
368 }
369
370 // Matches children or descendants of 'Node' with 'BaseMatcher'.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000371 bool matchesRecursively(const ast_type_traits::DynTypedNode &Node,
372 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000373 BoundNodesTreeBuilder *Builder, int MaxDepth,
374 TraversalKind Traversal, BindKind Bind) {
375 MatchChildASTVisitor Visitor(
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000376 &Matcher, this, Builder, MaxDepth, Traversal, Bind);
Manuel Klimek4da21662012-07-06 05:48:52 +0000377 return Visitor.findMatch(Node);
378 }
379
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000380 virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
Daniel Jasper20b802d2012-07-17 07:39:27 +0000381 const Matcher<NamedDecl> &Base,
382 BoundNodesTreeBuilder *Builder);
Manuel Klimek4da21662012-07-06 05:48:52 +0000383
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000384 // Implements ASTMatchFinder::matchesChildOf.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000385 virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node,
386 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000387 BoundNodesTreeBuilder *Builder,
388 TraversalKind Traversal,
389 BindKind Bind) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000390 return matchesRecursively(Node, Matcher, Builder, 1, Traversal,
Manuel Klimek4da21662012-07-06 05:48:52 +0000391 Bind);
392 }
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000393 // Implements ASTMatchFinder::matchesDescendantOf.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000394 virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node,
395 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000396 BoundNodesTreeBuilder *Builder,
397 BindKind Bind) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000398 return memoizedMatchesRecursively(Node, Matcher, Builder, INT_MAX,
Manuel Klimek4da21662012-07-06 05:48:52 +0000399 TK_AsIs, Bind);
400 }
Manuel Klimek579b1202012-09-07 09:26:10 +0000401 // Implements ASTMatchFinder::matchesAncestorOf.
402 virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node,
403 const DynTypedMatcher &Matcher,
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000404 BoundNodesTreeBuilder *Builder,
405 AncestorMatchMode MatchMode) {
Manuel Klimek579b1202012-09-07 09:26:10 +0000406 if (!Parents) {
407 // We always need to run over the whole translation unit, as
408 // \c hasAncestor can escape any subtree.
409 Parents.reset(ParentMapASTVisitor::buildMap(
410 *ActiveASTContext->getTranslationUnitDecl()));
411 }
412 ast_type_traits::DynTypedNode Ancestor = Node;
413 while (Ancestor.get<TranslationUnitDecl>() !=
414 ActiveASTContext->getTranslationUnitDecl()) {
415 assert(Ancestor.getMemoizationData() &&
416 "Invariant broken: only nodes that support memoization may be "
417 "used in the parent map.");
418 ParentMapASTVisitor::ParentMap::const_iterator I =
419 Parents->find(Ancestor.getMemoizationData());
420 if (I == Parents->end()) {
421 assert(false &&
422 "Found node that is not in the parent map.");
423 return false;
424 }
425 Ancestor = I->second;
426 if (Matcher.matches(Ancestor, this, Builder))
427 return true;
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000428 if (MatchMode == ASTMatchFinder::AMM_ParentOnly)
429 return false;
Manuel Klimek579b1202012-09-07 09:26:10 +0000430 }
431 return false;
432 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000433
434 bool shouldVisitTemplateInstantiations() const { return true; }
435 bool shouldVisitImplicitCode() const { return true; }
436
437private:
438 // Implements a BoundNodesTree::Visitor that calls a MatchCallback with
439 // the aggregated bound nodes for each match.
440 class MatchVisitor : public BoundNodesTree::Visitor {
441 public:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000442 MatchVisitor(ASTContext* Context,
Manuel Klimek4da21662012-07-06 05:48:52 +0000443 MatchFinder::MatchCallback* Callback)
444 : Context(Context),
445 Callback(Callback) {}
446
447 virtual void visitMatch(const BoundNodes& BoundNodesView) {
448 Callback->run(MatchFinder::MatchResult(BoundNodesView, Context));
449 }
450
451 private:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000452 ASTContext* Context;
Manuel Klimek4da21662012-07-06 05:48:52 +0000453 MatchFinder::MatchCallback* Callback;
454 };
455
Daniel Jasper20b802d2012-07-17 07:39:27 +0000456 // Returns true if 'TypeNode' has an alias that matches the given matcher.
457 bool typeHasMatchingAlias(const Type *TypeNode,
458 const Matcher<NamedDecl> Matcher,
459 BoundNodesTreeBuilder *Builder) {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000460 const Type *const CanonicalType =
Manuel Klimek4da21662012-07-06 05:48:52 +0000461 ActiveASTContext->getCanonicalType(TypeNode);
Daniel Jasper20b802d2012-07-17 07:39:27 +0000462 const std::set<const TypedefDecl*> &Aliases = TypeAliases[CanonicalType];
463 for (std::set<const TypedefDecl*>::const_iterator
464 It = Aliases.begin(), End = Aliases.end();
465 It != End; ++It) {
466 if (Matcher.matches(**It, this, Builder))
467 return true;
468 }
469 return false;
Manuel Klimek4da21662012-07-06 05:48:52 +0000470 }
471
472 // Matches all registered matchers on the given node and calls the
473 // result callback for every node that matches.
474 template <typename T>
475 void match(const T &node) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000476 for (std::vector<std::pair<const internal::DynTypedMatcher*,
477 MatchCallback*> >::const_iterator
478 I = MatcherCallbackPairs->begin(), E = MatcherCallbackPairs->end();
479 I != E; ++I) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000480 BoundNodesTreeBuilder Builder;
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000481 if (I->first->matches(ast_type_traits::DynTypedNode::create(node),
482 this, &Builder)) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000483 BoundNodesTree BoundNodes = Builder.build();
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000484 MatchVisitor Visitor(ActiveASTContext, I->second);
Manuel Klimek4da21662012-07-06 05:48:52 +0000485 BoundNodes.visitMatches(&Visitor);
486 }
487 }
488 }
489
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000490 std::vector<std::pair<const internal::DynTypedMatcher*,
491 MatchCallback*> > *const MatcherCallbackPairs;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000492 ASTContext *ActiveASTContext;
Manuel Klimek4da21662012-07-06 05:48:52 +0000493
Daniel Jasper20b802d2012-07-17 07:39:27 +0000494 // Maps a canonical type to its TypedefDecls.
495 llvm::DenseMap<const Type*, std::set<const TypedefDecl*> > TypeAliases;
Manuel Klimek4da21662012-07-06 05:48:52 +0000496
497 // Maps (matcher, node) -> the match result for memoization.
498 typedef llvm::DenseMap<UntypedMatchInput, MemoizedMatchResult> MemoizationMap;
499 MemoizationMap ResultCache;
Manuel Klimek579b1202012-09-07 09:26:10 +0000500
501 llvm::OwningPtr<ParentMapASTVisitor::ParentMap> Parents;
Manuel Klimek4da21662012-07-06 05:48:52 +0000502};
503
504// Returns true if the given class is directly or indirectly derived
Daniel Jasper76dafa72012-09-07 12:48:17 +0000505// from a base type with the given name. A class is not considered to be
506// derived from itself.
Daniel Jasper20b802d2012-07-17 07:39:27 +0000507bool MatchASTVisitor::classIsDerivedFrom(const CXXRecordDecl *Declaration,
508 const Matcher<NamedDecl> &Base,
509 BoundNodesTreeBuilder *Builder) {
Daniel Jasper20b802d2012-07-17 07:39:27 +0000510 if (!Declaration->hasDefinition())
Manuel Klimek4da21662012-07-06 05:48:52 +0000511 return false;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000512 typedef CXXRecordDecl::base_class_const_iterator BaseIterator;
Manuel Klimek4da21662012-07-06 05:48:52 +0000513 for (BaseIterator It = Declaration->bases_begin(),
514 End = Declaration->bases_end(); It != End; ++It) {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000515 const Type *TypeNode = It->getType().getTypePtr();
Manuel Klimek4da21662012-07-06 05:48:52 +0000516
Daniel Jasper20b802d2012-07-17 07:39:27 +0000517 if (typeHasMatchingAlias(TypeNode, Base, Builder))
Manuel Klimek4da21662012-07-06 05:48:52 +0000518 return true;
519
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000520 // Type::getAs<...>() drills through typedefs.
521 if (TypeNode->getAs<DependentNameType>() != NULL ||
Daniel Jasper08f0c532012-09-18 14:17:42 +0000522 TypeNode->getAs<DependentTemplateSpecializationType>() != NULL ||
Daniel Jasper20b802d2012-07-17 07:39:27 +0000523 TypeNode->getAs<TemplateTypeParmType>() != NULL)
Manuel Klimek4da21662012-07-06 05:48:52 +0000524 // Dependent names and template TypeNode parameters will be matched when
525 // the template is instantiated.
526 continue;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000527 CXXRecordDecl *ClassDecl = NULL;
528 TemplateSpecializationType const *TemplateType =
529 TypeNode->getAs<TemplateSpecializationType>();
Manuel Klimek4da21662012-07-06 05:48:52 +0000530 if (TemplateType != NULL) {
Daniel Jasper20b802d2012-07-17 07:39:27 +0000531 if (TemplateType->getTemplateName().isDependent())
Manuel Klimek4da21662012-07-06 05:48:52 +0000532 // Dependent template specializations will be matched when the
533 // template is instantiated.
534 continue;
Daniel Jasper20b802d2012-07-17 07:39:27 +0000535
Manuel Klimek4da21662012-07-06 05:48:52 +0000536 // For template specialization types which are specializing a template
537 // declaration which is an explicit or partial specialization of another
538 // template declaration, getAsCXXRecordDecl() returns the corresponding
539 // ClassTemplateSpecializationDecl.
540 //
541 // For template specialization types which are specializing a template
542 // declaration which is neither an explicit nor partial specialization of
543 // another template declaration, getAsCXXRecordDecl() returns NULL and
544 // we get the CXXRecordDecl of the templated declaration.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000545 CXXRecordDecl *SpecializationDecl =
Manuel Klimek4da21662012-07-06 05:48:52 +0000546 TemplateType->getAsCXXRecordDecl();
547 if (SpecializationDecl != NULL) {
548 ClassDecl = SpecializationDecl;
549 } else {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000550 ClassDecl = llvm::dyn_cast<CXXRecordDecl>(
Manuel Klimek4da21662012-07-06 05:48:52 +0000551 TemplateType->getTemplateName()
552 .getAsTemplateDecl()->getTemplatedDecl());
553 }
554 } else {
555 ClassDecl = TypeNode->getAsCXXRecordDecl();
556 }
557 assert(ClassDecl != NULL);
558 assert(ClassDecl != Declaration);
Daniel Jasper76dafa72012-09-07 12:48:17 +0000559 if (Base.matches(*ClassDecl, this, Builder))
560 return true;
Daniel Jasper20b802d2012-07-17 07:39:27 +0000561 if (classIsDerivedFrom(ClassDecl, Base, Builder))
Manuel Klimek4da21662012-07-06 05:48:52 +0000562 return true;
Manuel Klimek4da21662012-07-06 05:48:52 +0000563 }
564 return false;
565}
566
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000567bool MatchASTVisitor::TraverseDecl(Decl *DeclNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000568 if (DeclNode == NULL) {
569 return true;
570 }
571 match(*DeclNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000572 return RecursiveASTVisitor<MatchASTVisitor>::TraverseDecl(DeclNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000573}
574
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000575bool MatchASTVisitor::TraverseStmt(Stmt *StmtNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000576 if (StmtNode == NULL) {
577 return true;
578 }
579 match(*StmtNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000580 return RecursiveASTVisitor<MatchASTVisitor>::TraverseStmt(StmtNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000581}
582
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000583bool MatchASTVisitor::TraverseType(QualType TypeNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000584 match(TypeNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000585 return RecursiveASTVisitor<MatchASTVisitor>::TraverseType(TypeNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000586}
587
Daniel Jasperce620072012-10-17 08:52:59 +0000588bool MatchASTVisitor::TraverseTypeLoc(TypeLoc TypeLocNode) {
589 // The RecursiveASTVisitor only visits types if they're not within TypeLocs.
590 // We still want to find those types via matchers, so we match them here. Note
591 // that the TypeLocs are structurally a shadow-hierarchy to the expressed
592 // type, so we visit all involved parts of a compound type when matching on
593 // each TypeLoc.
594 match(TypeLocNode);
595 match(TypeLocNode.getType());
596 return RecursiveASTVisitor<MatchASTVisitor>::TraverseTypeLoc(TypeLocNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000597}
598
Daniel Jaspera7564432012-09-13 13:11:25 +0000599bool MatchASTVisitor::TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
600 match(*NNS);
601 return RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifier(NNS);
602}
603
604bool MatchASTVisitor::TraverseNestedNameSpecifierLoc(
605 NestedNameSpecifierLoc NNS) {
606 match(NNS);
607 // We only match the nested name specifier here (as opposed to traversing it)
608 // because the traversal is already done in the parallel "Loc"-hierarchy.
609 match(*NNS.getNestedNameSpecifier());
610 return
611 RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifierLoc(NNS);
612}
613
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000614class MatchASTConsumer : public ASTConsumer {
Manuel Klimek4da21662012-07-06 05:48:52 +0000615public:
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000616 MatchASTConsumer(
617 std::vector<std::pair<const internal::DynTypedMatcher*,
618 MatchCallback*> > *MatcherCallbackPairs,
619 MatchFinder::ParsingDoneTestCallback *ParsingDone)
620 : Visitor(MatcherCallbackPairs),
621 ParsingDone(ParsingDone) {}
Manuel Klimek4da21662012-07-06 05:48:52 +0000622
623private:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000624 virtual void HandleTranslationUnit(ASTContext &Context) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000625 if (ParsingDone != NULL) {
626 ParsingDone->run();
627 }
628 Visitor.set_active_ast_context(&Context);
629 Visitor.TraverseDecl(Context.getTranslationUnitDecl());
630 Visitor.set_active_ast_context(NULL);
631 }
632
633 MatchASTVisitor Visitor;
634 MatchFinder::ParsingDoneTestCallback *ParsingDone;
635};
636
637} // end namespace
638} // end namespace internal
639
640MatchFinder::MatchResult::MatchResult(const BoundNodes &Nodes,
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000641 ASTContext *Context)
Manuel Klimek4da21662012-07-06 05:48:52 +0000642 : Nodes(Nodes), Context(Context),
643 SourceManager(&Context->getSourceManager()) {}
644
645MatchFinder::MatchCallback::~MatchCallback() {}
646MatchFinder::ParsingDoneTestCallback::~ParsingDoneTestCallback() {}
647
648MatchFinder::MatchFinder() : ParsingDone(NULL) {}
649
650MatchFinder::~MatchFinder() {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000651 for (std::vector<std::pair<const internal::DynTypedMatcher*,
652 MatchCallback*> >::const_iterator
653 It = MatcherCallbackPairs.begin(), End = MatcherCallbackPairs.end();
Manuel Klimek4da21662012-07-06 05:48:52 +0000654 It != End; ++It) {
655 delete It->first;
656 }
657}
658
659void MatchFinder::addMatcher(const DeclarationMatcher &NodeMatch,
660 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000661 MatcherCallbackPairs.push_back(std::make_pair(
662 new internal::Matcher<Decl>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000663}
664
665void MatchFinder::addMatcher(const TypeMatcher &NodeMatch,
666 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000667 MatcherCallbackPairs.push_back(std::make_pair(
668 new internal::Matcher<QualType>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000669}
670
671void MatchFinder::addMatcher(const StatementMatcher &NodeMatch,
672 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000673 MatcherCallbackPairs.push_back(std::make_pair(
674 new internal::Matcher<Stmt>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000675}
676
Daniel Jaspera7564432012-09-13 13:11:25 +0000677void MatchFinder::addMatcher(const NestedNameSpecifierMatcher &NodeMatch,
678 MatchCallback *Action) {
679 MatcherCallbackPairs.push_back(std::make_pair(
680 new NestedNameSpecifierMatcher(NodeMatch), Action));
681}
682
683void MatchFinder::addMatcher(const NestedNameSpecifierLocMatcher &NodeMatch,
684 MatchCallback *Action) {
685 MatcherCallbackPairs.push_back(std::make_pair(
686 new NestedNameSpecifierLocMatcher(NodeMatch), Action));
687}
688
Daniel Jasperce620072012-10-17 08:52:59 +0000689void MatchFinder::addMatcher(const TypeLocMatcher &NodeMatch,
690 MatchCallback *Action) {
691 MatcherCallbackPairs.push_back(std::make_pair(
692 new TypeLocMatcher(NodeMatch), Action));
693}
694
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000695ASTConsumer *MatchFinder::newASTConsumer() {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000696 return new internal::MatchASTConsumer(&MatcherCallbackPairs, ParsingDone);
Manuel Klimek4da21662012-07-06 05:48:52 +0000697}
698
Manuel Klimek3e2aa992012-10-24 14:47:44 +0000699void MatchFinder::findAll(const Decl &Node, ASTContext &Context) {
700 internal::MatchASTVisitor Visitor(&MatcherCallbackPairs);
701 Visitor.set_active_ast_context(&Context);
702 Visitor.TraverseDecl(const_cast<Decl*>(&Node));
703}
704
705void MatchFinder::findAll(const Stmt &Node, ASTContext &Context) {
706 internal::MatchASTVisitor Visitor(&MatcherCallbackPairs);
707 Visitor.set_active_ast_context(&Context);
708 Visitor.TraverseStmt(const_cast<Stmt*>(&Node));
709}
710
Manuel Klimek4da21662012-07-06 05:48:52 +0000711void MatchFinder::registerTestCallbackAfterParsing(
712 MatchFinder::ParsingDoneTestCallback *NewParsingDone) {
713 ParsingDone = NewParsingDone;
714}
715
716} // end namespace ast_matchers
717} // end namespace clang