blob: 0b1d1b6f2585cfe748fc4f7dc528cf38d044a665 [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:
Manuel Klimek30ace372012-12-06 14:42:48 +000042 /// \brief Contains parents of a node.
43 typedef llvm::SmallVector<ast_type_traits::DynTypedNode, 1> ParentVector;
44
45 /// \brief Maps from a node to its parents.
46 typedef llvm::DenseMap<const void *, ParentVector> ParentMap;
Manuel Klimek579b1202012-09-07 09:26:10 +000047
48 /// \brief Builds and returns the translation unit's parent map.
49 ///
50 /// The caller takes ownership of the returned \c ParentMap.
51 static ParentMap *buildMap(TranslationUnitDecl &TU) {
52 ParentMapASTVisitor Visitor(new ParentMap);
53 Visitor.TraverseDecl(&TU);
54 return Visitor.Parents;
55 }
56
57private:
58 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
59
60 ParentMapASTVisitor(ParentMap *Parents) : Parents(Parents) {}
61
62 bool shouldVisitTemplateInstantiations() const { return true; }
63 bool shouldVisitImplicitCode() const { return true; }
Daniel Jasper278057f2012-11-15 03:29:05 +000064 // Disables data recursion. We intercept Traverse* methods in the RAV, which
65 // are not triggered during data recursion.
66 bool shouldUseDataRecursionFor(clang::Stmt *S) const { return false; }
Manuel Klimek579b1202012-09-07 09:26:10 +000067
68 template <typename T>
69 bool TraverseNode(T *Node, bool (VisitorBase::*traverse)(T*)) {
70 if (Node == NULL)
71 return true;
72 if (ParentStack.size() > 0)
Manuel Klimek30ace372012-12-06 14:42:48 +000073 // FIXME: Currently we add the same parent multiple times, for example
74 // when we visit all subexpressions of template instantiations; this is
75 // suboptimal, bug benign: the only way to visit those is with
76 // hasAncestor / hasParent, and those do not create new matches.
77 // The plan is to enable DynTypedNode to be storable in a map or hash
78 // map. The main problem there is to implement hash functions /
79 // comparison operators for all types that DynTypedNode supports that
80 // do not have pointer identity.
81 (*Parents)[Node].push_back(ParentStack.back());
Manuel Klimek579b1202012-09-07 09:26:10 +000082 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
83 bool Result = (this->*traverse)(Node);
84 ParentStack.pop_back();
85 return Result;
86 }
87
88 bool TraverseDecl(Decl *DeclNode) {
89 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
90 }
91
92 bool TraverseStmt(Stmt *StmtNode) {
93 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
94 }
95
96 ParentMap *Parents;
97 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
98
99 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
100};
101
Manuel Klimek4da21662012-07-06 05:48:52 +0000102// We use memoization to avoid running the same matcher on the same
103// AST node twice. This pair is the key for looking up match
104// result. It consists of an ID of the MatcherInterface (for
105// identifying the matcher) and a pointer to the AST node.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000106//
107// We currently only memoize on nodes whose pointers identify the
108// nodes (\c Stmt and \c Decl, but not \c QualType or \c TypeLoc).
109// For \c QualType and \c TypeLoc it is possible to implement
110// generation of keys for each type.
111// FIXME: Benchmark whether memoization of non-pointer typed nodes
112// provides enough benefit for the additional amount of code.
Manuel Klimek4da21662012-07-06 05:48:52 +0000113typedef std::pair<uint64_t, const void*> UntypedMatchInput;
114
115// Used to store the result of a match and possibly bound nodes.
116struct MemoizedMatchResult {
117 bool ResultOfMatch;
118 BoundNodesTree Nodes;
119};
120
121// A RecursiveASTVisitor that traverses all children or all descendants of
122// a node.
123class MatchChildASTVisitor
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000124 : public RecursiveASTVisitor<MatchChildASTVisitor> {
Manuel Klimek4da21662012-07-06 05:48:52 +0000125public:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000126 typedef RecursiveASTVisitor<MatchChildASTVisitor> VisitorBase;
Manuel Klimek4da21662012-07-06 05:48:52 +0000127
128 // Creates an AST visitor that matches 'matcher' on all children or
129 // descendants of a traversed node. max_depth is the maximum depth
130 // to traverse: use 1 for matching the children and INT_MAX for
131 // matching the descendants.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000132 MatchChildASTVisitor(const DynTypedMatcher *Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000133 ASTMatchFinder *Finder,
134 BoundNodesTreeBuilder *Builder,
135 int MaxDepth,
136 ASTMatchFinder::TraversalKind Traversal,
137 ASTMatchFinder::BindKind Bind)
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000138 : Matcher(Matcher),
Manuel Klimek4da21662012-07-06 05:48:52 +0000139 Finder(Finder),
140 Builder(Builder),
Daniel Jaspera267cf62012-10-29 10:14:44 +0000141 CurrentDepth(0),
Manuel Klimek4da21662012-07-06 05:48:52 +0000142 MaxDepth(MaxDepth),
143 Traversal(Traversal),
144 Bind(Bind),
145 Matches(false) {}
146
147 // Returns true if a match is found in the subtree rooted at the
148 // given AST node. This is done via a set of mutually recursive
149 // functions. Here's how the recursion is done (the *wildcard can
150 // actually be Decl, Stmt, or Type):
151 //
152 // - Traverse(node) calls BaseTraverse(node) when it needs
153 // to visit the descendants of node.
154 // - BaseTraverse(node) then calls (via VisitorBase::Traverse*(node))
155 // Traverse*(c) for each child c of 'node'.
156 // - Traverse*(c) in turn calls Traverse(c), completing the
157 // recursion.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000158 bool findMatch(const ast_type_traits::DynTypedNode &DynNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000159 reset();
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000160 if (const Decl *D = DynNode.get<Decl>())
161 traverse(*D);
162 else if (const Stmt *S = DynNode.get<Stmt>())
163 traverse(*S);
Daniel Jasperd1ce3c12012-10-30 15:42:00 +0000164 else if (const NestedNameSpecifier *NNS =
165 DynNode.get<NestedNameSpecifier>())
166 traverse(*NNS);
167 else if (const NestedNameSpecifierLoc *NNSLoc =
168 DynNode.get<NestedNameSpecifierLoc>())
169 traverse(*NNSLoc);
Daniel Jaspera267cf62012-10-29 10:14:44 +0000170 else if (const QualType *Q = DynNode.get<QualType>())
171 traverse(*Q);
172 else if (const TypeLoc *T = DynNode.get<TypeLoc>())
173 traverse(*T);
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000174 // FIXME: Add other base types after adding tests.
Manuel Klimek4da21662012-07-06 05:48:52 +0000175 return Matches;
176 }
177
178 // The following are overriding methods from the base visitor class.
179 // They are public only to allow CRTP to work. They are *not *part
180 // of the public API of this class.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000181 bool TraverseDecl(Decl *DeclNode) {
Daniel Jaspera267cf62012-10-29 10:14:44 +0000182 ScopedIncrement ScopedDepth(&CurrentDepth);
Manuel Klimek4da21662012-07-06 05:48:52 +0000183 return (DeclNode == NULL) || traverse(*DeclNode);
184 }
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000185 bool TraverseStmt(Stmt *StmtNode) {
Daniel Jaspera267cf62012-10-29 10:14:44 +0000186 ScopedIncrement ScopedDepth(&CurrentDepth);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000187 const Stmt *StmtToTraverse = StmtNode;
Manuel Klimek4da21662012-07-06 05:48:52 +0000188 if (Traversal ==
189 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses) {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000190 const Expr *ExprNode = dyn_cast_or_null<Expr>(StmtNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000191 if (ExprNode != NULL) {
192 StmtToTraverse = ExprNode->IgnoreParenImpCasts();
193 }
194 }
195 return (StmtToTraverse == NULL) || traverse(*StmtToTraverse);
196 }
Daniel Jaspera267cf62012-10-29 10:14:44 +0000197 // We assume that the QualType and the contained type are on the same
198 // hierarchy level. Thus, we try to match either of them.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000199 bool TraverseType(QualType TypeNode) {
Daniel Jasperb55c67d2012-11-13 17:14:11 +0000200 if (TypeNode.isNull())
201 return true;
Daniel Jaspera267cf62012-10-29 10:14:44 +0000202 ScopedIncrement ScopedDepth(&CurrentDepth);
203 // Match the Type.
204 if (!match(*TypeNode))
205 return false;
206 // The QualType is matched inside traverse.
Manuel Klimek4da21662012-07-06 05:48:52 +0000207 return traverse(TypeNode);
208 }
Daniel Jaspera267cf62012-10-29 10:14:44 +0000209 // We assume that the TypeLoc, contained QualType and contained Type all are
210 // on the same hierarchy level. Thus, we try to match all of them.
211 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Daniel Jasperb55c67d2012-11-13 17:14:11 +0000212 if (TypeLocNode.isNull())
213 return true;
Daniel Jaspera267cf62012-10-29 10:14:44 +0000214 ScopedIncrement ScopedDepth(&CurrentDepth);
215 // Match the Type.
216 if (!match(*TypeLocNode.getType()))
217 return false;
218 // Match the QualType.
219 if (!match(TypeLocNode.getType()))
220 return false;
221 // The TypeLoc is matched inside traverse.
222 return traverse(TypeLocNode);
223 }
Daniel Jasperd1ce3c12012-10-30 15:42:00 +0000224 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
225 ScopedIncrement ScopedDepth(&CurrentDepth);
226 return (NNS == NULL) || traverse(*NNS);
227 }
228 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
Daniel Jasperb55c67d2012-11-13 17:14:11 +0000229 if (!NNS)
230 return true;
Daniel Jasperd1ce3c12012-10-30 15:42:00 +0000231 ScopedIncrement ScopedDepth(&CurrentDepth);
232 if (!match(*NNS.getNestedNameSpecifier()))
233 return false;
Daniel Jasperb55c67d2012-11-13 17:14:11 +0000234 return traverse(NNS);
Daniel Jasperd1ce3c12012-10-30 15:42:00 +0000235 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000236
237 bool shouldVisitTemplateInstantiations() const { return true; }
238 bool shouldVisitImplicitCode() const { return true; }
Daniel Jasper278057f2012-11-15 03:29:05 +0000239 // Disables data recursion. We intercept Traverse* methods in the RAV, which
240 // are not triggered during data recursion.
241 bool shouldUseDataRecursionFor(clang::Stmt *S) const { return false; }
Manuel Klimek4da21662012-07-06 05:48:52 +0000242
243private:
244 // Used for updating the depth during traversal.
245 struct ScopedIncrement {
246 explicit ScopedIncrement(int *Depth) : Depth(Depth) { ++(*Depth); }
247 ~ScopedIncrement() { --(*Depth); }
248
249 private:
250 int *Depth;
251 };
252
253 // Resets the state of this object.
254 void reset() {
255 Matches = false;
Daniel Jaspera267cf62012-10-29 10:14:44 +0000256 CurrentDepth = 0;
Manuel Klimek4da21662012-07-06 05:48:52 +0000257 }
258
259 // Forwards the call to the corresponding Traverse*() method in the
260 // base visitor class.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000261 bool baseTraverse(const Decl &DeclNode) {
262 return VisitorBase::TraverseDecl(const_cast<Decl*>(&DeclNode));
Manuel Klimek4da21662012-07-06 05:48:52 +0000263 }
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000264 bool baseTraverse(const Stmt &StmtNode) {
265 return VisitorBase::TraverseStmt(const_cast<Stmt*>(&StmtNode));
Manuel Klimek4da21662012-07-06 05:48:52 +0000266 }
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000267 bool baseTraverse(QualType TypeNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000268 return VisitorBase::TraverseType(TypeNode);
269 }
Daniel Jaspera267cf62012-10-29 10:14:44 +0000270 bool baseTraverse(TypeLoc TypeLocNode) {
271 return VisitorBase::TraverseTypeLoc(TypeLocNode);
272 }
Daniel Jasperd1ce3c12012-10-30 15:42:00 +0000273 bool baseTraverse(const NestedNameSpecifier &NNS) {
274 return VisitorBase::TraverseNestedNameSpecifier(
275 const_cast<NestedNameSpecifier*>(&NNS));
276 }
277 bool baseTraverse(NestedNameSpecifierLoc NNS) {
278 return VisitorBase::TraverseNestedNameSpecifierLoc(NNS);
279 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000280
Daniel Jaspera267cf62012-10-29 10:14:44 +0000281 // Sets 'Matched' to true if 'Matcher' matches 'Node' and:
282 // 0 < CurrentDepth <= MaxDepth.
283 //
284 // Returns 'true' if traversal should continue after this function
285 // returns, i.e. if no match is found or 'Bind' is 'BK_All'.
Manuel Klimek4da21662012-07-06 05:48:52 +0000286 template <typename T>
Daniel Jaspera267cf62012-10-29 10:14:44 +0000287 bool match(const T &Node) {
288 if (CurrentDepth == 0 || CurrentDepth > MaxDepth) {
289 return true;
Manuel Klimek4da21662012-07-06 05:48:52 +0000290 }
291 if (Bind != ASTMatchFinder::BK_All) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000292 if (Matcher->matches(ast_type_traits::DynTypedNode::create(Node),
293 Finder, Builder)) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000294 Matches = true;
295 return false; // Abort as soon as a match is found.
296 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000297 } else {
298 BoundNodesTreeBuilder RecursiveBuilder;
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000299 if (Matcher->matches(ast_type_traits::DynTypedNode::create(Node),
300 Finder, &RecursiveBuilder)) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000301 // After the first match the matcher succeeds.
302 Matches = true;
303 Builder->addMatch(RecursiveBuilder.build());
304 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000305 }
Daniel Jaspera267cf62012-10-29 10:14:44 +0000306 return true;
307 }
308
309 // Traverses the subtree rooted at 'Node'; returns true if the
310 // traversal should continue after this function returns.
311 template <typename T>
312 bool traverse(const T &Node) {
313 TOOLING_COMPILE_ASSERT(IsBaseType<T>::value,
314 traverse_can_only_be_instantiated_with_base_type);
315 if (!match(Node))
316 return false;
317 return baseTraverse(Node);
Manuel Klimek4da21662012-07-06 05:48:52 +0000318 }
319
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000320 const DynTypedMatcher *const Matcher;
Manuel Klimek4da21662012-07-06 05:48:52 +0000321 ASTMatchFinder *const Finder;
322 BoundNodesTreeBuilder *const Builder;
323 int CurrentDepth;
324 const int MaxDepth;
325 const ASTMatchFinder::TraversalKind Traversal;
326 const ASTMatchFinder::BindKind Bind;
327 bool Matches;
328};
329
330// Controls the outermost traversal of the AST and allows to match multiple
331// matchers.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000332class MatchASTVisitor : public RecursiveASTVisitor<MatchASTVisitor>,
Manuel Klimek4da21662012-07-06 05:48:52 +0000333 public ASTMatchFinder {
334public:
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000335 MatchASTVisitor(std::vector<std::pair<const internal::DynTypedMatcher*,
336 MatchCallback*> > *MatcherCallbackPairs)
337 : MatcherCallbackPairs(MatcherCallbackPairs),
Manuel Klimek4da21662012-07-06 05:48:52 +0000338 ActiveASTContext(NULL) {
339 }
340
Manuel Klimeke5793282012-11-02 01:31:03 +0000341 void onStartOfTranslationUnit() {
342 for (std::vector<std::pair<const internal::DynTypedMatcher*,
343 MatchCallback*> >::const_iterator
344 I = MatcherCallbackPairs->begin(), E = MatcherCallbackPairs->end();
345 I != E; ++I) {
346 I->second->onStartOfTranslationUnit();
347 }
348 }
349
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000350 void set_active_ast_context(ASTContext *NewActiveASTContext) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000351 ActiveASTContext = NewActiveASTContext;
352 }
353
354 // The following Visit*() and Traverse*() functions "override"
355 // methods in RecursiveASTVisitor.
356
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000357 bool VisitTypedefDecl(TypedefDecl *DeclNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000358 // When we see 'typedef A B', we add name 'B' to the set of names
359 // A's canonical type maps to. This is necessary for implementing
Daniel Jasper76dafa72012-09-07 12:48:17 +0000360 // isDerivedFrom(x) properly, where x can be the name of the base
Manuel Klimek4da21662012-07-06 05:48:52 +0000361 // class or any of its aliases.
362 //
363 // In general, the is-alias-of (as defined by typedefs) relation
364 // is tree-shaped, as you can typedef a type more than once. For
365 // example,
366 //
367 // typedef A B;
368 // typedef A C;
369 // typedef C D;
370 // typedef C E;
371 //
372 // gives you
373 //
374 // A
375 // |- B
376 // `- C
377 // |- D
378 // `- E
379 //
380 // It is wrong to assume that the relation is a chain. A correct
Daniel Jasper76dafa72012-09-07 12:48:17 +0000381 // implementation of isDerivedFrom() needs to recognize that B and
Manuel Klimek4da21662012-07-06 05:48:52 +0000382 // E are aliases, even though neither is a typedef of the other.
383 // Therefore, we cannot simply walk through one typedef chain to
384 // find out whether the type name matches.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000385 const Type *TypeNode = DeclNode->getUnderlyingType().getTypePtr();
386 const Type *CanonicalType = // root of the typedef tree
Manuel Klimek4da21662012-07-06 05:48:52 +0000387 ActiveASTContext->getCanonicalType(TypeNode);
Daniel Jasper20b802d2012-07-17 07:39:27 +0000388 TypeAliases[CanonicalType].insert(DeclNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000389 return true;
390 }
391
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000392 bool TraverseDecl(Decl *DeclNode);
393 bool TraverseStmt(Stmt *StmtNode);
394 bool TraverseType(QualType TypeNode);
395 bool TraverseTypeLoc(TypeLoc TypeNode);
Daniel Jaspera7564432012-09-13 13:11:25 +0000396 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS);
397 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Manuel Klimek4da21662012-07-06 05:48:52 +0000398
399 // Matches children or descendants of 'Node' with 'BaseMatcher'.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000400 bool memoizedMatchesRecursively(const ast_type_traits::DynTypedNode &Node,
401 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000402 BoundNodesTreeBuilder *Builder, int MaxDepth,
403 TraversalKind Traversal, BindKind Bind) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000404 const UntypedMatchInput input(Matcher.getID(), Node.getMemoizationData());
Daniel Jaspera267cf62012-10-29 10:14:44 +0000405
406 // For AST-nodes that don't have an identity, we can't memoize.
407 if (!input.second)
408 return matchesRecursively(Node, Matcher, Builder, MaxDepth, Traversal,
409 Bind);
410
Manuel Klimek4da21662012-07-06 05:48:52 +0000411 std::pair<MemoizationMap::iterator, bool> InsertResult
412 = ResultCache.insert(std::make_pair(input, MemoizedMatchResult()));
413 if (InsertResult.second) {
414 BoundNodesTreeBuilder DescendantBoundNodesBuilder;
415 InsertResult.first->second.ResultOfMatch =
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000416 matchesRecursively(Node, Matcher, &DescendantBoundNodesBuilder,
Manuel Klimek4da21662012-07-06 05:48:52 +0000417 MaxDepth, Traversal, Bind);
418 InsertResult.first->second.Nodes =
419 DescendantBoundNodesBuilder.build();
420 }
421 InsertResult.first->second.Nodes.copyTo(Builder);
422 return InsertResult.first->second.ResultOfMatch;
423 }
424
425 // Matches children or descendants of 'Node' with 'BaseMatcher'.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000426 bool matchesRecursively(const ast_type_traits::DynTypedNode &Node,
427 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000428 BoundNodesTreeBuilder *Builder, int MaxDepth,
429 TraversalKind Traversal, BindKind Bind) {
430 MatchChildASTVisitor Visitor(
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000431 &Matcher, this, Builder, MaxDepth, Traversal, Bind);
Manuel Klimek4da21662012-07-06 05:48:52 +0000432 return Visitor.findMatch(Node);
433 }
434
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000435 virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
Daniel Jasper20b802d2012-07-17 07:39:27 +0000436 const Matcher<NamedDecl> &Base,
437 BoundNodesTreeBuilder *Builder);
Manuel Klimek4da21662012-07-06 05:48:52 +0000438
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000439 // Implements ASTMatchFinder::matchesChildOf.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000440 virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node,
441 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000442 BoundNodesTreeBuilder *Builder,
443 TraversalKind Traversal,
444 BindKind Bind) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000445 return matchesRecursively(Node, Matcher, Builder, 1, Traversal,
Manuel Klimek4da21662012-07-06 05:48:52 +0000446 Bind);
447 }
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000448 // Implements ASTMatchFinder::matchesDescendantOf.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000449 virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node,
450 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000451 BoundNodesTreeBuilder *Builder,
452 BindKind Bind) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000453 return memoizedMatchesRecursively(Node, Matcher, Builder, INT_MAX,
Manuel Klimek4da21662012-07-06 05:48:52 +0000454 TK_AsIs, Bind);
455 }
Manuel Klimek579b1202012-09-07 09:26:10 +0000456 // Implements ASTMatchFinder::matchesAncestorOf.
457 virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node,
458 const DynTypedMatcher &Matcher,
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000459 BoundNodesTreeBuilder *Builder,
460 AncestorMatchMode MatchMode) {
Manuel Klimek579b1202012-09-07 09:26:10 +0000461 if (!Parents) {
462 // We always need to run over the whole translation unit, as
463 // \c hasAncestor can escape any subtree.
464 Parents.reset(ParentMapASTVisitor::buildMap(
465 *ActiveASTContext->getTranslationUnitDecl()));
466 }
Manuel Klimek30ace372012-12-06 14:42:48 +0000467 return matchesAncestorOfRecursively(Node, Matcher, Builder, MatchMode);
Manuel Klimek579b1202012-09-07 09:26:10 +0000468 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000469
Manuel Klimek7f2d4802012-11-30 13:45:19 +0000470 // Implements ASTMatchFinder::getASTContext.
471 virtual ASTContext &getASTContext() const { return *ActiveASTContext; }
472
Manuel Klimek4da21662012-07-06 05:48:52 +0000473 bool shouldVisitTemplateInstantiations() const { return true; }
474 bool shouldVisitImplicitCode() const { return true; }
Daniel Jasper278057f2012-11-15 03:29:05 +0000475 // Disables data recursion. We intercept Traverse* methods in the RAV, which
476 // are not triggered during data recursion.
477 bool shouldUseDataRecursionFor(clang::Stmt *S) const { return false; }
Manuel Klimek4da21662012-07-06 05:48:52 +0000478
479private:
Manuel Klimek30ace372012-12-06 14:42:48 +0000480 bool matchesAncestorOfRecursively(
481 const ast_type_traits::DynTypedNode &Node, const DynTypedMatcher &Matcher,
482 BoundNodesTreeBuilder *Builder, AncestorMatchMode MatchMode) {
483 if (Node.get<TranslationUnitDecl>() ==
484 ActiveASTContext->getTranslationUnitDecl())
485 return false;
486 assert(Node.getMemoizationData() &&
487 "Invariant broken: only nodes that support memoization may be "
488 "used in the parent map.");
489 ParentMapASTVisitor::ParentMap::const_iterator I =
490 Parents->find(Node.getMemoizationData());
491 if (I == Parents->end()) {
492 assert(false && "Found node that is not in the parent map.");
493 return false;
494 }
495 for (ParentMapASTVisitor::ParentVector::const_iterator AncestorI =
496 I->second.begin(), AncestorE = I->second.end();
497 AncestorI != AncestorE; ++AncestorI) {
498 if (Matcher.matches(*AncestorI, this, Builder))
499 return true;
500 }
501 if (MatchMode == ASTMatchFinder::AMM_ParentOnly)
502 return false;
503 for (ParentMapASTVisitor::ParentVector::const_iterator AncestorI =
504 I->second.begin(), AncestorE = I->second.end();
505 AncestorI != AncestorE; ++AncestorI) {
506 if (matchesAncestorOfRecursively(*AncestorI, Matcher, Builder, MatchMode))
507 return true;
508 }
509 return false;
510 }
511
512
Manuel Klimek4da21662012-07-06 05:48:52 +0000513 // Implements a BoundNodesTree::Visitor that calls a MatchCallback with
514 // the aggregated bound nodes for each match.
515 class MatchVisitor : public BoundNodesTree::Visitor {
516 public:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000517 MatchVisitor(ASTContext* Context,
Manuel Klimek4da21662012-07-06 05:48:52 +0000518 MatchFinder::MatchCallback* Callback)
519 : Context(Context),
520 Callback(Callback) {}
521
522 virtual void visitMatch(const BoundNodes& BoundNodesView) {
523 Callback->run(MatchFinder::MatchResult(BoundNodesView, Context));
524 }
525
526 private:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000527 ASTContext* Context;
Manuel Klimek4da21662012-07-06 05:48:52 +0000528 MatchFinder::MatchCallback* Callback;
529 };
530
Daniel Jasper20b802d2012-07-17 07:39:27 +0000531 // Returns true if 'TypeNode' has an alias that matches the given matcher.
532 bool typeHasMatchingAlias(const Type *TypeNode,
533 const Matcher<NamedDecl> Matcher,
534 BoundNodesTreeBuilder *Builder) {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000535 const Type *const CanonicalType =
Manuel Klimek4da21662012-07-06 05:48:52 +0000536 ActiveASTContext->getCanonicalType(TypeNode);
Daniel Jasper20b802d2012-07-17 07:39:27 +0000537 const std::set<const TypedefDecl*> &Aliases = TypeAliases[CanonicalType];
538 for (std::set<const TypedefDecl*>::const_iterator
539 It = Aliases.begin(), End = Aliases.end();
540 It != End; ++It) {
541 if (Matcher.matches(**It, this, Builder))
542 return true;
543 }
544 return false;
Manuel Klimek4da21662012-07-06 05:48:52 +0000545 }
546
547 // Matches all registered matchers on the given node and calls the
548 // result callback for every node that matches.
549 template <typename T>
550 void match(const T &node) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000551 for (std::vector<std::pair<const internal::DynTypedMatcher*,
552 MatchCallback*> >::const_iterator
553 I = MatcherCallbackPairs->begin(), E = MatcherCallbackPairs->end();
554 I != E; ++I) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000555 BoundNodesTreeBuilder Builder;
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000556 if (I->first->matches(ast_type_traits::DynTypedNode::create(node),
557 this, &Builder)) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000558 BoundNodesTree BoundNodes = Builder.build();
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000559 MatchVisitor Visitor(ActiveASTContext, I->second);
Manuel Klimek4da21662012-07-06 05:48:52 +0000560 BoundNodes.visitMatches(&Visitor);
561 }
562 }
563 }
564
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000565 std::vector<std::pair<const internal::DynTypedMatcher*,
566 MatchCallback*> > *const MatcherCallbackPairs;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000567 ASTContext *ActiveASTContext;
Manuel Klimek4da21662012-07-06 05:48:52 +0000568
Daniel Jasper20b802d2012-07-17 07:39:27 +0000569 // Maps a canonical type to its TypedefDecls.
570 llvm::DenseMap<const Type*, std::set<const TypedefDecl*> > TypeAliases;
Manuel Klimek4da21662012-07-06 05:48:52 +0000571
572 // Maps (matcher, node) -> the match result for memoization.
573 typedef llvm::DenseMap<UntypedMatchInput, MemoizedMatchResult> MemoizationMap;
574 MemoizationMap ResultCache;
Manuel Klimek579b1202012-09-07 09:26:10 +0000575
576 llvm::OwningPtr<ParentMapASTVisitor::ParentMap> Parents;
Manuel Klimek4da21662012-07-06 05:48:52 +0000577};
578
579// Returns true if the given class is directly or indirectly derived
Daniel Jasper76dafa72012-09-07 12:48:17 +0000580// from a base type with the given name. A class is not considered to be
581// derived from itself.
Daniel Jasper20b802d2012-07-17 07:39:27 +0000582bool MatchASTVisitor::classIsDerivedFrom(const CXXRecordDecl *Declaration,
583 const Matcher<NamedDecl> &Base,
584 BoundNodesTreeBuilder *Builder) {
Daniel Jasper20b802d2012-07-17 07:39:27 +0000585 if (!Declaration->hasDefinition())
Manuel Klimek4da21662012-07-06 05:48:52 +0000586 return false;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000587 typedef CXXRecordDecl::base_class_const_iterator BaseIterator;
Manuel Klimek4da21662012-07-06 05:48:52 +0000588 for (BaseIterator It = Declaration->bases_begin(),
589 End = Declaration->bases_end(); It != End; ++It) {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000590 const Type *TypeNode = It->getType().getTypePtr();
Manuel Klimek4da21662012-07-06 05:48:52 +0000591
Daniel Jasper20b802d2012-07-17 07:39:27 +0000592 if (typeHasMatchingAlias(TypeNode, Base, Builder))
Manuel Klimek4da21662012-07-06 05:48:52 +0000593 return true;
594
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000595 // Type::getAs<...>() drills through typedefs.
596 if (TypeNode->getAs<DependentNameType>() != NULL ||
Daniel Jasper08f0c532012-09-18 14:17:42 +0000597 TypeNode->getAs<DependentTemplateSpecializationType>() != NULL ||
Daniel Jasper20b802d2012-07-17 07:39:27 +0000598 TypeNode->getAs<TemplateTypeParmType>() != NULL)
Manuel Klimek4da21662012-07-06 05:48:52 +0000599 // Dependent names and template TypeNode parameters will be matched when
600 // the template is instantiated.
601 continue;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000602 CXXRecordDecl *ClassDecl = NULL;
603 TemplateSpecializationType const *TemplateType =
604 TypeNode->getAs<TemplateSpecializationType>();
Manuel Klimek4da21662012-07-06 05:48:52 +0000605 if (TemplateType != NULL) {
Daniel Jasper20b802d2012-07-17 07:39:27 +0000606 if (TemplateType->getTemplateName().isDependent())
Manuel Klimek4da21662012-07-06 05:48:52 +0000607 // Dependent template specializations will be matched when the
608 // template is instantiated.
609 continue;
Daniel Jasper20b802d2012-07-17 07:39:27 +0000610
Manuel Klimek4da21662012-07-06 05:48:52 +0000611 // For template specialization types which are specializing a template
612 // declaration which is an explicit or partial specialization of another
613 // template declaration, getAsCXXRecordDecl() returns the corresponding
614 // ClassTemplateSpecializationDecl.
615 //
616 // For template specialization types which are specializing a template
617 // declaration which is neither an explicit nor partial specialization of
618 // another template declaration, getAsCXXRecordDecl() returns NULL and
619 // we get the CXXRecordDecl of the templated declaration.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000620 CXXRecordDecl *SpecializationDecl =
Manuel Klimek4da21662012-07-06 05:48:52 +0000621 TemplateType->getAsCXXRecordDecl();
622 if (SpecializationDecl != NULL) {
623 ClassDecl = SpecializationDecl;
624 } else {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000625 ClassDecl = llvm::dyn_cast<CXXRecordDecl>(
Manuel Klimek4da21662012-07-06 05:48:52 +0000626 TemplateType->getTemplateName()
627 .getAsTemplateDecl()->getTemplatedDecl());
628 }
629 } else {
630 ClassDecl = TypeNode->getAsCXXRecordDecl();
631 }
632 assert(ClassDecl != NULL);
Manuel Klimek987c2f52012-12-04 13:40:29 +0000633 if (ClassDecl == Declaration) {
634 // This can happen for recursive template definitions; if the
635 // current declaration did not match, we can safely return false.
636 assert(TemplateType);
637 return false;
638 }
Daniel Jasper76dafa72012-09-07 12:48:17 +0000639 if (Base.matches(*ClassDecl, this, Builder))
640 return true;
Daniel Jasper20b802d2012-07-17 07:39:27 +0000641 if (classIsDerivedFrom(ClassDecl, Base, Builder))
Manuel Klimek4da21662012-07-06 05:48:52 +0000642 return true;
Manuel Klimek4da21662012-07-06 05:48:52 +0000643 }
644 return false;
645}
646
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000647bool MatchASTVisitor::TraverseDecl(Decl *DeclNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000648 if (DeclNode == NULL) {
649 return true;
650 }
651 match(*DeclNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000652 return RecursiveASTVisitor<MatchASTVisitor>::TraverseDecl(DeclNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000653}
654
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000655bool MatchASTVisitor::TraverseStmt(Stmt *StmtNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000656 if (StmtNode == NULL) {
657 return true;
658 }
659 match(*StmtNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000660 return RecursiveASTVisitor<MatchASTVisitor>::TraverseStmt(StmtNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000661}
662
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000663bool MatchASTVisitor::TraverseType(QualType TypeNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000664 match(TypeNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000665 return RecursiveASTVisitor<MatchASTVisitor>::TraverseType(TypeNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000666}
667
Daniel Jasperce620072012-10-17 08:52:59 +0000668bool MatchASTVisitor::TraverseTypeLoc(TypeLoc TypeLocNode) {
669 // The RecursiveASTVisitor only visits types if they're not within TypeLocs.
670 // We still want to find those types via matchers, so we match them here. Note
671 // that the TypeLocs are structurally a shadow-hierarchy to the expressed
672 // type, so we visit all involved parts of a compound type when matching on
673 // each TypeLoc.
674 match(TypeLocNode);
675 match(TypeLocNode.getType());
676 return RecursiveASTVisitor<MatchASTVisitor>::TraverseTypeLoc(TypeLocNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000677}
678
Daniel Jaspera7564432012-09-13 13:11:25 +0000679bool MatchASTVisitor::TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
680 match(*NNS);
681 return RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifier(NNS);
682}
683
684bool MatchASTVisitor::TraverseNestedNameSpecifierLoc(
685 NestedNameSpecifierLoc NNS) {
686 match(NNS);
687 // We only match the nested name specifier here (as opposed to traversing it)
688 // because the traversal is already done in the parallel "Loc"-hierarchy.
689 match(*NNS.getNestedNameSpecifier());
690 return
691 RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifierLoc(NNS);
692}
693
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000694class MatchASTConsumer : public ASTConsumer {
Manuel Klimek4da21662012-07-06 05:48:52 +0000695public:
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000696 MatchASTConsumer(
697 std::vector<std::pair<const internal::DynTypedMatcher*,
698 MatchCallback*> > *MatcherCallbackPairs,
699 MatchFinder::ParsingDoneTestCallback *ParsingDone)
700 : Visitor(MatcherCallbackPairs),
701 ParsingDone(ParsingDone) {}
Manuel Klimek4da21662012-07-06 05:48:52 +0000702
703private:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000704 virtual void HandleTranslationUnit(ASTContext &Context) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000705 if (ParsingDone != NULL) {
706 ParsingDone->run();
707 }
708 Visitor.set_active_ast_context(&Context);
Manuel Klimeke5793282012-11-02 01:31:03 +0000709 Visitor.onStartOfTranslationUnit();
Manuel Klimek4da21662012-07-06 05:48:52 +0000710 Visitor.TraverseDecl(Context.getTranslationUnitDecl());
711 Visitor.set_active_ast_context(NULL);
712 }
713
714 MatchASTVisitor Visitor;
715 MatchFinder::ParsingDoneTestCallback *ParsingDone;
716};
717
718} // end namespace
719} // end namespace internal
720
721MatchFinder::MatchResult::MatchResult(const BoundNodes &Nodes,
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000722 ASTContext *Context)
Manuel Klimek4da21662012-07-06 05:48:52 +0000723 : Nodes(Nodes), Context(Context),
724 SourceManager(&Context->getSourceManager()) {}
725
726MatchFinder::MatchCallback::~MatchCallback() {}
727MatchFinder::ParsingDoneTestCallback::~ParsingDoneTestCallback() {}
728
729MatchFinder::MatchFinder() : ParsingDone(NULL) {}
730
731MatchFinder::~MatchFinder() {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000732 for (std::vector<std::pair<const internal::DynTypedMatcher*,
733 MatchCallback*> >::const_iterator
734 It = MatcherCallbackPairs.begin(), End = MatcherCallbackPairs.end();
Manuel Klimek4da21662012-07-06 05:48:52 +0000735 It != End; ++It) {
736 delete It->first;
737 }
738}
739
740void MatchFinder::addMatcher(const DeclarationMatcher &NodeMatch,
741 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000742 MatcherCallbackPairs.push_back(std::make_pair(
743 new internal::Matcher<Decl>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000744}
745
746void MatchFinder::addMatcher(const TypeMatcher &NodeMatch,
747 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000748 MatcherCallbackPairs.push_back(std::make_pair(
749 new internal::Matcher<QualType>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000750}
751
752void MatchFinder::addMatcher(const StatementMatcher &NodeMatch,
753 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000754 MatcherCallbackPairs.push_back(std::make_pair(
755 new internal::Matcher<Stmt>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000756}
757
Daniel Jaspera7564432012-09-13 13:11:25 +0000758void MatchFinder::addMatcher(const NestedNameSpecifierMatcher &NodeMatch,
759 MatchCallback *Action) {
760 MatcherCallbackPairs.push_back(std::make_pair(
761 new NestedNameSpecifierMatcher(NodeMatch), Action));
762}
763
764void MatchFinder::addMatcher(const NestedNameSpecifierLocMatcher &NodeMatch,
765 MatchCallback *Action) {
766 MatcherCallbackPairs.push_back(std::make_pair(
767 new NestedNameSpecifierLocMatcher(NodeMatch), Action));
768}
769
Daniel Jasperce620072012-10-17 08:52:59 +0000770void MatchFinder::addMatcher(const TypeLocMatcher &NodeMatch,
771 MatchCallback *Action) {
772 MatcherCallbackPairs.push_back(std::make_pair(
773 new TypeLocMatcher(NodeMatch), Action));
774}
775
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000776ASTConsumer *MatchFinder::newASTConsumer() {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000777 return new internal::MatchASTConsumer(&MatcherCallbackPairs, ParsingDone);
Manuel Klimek4da21662012-07-06 05:48:52 +0000778}
779
Manuel Klimek3e2aa992012-10-24 14:47:44 +0000780void MatchFinder::findAll(const Decl &Node, ASTContext &Context) {
781 internal::MatchASTVisitor Visitor(&MatcherCallbackPairs);
782 Visitor.set_active_ast_context(&Context);
783 Visitor.TraverseDecl(const_cast<Decl*>(&Node));
784}
785
786void MatchFinder::findAll(const Stmt &Node, ASTContext &Context) {
787 internal::MatchASTVisitor Visitor(&MatcherCallbackPairs);
788 Visitor.set_active_ast_context(&Context);
789 Visitor.TraverseStmt(const_cast<Stmt*>(&Node));
790}
791
Manuel Klimek4da21662012-07-06 05:48:52 +0000792void MatchFinder::registerTestCallbackAfterParsing(
793 MatchFinder::ParsingDoneTestCallback *NewParsingDone) {
794 ParsingDone = NewParsingDone;
795}
796
797} // end namespace ast_matchers
798} // end namespace clang