blob: 3a3c1fb6e17d550aaa88b2a8932cdd5361877cd7 [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.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000043 typedef SmallVector<ast_type_traits::DynTypedNode, 1> ParentVector;
Manuel Klimek30ace372012-12-06 14:42:48 +000044
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;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000097 SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
Manuel Klimek579b1202012-09-07 09:26:10 +000098
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 Klimek60969f52013-02-01 13:41:35 +0000470 // Matches all registered matchers on the given node and calls the
471 // result callback for every node that matches.
472 void match(const ast_type_traits::DynTypedNode& Node) {
473 for (std::vector<std::pair<const internal::DynTypedMatcher*,
474 MatchCallback*> >::const_iterator
475 I = MatcherCallbackPairs->begin(), E = MatcherCallbackPairs->end();
476 I != E; ++I) {
477 BoundNodesTreeBuilder Builder;
478 if (I->first->matches(Node, this, &Builder)) {
479 BoundNodesTree BoundNodes = Builder.build();
480 MatchVisitor Visitor(ActiveASTContext, I->second);
481 BoundNodes.visitMatches(&Visitor);
482 }
483 }
484 }
485
486 template <typename T> void match(const T &Node) {
487 match(ast_type_traits::DynTypedNode::create(Node));
488 }
489
Manuel Klimek7f2d4802012-11-30 13:45:19 +0000490 // Implements ASTMatchFinder::getASTContext.
491 virtual ASTContext &getASTContext() const { return *ActiveASTContext; }
492
Manuel Klimek4da21662012-07-06 05:48:52 +0000493 bool shouldVisitTemplateInstantiations() const { return true; }
494 bool shouldVisitImplicitCode() const { return true; }
Daniel Jasper278057f2012-11-15 03:29:05 +0000495 // Disables data recursion. We intercept Traverse* methods in the RAV, which
496 // are not triggered during data recursion.
497 bool shouldUseDataRecursionFor(clang::Stmt *S) const { return false; }
Manuel Klimek4da21662012-07-06 05:48:52 +0000498
499private:
Manuel Klimek30ace372012-12-06 14:42:48 +0000500 bool matchesAncestorOfRecursively(
501 const ast_type_traits::DynTypedNode &Node, const DynTypedMatcher &Matcher,
502 BoundNodesTreeBuilder *Builder, AncestorMatchMode MatchMode) {
503 if (Node.get<TranslationUnitDecl>() ==
504 ActiveASTContext->getTranslationUnitDecl())
505 return false;
506 assert(Node.getMemoizationData() &&
507 "Invariant broken: only nodes that support memoization may be "
508 "used in the parent map.");
509 ParentMapASTVisitor::ParentMap::const_iterator I =
510 Parents->find(Node.getMemoizationData());
511 if (I == Parents->end()) {
512 assert(false && "Found node that is not in the parent map.");
513 return false;
514 }
515 for (ParentMapASTVisitor::ParentVector::const_iterator AncestorI =
516 I->second.begin(), AncestorE = I->second.end();
517 AncestorI != AncestorE; ++AncestorI) {
518 if (Matcher.matches(*AncestorI, this, Builder))
519 return true;
520 }
521 if (MatchMode == ASTMatchFinder::AMM_ParentOnly)
522 return false;
523 for (ParentMapASTVisitor::ParentVector::const_iterator AncestorI =
524 I->second.begin(), AncestorE = I->second.end();
525 AncestorI != AncestorE; ++AncestorI) {
526 if (matchesAncestorOfRecursively(*AncestorI, Matcher, Builder, MatchMode))
527 return true;
528 }
529 return false;
530 }
531
532
Manuel Klimek4da21662012-07-06 05:48:52 +0000533 // Implements a BoundNodesTree::Visitor that calls a MatchCallback with
534 // the aggregated bound nodes for each match.
535 class MatchVisitor : public BoundNodesTree::Visitor {
536 public:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000537 MatchVisitor(ASTContext* Context,
Manuel Klimek4da21662012-07-06 05:48:52 +0000538 MatchFinder::MatchCallback* Callback)
539 : Context(Context),
540 Callback(Callback) {}
541
542 virtual void visitMatch(const BoundNodes& BoundNodesView) {
543 Callback->run(MatchFinder::MatchResult(BoundNodesView, Context));
544 }
545
546 private:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000547 ASTContext* Context;
Manuel Klimek4da21662012-07-06 05:48:52 +0000548 MatchFinder::MatchCallback* Callback;
549 };
550
Daniel Jasper20b802d2012-07-17 07:39:27 +0000551 // Returns true if 'TypeNode' has an alias that matches the given matcher.
552 bool typeHasMatchingAlias(const Type *TypeNode,
553 const Matcher<NamedDecl> Matcher,
554 BoundNodesTreeBuilder *Builder) {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000555 const Type *const CanonicalType =
Manuel Klimek4da21662012-07-06 05:48:52 +0000556 ActiveASTContext->getCanonicalType(TypeNode);
Daniel Jasper20b802d2012-07-17 07:39:27 +0000557 const std::set<const TypedefDecl*> &Aliases = TypeAliases[CanonicalType];
558 for (std::set<const TypedefDecl*>::const_iterator
559 It = Aliases.begin(), End = Aliases.end();
560 It != End; ++It) {
561 if (Matcher.matches(**It, this, Builder))
562 return true;
563 }
564 return false;
Manuel Klimek4da21662012-07-06 05:48:52 +0000565 }
566
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000567 std::vector<std::pair<const internal::DynTypedMatcher*,
568 MatchCallback*> > *const MatcherCallbackPairs;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000569 ASTContext *ActiveASTContext;
Manuel Klimek4da21662012-07-06 05:48:52 +0000570
Daniel Jasper20b802d2012-07-17 07:39:27 +0000571 // Maps a canonical type to its TypedefDecls.
572 llvm::DenseMap<const Type*, std::set<const TypedefDecl*> > TypeAliases;
Manuel Klimek4da21662012-07-06 05:48:52 +0000573
574 // Maps (matcher, node) -> the match result for memoization.
575 typedef llvm::DenseMap<UntypedMatchInput, MemoizedMatchResult> MemoizationMap;
576 MemoizationMap ResultCache;
Manuel Klimek579b1202012-09-07 09:26:10 +0000577
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000578 OwningPtr<ParentMapASTVisitor::ParentMap> Parents;
Manuel Klimek4da21662012-07-06 05:48:52 +0000579};
580
581// Returns true if the given class is directly or indirectly derived
Daniel Jasper76dafa72012-09-07 12:48:17 +0000582// from a base type with the given name. A class is not considered to be
583// derived from itself.
Daniel Jasper20b802d2012-07-17 07:39:27 +0000584bool MatchASTVisitor::classIsDerivedFrom(const CXXRecordDecl *Declaration,
585 const Matcher<NamedDecl> &Base,
586 BoundNodesTreeBuilder *Builder) {
Daniel Jasper20b802d2012-07-17 07:39:27 +0000587 if (!Declaration->hasDefinition())
Manuel Klimek4da21662012-07-06 05:48:52 +0000588 return false;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000589 typedef CXXRecordDecl::base_class_const_iterator BaseIterator;
Manuel Klimek4da21662012-07-06 05:48:52 +0000590 for (BaseIterator It = Declaration->bases_begin(),
591 End = Declaration->bases_end(); It != End; ++It) {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000592 const Type *TypeNode = It->getType().getTypePtr();
Manuel Klimek4da21662012-07-06 05:48:52 +0000593
Daniel Jasper20b802d2012-07-17 07:39:27 +0000594 if (typeHasMatchingAlias(TypeNode, Base, Builder))
Manuel Klimek4da21662012-07-06 05:48:52 +0000595 return true;
596
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000597 // Type::getAs<...>() drills through typedefs.
598 if (TypeNode->getAs<DependentNameType>() != NULL ||
Daniel Jasper08f0c532012-09-18 14:17:42 +0000599 TypeNode->getAs<DependentTemplateSpecializationType>() != NULL ||
Daniel Jasper20b802d2012-07-17 07:39:27 +0000600 TypeNode->getAs<TemplateTypeParmType>() != NULL)
Manuel Klimek4da21662012-07-06 05:48:52 +0000601 // Dependent names and template TypeNode parameters will be matched when
602 // the template is instantiated.
603 continue;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000604 CXXRecordDecl *ClassDecl = NULL;
605 TemplateSpecializationType const *TemplateType =
606 TypeNode->getAs<TemplateSpecializationType>();
Manuel Klimek4da21662012-07-06 05:48:52 +0000607 if (TemplateType != NULL) {
Daniel Jasper20b802d2012-07-17 07:39:27 +0000608 if (TemplateType->getTemplateName().isDependent())
Manuel Klimek4da21662012-07-06 05:48:52 +0000609 // Dependent template specializations will be matched when the
610 // template is instantiated.
611 continue;
Daniel Jasper20b802d2012-07-17 07:39:27 +0000612
Manuel Klimek4da21662012-07-06 05:48:52 +0000613 // For template specialization types which are specializing a template
614 // declaration which is an explicit or partial specialization of another
615 // template declaration, getAsCXXRecordDecl() returns the corresponding
616 // ClassTemplateSpecializationDecl.
617 //
618 // For template specialization types which are specializing a template
619 // declaration which is neither an explicit nor partial specialization of
620 // another template declaration, getAsCXXRecordDecl() returns NULL and
621 // we get the CXXRecordDecl of the templated declaration.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000622 CXXRecordDecl *SpecializationDecl =
Manuel Klimek4da21662012-07-06 05:48:52 +0000623 TemplateType->getAsCXXRecordDecl();
624 if (SpecializationDecl != NULL) {
625 ClassDecl = SpecializationDecl;
626 } else {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000627 ClassDecl = dyn_cast<CXXRecordDecl>(
Manuel Klimek4da21662012-07-06 05:48:52 +0000628 TemplateType->getTemplateName()
629 .getAsTemplateDecl()->getTemplatedDecl());
630 }
631 } else {
632 ClassDecl = TypeNode->getAsCXXRecordDecl();
633 }
634 assert(ClassDecl != NULL);
Manuel Klimek987c2f52012-12-04 13:40:29 +0000635 if (ClassDecl == Declaration) {
636 // This can happen for recursive template definitions; if the
637 // current declaration did not match, we can safely return false.
638 assert(TemplateType);
639 return false;
640 }
Daniel Jasper76dafa72012-09-07 12:48:17 +0000641 if (Base.matches(*ClassDecl, this, Builder))
642 return true;
Daniel Jasper20b802d2012-07-17 07:39:27 +0000643 if (classIsDerivedFrom(ClassDecl, Base, Builder))
Manuel Klimek4da21662012-07-06 05:48:52 +0000644 return true;
Manuel Klimek4da21662012-07-06 05:48:52 +0000645 }
646 return false;
647}
648
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000649bool MatchASTVisitor::TraverseDecl(Decl *DeclNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000650 if (DeclNode == NULL) {
651 return true;
652 }
653 match(*DeclNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000654 return RecursiveASTVisitor<MatchASTVisitor>::TraverseDecl(DeclNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000655}
656
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000657bool MatchASTVisitor::TraverseStmt(Stmt *StmtNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000658 if (StmtNode == NULL) {
659 return true;
660 }
661 match(*StmtNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000662 return RecursiveASTVisitor<MatchASTVisitor>::TraverseStmt(StmtNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000663}
664
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000665bool MatchASTVisitor::TraverseType(QualType TypeNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000666 match(TypeNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000667 return RecursiveASTVisitor<MatchASTVisitor>::TraverseType(TypeNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000668}
669
Daniel Jasperce620072012-10-17 08:52:59 +0000670bool MatchASTVisitor::TraverseTypeLoc(TypeLoc TypeLocNode) {
671 // The RecursiveASTVisitor only visits types if they're not within TypeLocs.
672 // We still want to find those types via matchers, so we match them here. Note
673 // that the TypeLocs are structurally a shadow-hierarchy to the expressed
674 // type, so we visit all involved parts of a compound type when matching on
675 // each TypeLoc.
676 match(TypeLocNode);
677 match(TypeLocNode.getType());
678 return RecursiveASTVisitor<MatchASTVisitor>::TraverseTypeLoc(TypeLocNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000679}
680
Daniel Jaspera7564432012-09-13 13:11:25 +0000681bool MatchASTVisitor::TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
682 match(*NNS);
683 return RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifier(NNS);
684}
685
686bool MatchASTVisitor::TraverseNestedNameSpecifierLoc(
687 NestedNameSpecifierLoc NNS) {
688 match(NNS);
689 // We only match the nested name specifier here (as opposed to traversing it)
690 // because the traversal is already done in the parallel "Loc"-hierarchy.
691 match(*NNS.getNestedNameSpecifier());
692 return
693 RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifierLoc(NNS);
694}
695
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000696class MatchASTConsumer : public ASTConsumer {
Manuel Klimek4da21662012-07-06 05:48:52 +0000697public:
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000698 MatchASTConsumer(
699 std::vector<std::pair<const internal::DynTypedMatcher*,
700 MatchCallback*> > *MatcherCallbackPairs,
701 MatchFinder::ParsingDoneTestCallback *ParsingDone)
702 : Visitor(MatcherCallbackPairs),
703 ParsingDone(ParsingDone) {}
Manuel Klimek4da21662012-07-06 05:48:52 +0000704
705private:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000706 virtual void HandleTranslationUnit(ASTContext &Context) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000707 if (ParsingDone != NULL) {
708 ParsingDone->run();
709 }
710 Visitor.set_active_ast_context(&Context);
Manuel Klimeke5793282012-11-02 01:31:03 +0000711 Visitor.onStartOfTranslationUnit();
Manuel Klimek4da21662012-07-06 05:48:52 +0000712 Visitor.TraverseDecl(Context.getTranslationUnitDecl());
713 Visitor.set_active_ast_context(NULL);
714 }
715
716 MatchASTVisitor Visitor;
717 MatchFinder::ParsingDoneTestCallback *ParsingDone;
718};
719
720} // end namespace
721} // end namespace internal
722
723MatchFinder::MatchResult::MatchResult(const BoundNodes &Nodes,
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000724 ASTContext *Context)
Manuel Klimek4da21662012-07-06 05:48:52 +0000725 : Nodes(Nodes), Context(Context),
726 SourceManager(&Context->getSourceManager()) {}
727
728MatchFinder::MatchCallback::~MatchCallback() {}
729MatchFinder::ParsingDoneTestCallback::~ParsingDoneTestCallback() {}
730
731MatchFinder::MatchFinder() : ParsingDone(NULL) {}
732
733MatchFinder::~MatchFinder() {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000734 for (std::vector<std::pair<const internal::DynTypedMatcher*,
735 MatchCallback*> >::const_iterator
736 It = MatcherCallbackPairs.begin(), End = MatcherCallbackPairs.end();
Manuel Klimek4da21662012-07-06 05:48:52 +0000737 It != End; ++It) {
738 delete It->first;
739 }
740}
741
742void MatchFinder::addMatcher(const DeclarationMatcher &NodeMatch,
743 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000744 MatcherCallbackPairs.push_back(std::make_pair(
745 new internal::Matcher<Decl>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000746}
747
748void MatchFinder::addMatcher(const TypeMatcher &NodeMatch,
749 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000750 MatcherCallbackPairs.push_back(std::make_pair(
751 new internal::Matcher<QualType>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000752}
753
754void MatchFinder::addMatcher(const StatementMatcher &NodeMatch,
755 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000756 MatcherCallbackPairs.push_back(std::make_pair(
757 new internal::Matcher<Stmt>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000758}
759
Daniel Jaspera7564432012-09-13 13:11:25 +0000760void MatchFinder::addMatcher(const NestedNameSpecifierMatcher &NodeMatch,
761 MatchCallback *Action) {
762 MatcherCallbackPairs.push_back(std::make_pair(
763 new NestedNameSpecifierMatcher(NodeMatch), Action));
764}
765
766void MatchFinder::addMatcher(const NestedNameSpecifierLocMatcher &NodeMatch,
767 MatchCallback *Action) {
768 MatcherCallbackPairs.push_back(std::make_pair(
769 new NestedNameSpecifierLocMatcher(NodeMatch), Action));
770}
771
Daniel Jasperce620072012-10-17 08:52:59 +0000772void MatchFinder::addMatcher(const TypeLocMatcher &NodeMatch,
773 MatchCallback *Action) {
774 MatcherCallbackPairs.push_back(std::make_pair(
775 new TypeLocMatcher(NodeMatch), Action));
776}
777
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000778ASTConsumer *MatchFinder::newASTConsumer() {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000779 return new internal::MatchASTConsumer(&MatcherCallbackPairs, ParsingDone);
Manuel Klimek4da21662012-07-06 05:48:52 +0000780}
781
Manuel Klimek60969f52013-02-01 13:41:35 +0000782void MatchFinder::match(const clang::ast_type_traits::DynTypedNode &Node,
783 ASTContext &Context) {
Manuel Klimek3e2aa992012-10-24 14:47:44 +0000784 internal::MatchASTVisitor Visitor(&MatcherCallbackPairs);
785 Visitor.set_active_ast_context(&Context);
Manuel Klimek60969f52013-02-01 13:41:35 +0000786 Visitor.match(Node);
Manuel Klimek3e2aa992012-10-24 14:47:44 +0000787}
788
Manuel Klimek4da21662012-07-06 05:48:52 +0000789void MatchFinder::registerTestCallbackAfterParsing(
790 MatchFinder::ParsingDoneTestCallback *NewParsingDone) {
791 ParsingDone = NewParsingDone;
792}
793
794} // end namespace ast_matchers
795} // end namespace clang