blob: 218b78187db6ad3eda010c0f4cba6b8a5434ab15 [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),
127 CurrentDepth(-1),
128 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);
150 // FIXME: Add other base types after adding tests.
Manuel Klimek4da21662012-07-06 05:48:52 +0000151 return Matches;
152 }
153
154 // The following are overriding methods from the base visitor class.
155 // They are public only to allow CRTP to work. They are *not *part
156 // of the public API of this class.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000157 bool TraverseDecl(Decl *DeclNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000158 return (DeclNode == NULL) || traverse(*DeclNode);
159 }
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000160 bool TraverseStmt(Stmt *StmtNode) {
161 const Stmt *StmtToTraverse = StmtNode;
Manuel Klimek4da21662012-07-06 05:48:52 +0000162 if (Traversal ==
163 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses) {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000164 const Expr *ExprNode = dyn_cast_or_null<Expr>(StmtNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000165 if (ExprNode != NULL) {
166 StmtToTraverse = ExprNode->IgnoreParenImpCasts();
167 }
168 }
169 return (StmtToTraverse == NULL) || traverse(*StmtToTraverse);
170 }
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000171 bool TraverseType(QualType TypeNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000172 return traverse(TypeNode);
173 }
174
175 bool shouldVisitTemplateInstantiations() const { return true; }
176 bool shouldVisitImplicitCode() const { return true; }
177
178private:
179 // Used for updating the depth during traversal.
180 struct ScopedIncrement {
181 explicit ScopedIncrement(int *Depth) : Depth(Depth) { ++(*Depth); }
182 ~ScopedIncrement() { --(*Depth); }
183
184 private:
185 int *Depth;
186 };
187
188 // Resets the state of this object.
189 void reset() {
190 Matches = false;
191 CurrentDepth = -1;
192 }
193
194 // Forwards the call to the corresponding Traverse*() method in the
195 // base visitor class.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000196 bool baseTraverse(const Decl &DeclNode) {
197 return VisitorBase::TraverseDecl(const_cast<Decl*>(&DeclNode));
Manuel Klimek4da21662012-07-06 05:48:52 +0000198 }
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000199 bool baseTraverse(const Stmt &StmtNode) {
200 return VisitorBase::TraverseStmt(const_cast<Stmt*>(&StmtNode));
Manuel Klimek4da21662012-07-06 05:48:52 +0000201 }
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000202 bool baseTraverse(QualType TypeNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000203 return VisitorBase::TraverseType(TypeNode);
204 }
205
206 // Traverses the subtree rooted at 'node'; returns true if the
207 // traversal should continue after this function returns; also sets
208 // matched_ to true if a match is found during the traversal.
209 template <typename T>
210 bool traverse(const T &Node) {
211 TOOLING_COMPILE_ASSERT(IsBaseType<T>::value,
212 traverse_can_only_be_instantiated_with_base_type);
213 ScopedIncrement ScopedDepth(&CurrentDepth);
214 if (CurrentDepth == 0) {
215 // We don't want to match the root node, so just recurse.
216 return baseTraverse(Node);
217 }
218 if (Bind != ASTMatchFinder::BK_All) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000219 if (Matcher->matches(ast_type_traits::DynTypedNode::create(Node),
220 Finder, Builder)) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000221 Matches = true;
222 return false; // Abort as soon as a match is found.
223 }
224 if (CurrentDepth < MaxDepth) {
225 // The current node doesn't match, and we haven't reached the
226 // maximum depth yet, so recurse.
227 return baseTraverse(Node);
228 }
229 // The current node doesn't match, and we have reached the
230 // maximum depth, so don't recurse (but continue the traversal
231 // such that other nodes at the current level can be visited).
232 return true;
233 } else {
234 BoundNodesTreeBuilder RecursiveBuilder;
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000235 if (Matcher->matches(ast_type_traits::DynTypedNode::create(Node),
236 Finder, &RecursiveBuilder)) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000237 // After the first match the matcher succeeds.
238 Matches = true;
239 Builder->addMatch(RecursiveBuilder.build());
240 }
241 if (CurrentDepth < MaxDepth) {
242 baseTraverse(Node);
243 }
244 // In kBindAll mode we always search for more matches.
245 return true;
246 }
247 }
248
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000249 const DynTypedMatcher *const Matcher;
Manuel Klimek4da21662012-07-06 05:48:52 +0000250 ASTMatchFinder *const Finder;
251 BoundNodesTreeBuilder *const Builder;
252 int CurrentDepth;
253 const int MaxDepth;
254 const ASTMatchFinder::TraversalKind Traversal;
255 const ASTMatchFinder::BindKind Bind;
256 bool Matches;
257};
258
259// Controls the outermost traversal of the AST and allows to match multiple
260// matchers.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000261class MatchASTVisitor : public RecursiveASTVisitor<MatchASTVisitor>,
Manuel Klimek4da21662012-07-06 05:48:52 +0000262 public ASTMatchFinder {
263public:
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000264 MatchASTVisitor(std::vector<std::pair<const internal::DynTypedMatcher*,
265 MatchCallback*> > *MatcherCallbackPairs)
266 : MatcherCallbackPairs(MatcherCallbackPairs),
Manuel Klimek4da21662012-07-06 05:48:52 +0000267 ActiveASTContext(NULL) {
268 }
269
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000270 void set_active_ast_context(ASTContext *NewActiveASTContext) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000271 ActiveASTContext = NewActiveASTContext;
272 }
273
274 // The following Visit*() and Traverse*() functions "override"
275 // methods in RecursiveASTVisitor.
276
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000277 bool VisitTypedefDecl(TypedefDecl *DeclNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000278 // When we see 'typedef A B', we add name 'B' to the set of names
279 // A's canonical type maps to. This is necessary for implementing
Daniel Jasper76dafa72012-09-07 12:48:17 +0000280 // isDerivedFrom(x) properly, where x can be the name of the base
Manuel Klimek4da21662012-07-06 05:48:52 +0000281 // class or any of its aliases.
282 //
283 // In general, the is-alias-of (as defined by typedefs) relation
284 // is tree-shaped, as you can typedef a type more than once. For
285 // example,
286 //
287 // typedef A B;
288 // typedef A C;
289 // typedef C D;
290 // typedef C E;
291 //
292 // gives you
293 //
294 // A
295 // |- B
296 // `- C
297 // |- D
298 // `- E
299 //
300 // It is wrong to assume that the relation is a chain. A correct
Daniel Jasper76dafa72012-09-07 12:48:17 +0000301 // implementation of isDerivedFrom() needs to recognize that B and
Manuel Klimek4da21662012-07-06 05:48:52 +0000302 // E are aliases, even though neither is a typedef of the other.
303 // Therefore, we cannot simply walk through one typedef chain to
304 // find out whether the type name matches.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000305 const Type *TypeNode = DeclNode->getUnderlyingType().getTypePtr();
306 const Type *CanonicalType = // root of the typedef tree
Manuel Klimek4da21662012-07-06 05:48:52 +0000307 ActiveASTContext->getCanonicalType(TypeNode);
Daniel Jasper20b802d2012-07-17 07:39:27 +0000308 TypeAliases[CanonicalType].insert(DeclNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000309 return true;
310 }
311
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000312 bool TraverseDecl(Decl *DeclNode);
313 bool TraverseStmt(Stmt *StmtNode);
314 bool TraverseType(QualType TypeNode);
315 bool TraverseTypeLoc(TypeLoc TypeNode);
Daniel Jaspera7564432012-09-13 13:11:25 +0000316 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS);
317 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Manuel Klimek4da21662012-07-06 05:48:52 +0000318
319 // Matches children or descendants of 'Node' with 'BaseMatcher'.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000320 bool memoizedMatchesRecursively(const ast_type_traits::DynTypedNode &Node,
321 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000322 BoundNodesTreeBuilder *Builder, int MaxDepth,
323 TraversalKind Traversal, BindKind Bind) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000324 const UntypedMatchInput input(Matcher.getID(), Node.getMemoizationData());
325 assert(input.second &&
326 "Fix getMemoizationData once more types allow recursive matching.");
Manuel Klimek4da21662012-07-06 05:48:52 +0000327 std::pair<MemoizationMap::iterator, bool> InsertResult
328 = ResultCache.insert(std::make_pair(input, MemoizedMatchResult()));
329 if (InsertResult.second) {
330 BoundNodesTreeBuilder DescendantBoundNodesBuilder;
331 InsertResult.first->second.ResultOfMatch =
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000332 matchesRecursively(Node, Matcher, &DescendantBoundNodesBuilder,
Manuel Klimek4da21662012-07-06 05:48:52 +0000333 MaxDepth, Traversal, Bind);
334 InsertResult.first->second.Nodes =
335 DescendantBoundNodesBuilder.build();
336 }
337 InsertResult.first->second.Nodes.copyTo(Builder);
338 return InsertResult.first->second.ResultOfMatch;
339 }
340
341 // Matches children or descendants of 'Node' with 'BaseMatcher'.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000342 bool matchesRecursively(const ast_type_traits::DynTypedNode &Node,
343 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000344 BoundNodesTreeBuilder *Builder, int MaxDepth,
345 TraversalKind Traversal, BindKind Bind) {
346 MatchChildASTVisitor Visitor(
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000347 &Matcher, this, Builder, MaxDepth, Traversal, Bind);
Manuel Klimek4da21662012-07-06 05:48:52 +0000348 return Visitor.findMatch(Node);
349 }
350
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000351 virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
Daniel Jasper20b802d2012-07-17 07:39:27 +0000352 const Matcher<NamedDecl> &Base,
353 BoundNodesTreeBuilder *Builder);
Manuel Klimek4da21662012-07-06 05:48:52 +0000354
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000355 // Implements ASTMatchFinder::matchesChildOf.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000356 virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node,
357 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000358 BoundNodesTreeBuilder *Builder,
359 TraversalKind Traversal,
360 BindKind Bind) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000361 return matchesRecursively(Node, Matcher, Builder, 1, Traversal,
Manuel Klimek4da21662012-07-06 05:48:52 +0000362 Bind);
363 }
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000364 // Implements ASTMatchFinder::matchesDescendantOf.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000365 virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node,
366 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000367 BoundNodesTreeBuilder *Builder,
368 BindKind Bind) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000369 return memoizedMatchesRecursively(Node, Matcher, Builder, INT_MAX,
Manuel Klimek4da21662012-07-06 05:48:52 +0000370 TK_AsIs, Bind);
371 }
Manuel Klimek579b1202012-09-07 09:26:10 +0000372 // Implements ASTMatchFinder::matchesAncestorOf.
373 virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node,
374 const DynTypedMatcher &Matcher,
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000375 BoundNodesTreeBuilder *Builder,
376 AncestorMatchMode MatchMode) {
Manuel Klimek579b1202012-09-07 09:26:10 +0000377 if (!Parents) {
378 // We always need to run over the whole translation unit, as
379 // \c hasAncestor can escape any subtree.
380 Parents.reset(ParentMapASTVisitor::buildMap(
381 *ActiveASTContext->getTranslationUnitDecl()));
382 }
383 ast_type_traits::DynTypedNode Ancestor = Node;
384 while (Ancestor.get<TranslationUnitDecl>() !=
385 ActiveASTContext->getTranslationUnitDecl()) {
386 assert(Ancestor.getMemoizationData() &&
387 "Invariant broken: only nodes that support memoization may be "
388 "used in the parent map.");
389 ParentMapASTVisitor::ParentMap::const_iterator I =
390 Parents->find(Ancestor.getMemoizationData());
391 if (I == Parents->end()) {
392 assert(false &&
393 "Found node that is not in the parent map.");
394 return false;
395 }
396 Ancestor = I->second;
397 if (Matcher.matches(Ancestor, this, Builder))
398 return true;
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000399 if (MatchMode == ASTMatchFinder::AMM_ParentOnly)
400 return false;
Manuel Klimek579b1202012-09-07 09:26:10 +0000401 }
402 return false;
403 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000404
405 bool shouldVisitTemplateInstantiations() const { return true; }
406 bool shouldVisitImplicitCode() const { return true; }
407
408private:
409 // Implements a BoundNodesTree::Visitor that calls a MatchCallback with
410 // the aggregated bound nodes for each match.
411 class MatchVisitor : public BoundNodesTree::Visitor {
412 public:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000413 MatchVisitor(ASTContext* Context,
Manuel Klimek4da21662012-07-06 05:48:52 +0000414 MatchFinder::MatchCallback* Callback)
415 : Context(Context),
416 Callback(Callback) {}
417
418 virtual void visitMatch(const BoundNodes& BoundNodesView) {
419 Callback->run(MatchFinder::MatchResult(BoundNodesView, Context));
420 }
421
422 private:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000423 ASTContext* Context;
Manuel Klimek4da21662012-07-06 05:48:52 +0000424 MatchFinder::MatchCallback* Callback;
425 };
426
Daniel Jasper20b802d2012-07-17 07:39:27 +0000427 // Returns true if 'TypeNode' has an alias that matches the given matcher.
428 bool typeHasMatchingAlias(const Type *TypeNode,
429 const Matcher<NamedDecl> Matcher,
430 BoundNodesTreeBuilder *Builder) {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000431 const Type *const CanonicalType =
Manuel Klimek4da21662012-07-06 05:48:52 +0000432 ActiveASTContext->getCanonicalType(TypeNode);
Daniel Jasper20b802d2012-07-17 07:39:27 +0000433 const std::set<const TypedefDecl*> &Aliases = TypeAliases[CanonicalType];
434 for (std::set<const TypedefDecl*>::const_iterator
435 It = Aliases.begin(), End = Aliases.end();
436 It != End; ++It) {
437 if (Matcher.matches(**It, this, Builder))
438 return true;
439 }
440 return false;
Manuel Klimek4da21662012-07-06 05:48:52 +0000441 }
442
443 // Matches all registered matchers on the given node and calls the
444 // result callback for every node that matches.
445 template <typename T>
446 void match(const T &node) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000447 for (std::vector<std::pair<const internal::DynTypedMatcher*,
448 MatchCallback*> >::const_iterator
449 I = MatcherCallbackPairs->begin(), E = MatcherCallbackPairs->end();
450 I != E; ++I) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000451 BoundNodesTreeBuilder Builder;
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000452 if (I->first->matches(ast_type_traits::DynTypedNode::create(node),
453 this, &Builder)) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000454 BoundNodesTree BoundNodes = Builder.build();
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000455 MatchVisitor Visitor(ActiveASTContext, I->second);
Manuel Klimek4da21662012-07-06 05:48:52 +0000456 BoundNodes.visitMatches(&Visitor);
457 }
458 }
459 }
460
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000461 std::vector<std::pair<const internal::DynTypedMatcher*,
462 MatchCallback*> > *const MatcherCallbackPairs;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000463 ASTContext *ActiveASTContext;
Manuel Klimek4da21662012-07-06 05:48:52 +0000464
Daniel Jasper20b802d2012-07-17 07:39:27 +0000465 // Maps a canonical type to its TypedefDecls.
466 llvm::DenseMap<const Type*, std::set<const TypedefDecl*> > TypeAliases;
Manuel Klimek4da21662012-07-06 05:48:52 +0000467
468 // Maps (matcher, node) -> the match result for memoization.
469 typedef llvm::DenseMap<UntypedMatchInput, MemoizedMatchResult> MemoizationMap;
470 MemoizationMap ResultCache;
Manuel Klimek579b1202012-09-07 09:26:10 +0000471
472 llvm::OwningPtr<ParentMapASTVisitor::ParentMap> Parents;
Manuel Klimek4da21662012-07-06 05:48:52 +0000473};
474
475// Returns true if the given class is directly or indirectly derived
Daniel Jasper76dafa72012-09-07 12:48:17 +0000476// from a base type with the given name. A class is not considered to be
477// derived from itself.
Daniel Jasper20b802d2012-07-17 07:39:27 +0000478bool MatchASTVisitor::classIsDerivedFrom(const CXXRecordDecl *Declaration,
479 const Matcher<NamedDecl> &Base,
480 BoundNodesTreeBuilder *Builder) {
Daniel Jasper20b802d2012-07-17 07:39:27 +0000481 if (!Declaration->hasDefinition())
Manuel Klimek4da21662012-07-06 05:48:52 +0000482 return false;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000483 typedef CXXRecordDecl::base_class_const_iterator BaseIterator;
Manuel Klimek4da21662012-07-06 05:48:52 +0000484 for (BaseIterator It = Declaration->bases_begin(),
485 End = Declaration->bases_end(); It != End; ++It) {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000486 const Type *TypeNode = It->getType().getTypePtr();
Manuel Klimek4da21662012-07-06 05:48:52 +0000487
Daniel Jasper20b802d2012-07-17 07:39:27 +0000488 if (typeHasMatchingAlias(TypeNode, Base, Builder))
Manuel Klimek4da21662012-07-06 05:48:52 +0000489 return true;
490
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000491 // Type::getAs<...>() drills through typedefs.
492 if (TypeNode->getAs<DependentNameType>() != NULL ||
Daniel Jasper08f0c532012-09-18 14:17:42 +0000493 TypeNode->getAs<DependentTemplateSpecializationType>() != NULL ||
Daniel Jasper20b802d2012-07-17 07:39:27 +0000494 TypeNode->getAs<TemplateTypeParmType>() != NULL)
Manuel Klimek4da21662012-07-06 05:48:52 +0000495 // Dependent names and template TypeNode parameters will be matched when
496 // the template is instantiated.
497 continue;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000498 CXXRecordDecl *ClassDecl = NULL;
499 TemplateSpecializationType const *TemplateType =
500 TypeNode->getAs<TemplateSpecializationType>();
Manuel Klimek4da21662012-07-06 05:48:52 +0000501 if (TemplateType != NULL) {
Daniel Jasper20b802d2012-07-17 07:39:27 +0000502 if (TemplateType->getTemplateName().isDependent())
Manuel Klimek4da21662012-07-06 05:48:52 +0000503 // Dependent template specializations will be matched when the
504 // template is instantiated.
505 continue;
Daniel Jasper20b802d2012-07-17 07:39:27 +0000506
Manuel Klimek4da21662012-07-06 05:48:52 +0000507 // For template specialization types which are specializing a template
508 // declaration which is an explicit or partial specialization of another
509 // template declaration, getAsCXXRecordDecl() returns the corresponding
510 // ClassTemplateSpecializationDecl.
511 //
512 // For template specialization types which are specializing a template
513 // declaration which is neither an explicit nor partial specialization of
514 // another template declaration, getAsCXXRecordDecl() returns NULL and
515 // we get the CXXRecordDecl of the templated declaration.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000516 CXXRecordDecl *SpecializationDecl =
Manuel Klimek4da21662012-07-06 05:48:52 +0000517 TemplateType->getAsCXXRecordDecl();
518 if (SpecializationDecl != NULL) {
519 ClassDecl = SpecializationDecl;
520 } else {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000521 ClassDecl = llvm::dyn_cast<CXXRecordDecl>(
Manuel Klimek4da21662012-07-06 05:48:52 +0000522 TemplateType->getTemplateName()
523 .getAsTemplateDecl()->getTemplatedDecl());
524 }
525 } else {
526 ClassDecl = TypeNode->getAsCXXRecordDecl();
527 }
528 assert(ClassDecl != NULL);
529 assert(ClassDecl != Declaration);
Daniel Jasper76dafa72012-09-07 12:48:17 +0000530 if (Base.matches(*ClassDecl, this, Builder))
531 return true;
Daniel Jasper20b802d2012-07-17 07:39:27 +0000532 if (classIsDerivedFrom(ClassDecl, Base, Builder))
Manuel Klimek4da21662012-07-06 05:48:52 +0000533 return true;
Manuel Klimek4da21662012-07-06 05:48:52 +0000534 }
535 return false;
536}
537
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000538bool MatchASTVisitor::TraverseDecl(Decl *DeclNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000539 if (DeclNode == NULL) {
540 return true;
541 }
542 match(*DeclNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000543 return RecursiveASTVisitor<MatchASTVisitor>::TraverseDecl(DeclNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000544}
545
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000546bool MatchASTVisitor::TraverseStmt(Stmt *StmtNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000547 if (StmtNode == NULL) {
548 return true;
549 }
550 match(*StmtNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000551 return RecursiveASTVisitor<MatchASTVisitor>::TraverseStmt(StmtNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000552}
553
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000554bool MatchASTVisitor::TraverseType(QualType TypeNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000555 match(TypeNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000556 return RecursiveASTVisitor<MatchASTVisitor>::TraverseType(TypeNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000557}
558
Daniel Jasperce620072012-10-17 08:52:59 +0000559bool MatchASTVisitor::TraverseTypeLoc(TypeLoc TypeLocNode) {
560 // The RecursiveASTVisitor only visits types if they're not within TypeLocs.
561 // We still want to find those types via matchers, so we match them here. Note
562 // that the TypeLocs are structurally a shadow-hierarchy to the expressed
563 // type, so we visit all involved parts of a compound type when matching on
564 // each TypeLoc.
565 match(TypeLocNode);
566 match(TypeLocNode.getType());
567 return RecursiveASTVisitor<MatchASTVisitor>::TraverseTypeLoc(TypeLocNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000568}
569
Daniel Jaspera7564432012-09-13 13:11:25 +0000570bool MatchASTVisitor::TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
571 match(*NNS);
572 return RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifier(NNS);
573}
574
575bool MatchASTVisitor::TraverseNestedNameSpecifierLoc(
576 NestedNameSpecifierLoc NNS) {
577 match(NNS);
578 // We only match the nested name specifier here (as opposed to traversing it)
579 // because the traversal is already done in the parallel "Loc"-hierarchy.
580 match(*NNS.getNestedNameSpecifier());
581 return
582 RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifierLoc(NNS);
583}
584
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000585class MatchASTConsumer : public ASTConsumer {
Manuel Klimek4da21662012-07-06 05:48:52 +0000586public:
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000587 MatchASTConsumer(
588 std::vector<std::pair<const internal::DynTypedMatcher*,
589 MatchCallback*> > *MatcherCallbackPairs,
590 MatchFinder::ParsingDoneTestCallback *ParsingDone)
591 : Visitor(MatcherCallbackPairs),
592 ParsingDone(ParsingDone) {}
Manuel Klimek4da21662012-07-06 05:48:52 +0000593
594private:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000595 virtual void HandleTranslationUnit(ASTContext &Context) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000596 if (ParsingDone != NULL) {
597 ParsingDone->run();
598 }
599 Visitor.set_active_ast_context(&Context);
600 Visitor.TraverseDecl(Context.getTranslationUnitDecl());
601 Visitor.set_active_ast_context(NULL);
602 }
603
604 MatchASTVisitor Visitor;
605 MatchFinder::ParsingDoneTestCallback *ParsingDone;
606};
607
608} // end namespace
609} // end namespace internal
610
611MatchFinder::MatchResult::MatchResult(const BoundNodes &Nodes,
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000612 ASTContext *Context)
Manuel Klimek4da21662012-07-06 05:48:52 +0000613 : Nodes(Nodes), Context(Context),
614 SourceManager(&Context->getSourceManager()) {}
615
616MatchFinder::MatchCallback::~MatchCallback() {}
617MatchFinder::ParsingDoneTestCallback::~ParsingDoneTestCallback() {}
618
619MatchFinder::MatchFinder() : ParsingDone(NULL) {}
620
621MatchFinder::~MatchFinder() {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000622 for (std::vector<std::pair<const internal::DynTypedMatcher*,
623 MatchCallback*> >::const_iterator
624 It = MatcherCallbackPairs.begin(), End = MatcherCallbackPairs.end();
Manuel Klimek4da21662012-07-06 05:48:52 +0000625 It != End; ++It) {
626 delete It->first;
627 }
628}
629
630void MatchFinder::addMatcher(const DeclarationMatcher &NodeMatch,
631 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000632 MatcherCallbackPairs.push_back(std::make_pair(
633 new internal::Matcher<Decl>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000634}
635
636void MatchFinder::addMatcher(const TypeMatcher &NodeMatch,
637 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000638 MatcherCallbackPairs.push_back(std::make_pair(
639 new internal::Matcher<QualType>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000640}
641
642void MatchFinder::addMatcher(const StatementMatcher &NodeMatch,
643 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000644 MatcherCallbackPairs.push_back(std::make_pair(
645 new internal::Matcher<Stmt>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000646}
647
Daniel Jaspera7564432012-09-13 13:11:25 +0000648void MatchFinder::addMatcher(const NestedNameSpecifierMatcher &NodeMatch,
649 MatchCallback *Action) {
650 MatcherCallbackPairs.push_back(std::make_pair(
651 new NestedNameSpecifierMatcher(NodeMatch), Action));
652}
653
654void MatchFinder::addMatcher(const NestedNameSpecifierLocMatcher &NodeMatch,
655 MatchCallback *Action) {
656 MatcherCallbackPairs.push_back(std::make_pair(
657 new NestedNameSpecifierLocMatcher(NodeMatch), Action));
658}
659
Daniel Jasperce620072012-10-17 08:52:59 +0000660void MatchFinder::addMatcher(const TypeLocMatcher &NodeMatch,
661 MatchCallback *Action) {
662 MatcherCallbackPairs.push_back(std::make_pair(
663 new TypeLocMatcher(NodeMatch), Action));
664}
665
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000666ASTConsumer *MatchFinder::newASTConsumer() {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000667 return new internal::MatchASTConsumer(&MatcherCallbackPairs, ParsingDone);
Manuel Klimek4da21662012-07-06 05:48:52 +0000668}
669
Manuel Klimek3e2aa992012-10-24 14:47:44 +0000670void MatchFinder::findAll(const Decl &Node, ASTContext &Context) {
671 internal::MatchASTVisitor Visitor(&MatcherCallbackPairs);
672 Visitor.set_active_ast_context(&Context);
673 Visitor.TraverseDecl(const_cast<Decl*>(&Node));
674}
675
676void MatchFinder::findAll(const Stmt &Node, ASTContext &Context) {
677 internal::MatchASTVisitor Visitor(&MatcherCallbackPairs);
678 Visitor.set_active_ast_context(&Context);
679 Visitor.TraverseStmt(const_cast<Stmt*>(&Node));
680}
681
Manuel Klimek4da21662012-07-06 05:48:52 +0000682void MatchFinder::registerTestCallbackAfterParsing(
683 MatchFinder::ParsingDoneTestCallback *NewParsingDone) {
684 ParsingDone = NewParsingDone;
685}
686
687} // end namespace ast_matchers
688} // end namespace clang