blob: 6ff125bc8358b436e597d702f159eb864746bc8f [file] [log] [blame]
Manuel Klimek4da21662012-07-06 05:48:52 +00001//===--- ASTMatchFinder.cpp - Structural query framework ------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Implements an algorithm to efficiently search for matches on AST nodes.
11// Uses memoization to support recursive matches like HasDescendant.
12//
13// The general idea is to visit all AST nodes with a RecursiveASTVisitor,
14// calling the Matches(...) method of each matcher we are running on each
15// AST node. The matcher can recurse via the ASTMatchFinder interface.
16//
17//===----------------------------------------------------------------------===//
18
19#include "clang/ASTMatchers/ASTMatchFinder.h"
20#include "clang/AST/ASTConsumer.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/RecursiveASTVisitor.h"
23#include <set>
24
25namespace clang {
26namespace ast_matchers {
27namespace internal {
28namespace {
29
Manuel Klimeka78d0d62012-09-05 12:12:07 +000030typedef MatchFinder::MatchCallback MatchCallback;
31
Manuel Klimek579b1202012-09-07 09:26:10 +000032/// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
33/// parents as defined by the \c RecursiveASTVisitor.
34///
35/// Note that the relationship described here is purely in terms of AST
36/// traversal - there are other relationships (for example declaration context)
37/// in the AST that are better modeled by special matchers.
38///
39/// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
40class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
41public:
42 /// \brief Maps from a node to its parent.
43 typedef llvm::DenseMap<const void*, ast_type_traits::DynTypedNode> ParentMap;
44
45 /// \brief Builds and returns the translation unit's parent map.
46 ///
47 /// The caller takes ownership of the returned \c ParentMap.
48 static ParentMap *buildMap(TranslationUnitDecl &TU) {
49 ParentMapASTVisitor Visitor(new ParentMap);
50 Visitor.TraverseDecl(&TU);
51 return Visitor.Parents;
52 }
53
54private:
55 typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
56
57 ParentMapASTVisitor(ParentMap *Parents) : Parents(Parents) {}
58
59 bool shouldVisitTemplateInstantiations() const { return true; }
60 bool shouldVisitImplicitCode() const { return true; }
61
62 template <typename T>
63 bool TraverseNode(T *Node, bool (VisitorBase::*traverse)(T*)) {
64 if (Node == NULL)
65 return true;
66 if (ParentStack.size() > 0)
67 (*Parents)[Node] = ParentStack.back();
68 ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
69 bool Result = (this->*traverse)(Node);
70 ParentStack.pop_back();
71 return Result;
72 }
73
74 bool TraverseDecl(Decl *DeclNode) {
75 return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
76 }
77
78 bool TraverseStmt(Stmt *StmtNode) {
79 return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
80 }
81
82 ParentMap *Parents;
83 llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
84
85 friend class RecursiveASTVisitor<ParentMapASTVisitor>;
86};
87
Manuel Klimek4da21662012-07-06 05:48:52 +000088// We use memoization to avoid running the same matcher on the same
89// AST node twice. This pair is the key for looking up match
90// result. It consists of an ID of the MatcherInterface (for
91// identifying the matcher) and a pointer to the AST node.
Manuel Klimeka78d0d62012-09-05 12:12:07 +000092//
93// We currently only memoize on nodes whose pointers identify the
94// nodes (\c Stmt and \c Decl, but not \c QualType or \c TypeLoc).
95// For \c QualType and \c TypeLoc it is possible to implement
96// generation of keys for each type.
97// FIXME: Benchmark whether memoization of non-pointer typed nodes
98// provides enough benefit for the additional amount of code.
Manuel Klimek4da21662012-07-06 05:48:52 +000099typedef std::pair<uint64_t, const void*> UntypedMatchInput;
100
101// Used to store the result of a match and possibly bound nodes.
102struct MemoizedMatchResult {
103 bool ResultOfMatch;
104 BoundNodesTree Nodes;
105};
106
107// A RecursiveASTVisitor that traverses all children or all descendants of
108// a node.
109class MatchChildASTVisitor
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000110 : public RecursiveASTVisitor<MatchChildASTVisitor> {
Manuel Klimek4da21662012-07-06 05:48:52 +0000111public:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000112 typedef RecursiveASTVisitor<MatchChildASTVisitor> VisitorBase;
Manuel Klimek4da21662012-07-06 05:48:52 +0000113
114 // Creates an AST visitor that matches 'matcher' on all children or
115 // descendants of a traversed node. max_depth is the maximum depth
116 // to traverse: use 1 for matching the children and INT_MAX for
117 // matching the descendants.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000118 MatchChildASTVisitor(const DynTypedMatcher *Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000119 ASTMatchFinder *Finder,
120 BoundNodesTreeBuilder *Builder,
121 int MaxDepth,
122 ASTMatchFinder::TraversalKind Traversal,
123 ASTMatchFinder::BindKind Bind)
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000124 : Matcher(Matcher),
Manuel Klimek4da21662012-07-06 05:48:52 +0000125 Finder(Finder),
126 Builder(Builder),
Daniel Jaspera267cf62012-10-29 10:14:44 +0000127 CurrentDepth(0),
Manuel Klimek4da21662012-07-06 05:48:52 +0000128 MaxDepth(MaxDepth),
129 Traversal(Traversal),
130 Bind(Bind),
131 Matches(false) {}
132
133 // Returns true if a match is found in the subtree rooted at the
134 // given AST node. This is done via a set of mutually recursive
135 // functions. Here's how the recursion is done (the *wildcard can
136 // actually be Decl, Stmt, or Type):
137 //
138 // - Traverse(node) calls BaseTraverse(node) when it needs
139 // to visit the descendants of node.
140 // - BaseTraverse(node) then calls (via VisitorBase::Traverse*(node))
141 // Traverse*(c) for each child c of 'node'.
142 // - Traverse*(c) in turn calls Traverse(c), completing the
143 // recursion.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000144 bool findMatch(const ast_type_traits::DynTypedNode &DynNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000145 reset();
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000146 if (const Decl *D = DynNode.get<Decl>())
147 traverse(*D);
148 else if (const Stmt *S = DynNode.get<Stmt>())
149 traverse(*S);
Daniel Jasperd1ce3c12012-10-30 15:42:00 +0000150 else if (const NestedNameSpecifier *NNS =
151 DynNode.get<NestedNameSpecifier>())
152 traverse(*NNS);
153 else if (const NestedNameSpecifierLoc *NNSLoc =
154 DynNode.get<NestedNameSpecifierLoc>())
155 traverse(*NNSLoc);
Daniel Jaspera267cf62012-10-29 10:14:44 +0000156 else if (const QualType *Q = DynNode.get<QualType>())
157 traverse(*Q);
158 else if (const TypeLoc *T = DynNode.get<TypeLoc>())
159 traverse(*T);
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000160 // FIXME: Add other base types after adding tests.
Manuel Klimek4da21662012-07-06 05:48:52 +0000161 return Matches;
162 }
163
164 // The following are overriding methods from the base visitor class.
165 // They are public only to allow CRTP to work. They are *not *part
166 // of the public API of this class.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000167 bool TraverseDecl(Decl *DeclNode) {
Daniel Jaspera267cf62012-10-29 10:14:44 +0000168 ScopedIncrement ScopedDepth(&CurrentDepth);
Manuel Klimek4da21662012-07-06 05:48:52 +0000169 return (DeclNode == NULL) || traverse(*DeclNode);
170 }
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000171 bool TraverseStmt(Stmt *StmtNode) {
Daniel Jaspera267cf62012-10-29 10:14:44 +0000172 ScopedIncrement ScopedDepth(&CurrentDepth);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000173 const Stmt *StmtToTraverse = StmtNode;
Manuel Klimek4da21662012-07-06 05:48:52 +0000174 if (Traversal ==
175 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses) {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000176 const Expr *ExprNode = dyn_cast_or_null<Expr>(StmtNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000177 if (ExprNode != NULL) {
178 StmtToTraverse = ExprNode->IgnoreParenImpCasts();
179 }
180 }
181 return (StmtToTraverse == NULL) || traverse(*StmtToTraverse);
182 }
Daniel Jaspera267cf62012-10-29 10:14:44 +0000183 // We assume that the QualType and the contained type are on the same
184 // hierarchy level. Thus, we try to match either of them.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000185 bool TraverseType(QualType TypeNode) {
Daniel Jasperb55c67d2012-11-13 17:14:11 +0000186 if (TypeNode.isNull())
187 return true;
Daniel Jaspera267cf62012-10-29 10:14:44 +0000188 ScopedIncrement ScopedDepth(&CurrentDepth);
189 // Match the Type.
190 if (!match(*TypeNode))
191 return false;
192 // The QualType is matched inside traverse.
Manuel Klimek4da21662012-07-06 05:48:52 +0000193 return traverse(TypeNode);
194 }
Daniel Jaspera267cf62012-10-29 10:14:44 +0000195 // We assume that the TypeLoc, contained QualType and contained Type all are
196 // on the same hierarchy level. Thus, we try to match all of them.
197 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Daniel Jasperb55c67d2012-11-13 17:14:11 +0000198 if (TypeLocNode.isNull())
199 return true;
Daniel Jaspera267cf62012-10-29 10:14:44 +0000200 ScopedIncrement ScopedDepth(&CurrentDepth);
201 // Match the Type.
202 if (!match(*TypeLocNode.getType()))
203 return false;
204 // Match the QualType.
205 if (!match(TypeLocNode.getType()))
206 return false;
207 // The TypeLoc is matched inside traverse.
208 return traverse(TypeLocNode);
209 }
Daniel Jasperd1ce3c12012-10-30 15:42:00 +0000210 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
211 ScopedIncrement ScopedDepth(&CurrentDepth);
212 return (NNS == NULL) || traverse(*NNS);
213 }
214 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
Daniel Jasperb55c67d2012-11-13 17:14:11 +0000215 if (!NNS)
216 return true;
Daniel Jasperd1ce3c12012-10-30 15:42:00 +0000217 ScopedIncrement ScopedDepth(&CurrentDepth);
218 if (!match(*NNS.getNestedNameSpecifier()))
219 return false;
Daniel Jasperb55c67d2012-11-13 17:14:11 +0000220 return traverse(NNS);
Daniel Jasperd1ce3c12012-10-30 15:42:00 +0000221 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000222
223 bool shouldVisitTemplateInstantiations() const { return true; }
224 bool shouldVisitImplicitCode() const { return true; }
225
226private:
227 // Used for updating the depth during traversal.
228 struct ScopedIncrement {
229 explicit ScopedIncrement(int *Depth) : Depth(Depth) { ++(*Depth); }
230 ~ScopedIncrement() { --(*Depth); }
231
232 private:
233 int *Depth;
234 };
235
236 // Resets the state of this object.
237 void reset() {
238 Matches = false;
Daniel Jaspera267cf62012-10-29 10:14:44 +0000239 CurrentDepth = 0;
Manuel Klimek4da21662012-07-06 05:48:52 +0000240 }
241
242 // Forwards the call to the corresponding Traverse*() method in the
243 // base visitor class.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000244 bool baseTraverse(const Decl &DeclNode) {
245 return VisitorBase::TraverseDecl(const_cast<Decl*>(&DeclNode));
Manuel Klimek4da21662012-07-06 05:48:52 +0000246 }
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000247 bool baseTraverse(const Stmt &StmtNode) {
248 return VisitorBase::TraverseStmt(const_cast<Stmt*>(&StmtNode));
Manuel Klimek4da21662012-07-06 05:48:52 +0000249 }
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000250 bool baseTraverse(QualType TypeNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000251 return VisitorBase::TraverseType(TypeNode);
252 }
Daniel Jaspera267cf62012-10-29 10:14:44 +0000253 bool baseTraverse(TypeLoc TypeLocNode) {
254 return VisitorBase::TraverseTypeLoc(TypeLocNode);
255 }
Daniel Jasperd1ce3c12012-10-30 15:42:00 +0000256 bool baseTraverse(const NestedNameSpecifier &NNS) {
257 return VisitorBase::TraverseNestedNameSpecifier(
258 const_cast<NestedNameSpecifier*>(&NNS));
259 }
260 bool baseTraverse(NestedNameSpecifierLoc NNS) {
261 return VisitorBase::TraverseNestedNameSpecifierLoc(NNS);
262 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000263
Daniel Jaspera267cf62012-10-29 10:14:44 +0000264 // Sets 'Matched' to true if 'Matcher' matches 'Node' and:
265 // 0 < CurrentDepth <= MaxDepth.
266 //
267 // Returns 'true' if traversal should continue after this function
268 // returns, i.e. if no match is found or 'Bind' is 'BK_All'.
Manuel Klimek4da21662012-07-06 05:48:52 +0000269 template <typename T>
Daniel Jaspera267cf62012-10-29 10:14:44 +0000270 bool match(const T &Node) {
271 if (CurrentDepth == 0 || CurrentDepth > MaxDepth) {
272 return true;
Manuel Klimek4da21662012-07-06 05:48:52 +0000273 }
274 if (Bind != ASTMatchFinder::BK_All) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000275 if (Matcher->matches(ast_type_traits::DynTypedNode::create(Node),
276 Finder, Builder)) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000277 Matches = true;
278 return false; // Abort as soon as a match is found.
279 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000280 } else {
281 BoundNodesTreeBuilder RecursiveBuilder;
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000282 if (Matcher->matches(ast_type_traits::DynTypedNode::create(Node),
283 Finder, &RecursiveBuilder)) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000284 // After the first match the matcher succeeds.
285 Matches = true;
286 Builder->addMatch(RecursiveBuilder.build());
287 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000288 }
Daniel Jaspera267cf62012-10-29 10:14:44 +0000289 return true;
290 }
291
292 // Traverses the subtree rooted at 'Node'; returns true if the
293 // traversal should continue after this function returns.
294 template <typename T>
295 bool traverse(const T &Node) {
296 TOOLING_COMPILE_ASSERT(IsBaseType<T>::value,
297 traverse_can_only_be_instantiated_with_base_type);
298 if (!match(Node))
299 return false;
300 return baseTraverse(Node);
Manuel Klimek4da21662012-07-06 05:48:52 +0000301 }
302
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000303 const DynTypedMatcher *const Matcher;
Manuel Klimek4da21662012-07-06 05:48:52 +0000304 ASTMatchFinder *const Finder;
305 BoundNodesTreeBuilder *const Builder;
306 int CurrentDepth;
307 const int MaxDepth;
308 const ASTMatchFinder::TraversalKind Traversal;
309 const ASTMatchFinder::BindKind Bind;
310 bool Matches;
311};
312
313// Controls the outermost traversal of the AST and allows to match multiple
314// matchers.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000315class MatchASTVisitor : public RecursiveASTVisitor<MatchASTVisitor>,
Manuel Klimek4da21662012-07-06 05:48:52 +0000316 public ASTMatchFinder {
317public:
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000318 MatchASTVisitor(std::vector<std::pair<const internal::DynTypedMatcher*,
319 MatchCallback*> > *MatcherCallbackPairs)
320 : MatcherCallbackPairs(MatcherCallbackPairs),
Manuel Klimek4da21662012-07-06 05:48:52 +0000321 ActiveASTContext(NULL) {
322 }
323
Manuel Klimeke5793282012-11-02 01:31:03 +0000324 void onStartOfTranslationUnit() {
325 for (std::vector<std::pair<const internal::DynTypedMatcher*,
326 MatchCallback*> >::const_iterator
327 I = MatcherCallbackPairs->begin(), E = MatcherCallbackPairs->end();
328 I != E; ++I) {
329 I->second->onStartOfTranslationUnit();
330 }
331 }
332
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000333 void set_active_ast_context(ASTContext *NewActiveASTContext) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000334 ActiveASTContext = NewActiveASTContext;
335 }
336
337 // The following Visit*() and Traverse*() functions "override"
338 // methods in RecursiveASTVisitor.
339
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000340 bool VisitTypedefDecl(TypedefDecl *DeclNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000341 // When we see 'typedef A B', we add name 'B' to the set of names
342 // A's canonical type maps to. This is necessary for implementing
Daniel Jasper76dafa72012-09-07 12:48:17 +0000343 // isDerivedFrom(x) properly, where x can be the name of the base
Manuel Klimek4da21662012-07-06 05:48:52 +0000344 // class or any of its aliases.
345 //
346 // In general, the is-alias-of (as defined by typedefs) relation
347 // is tree-shaped, as you can typedef a type more than once. For
348 // example,
349 //
350 // typedef A B;
351 // typedef A C;
352 // typedef C D;
353 // typedef C E;
354 //
355 // gives you
356 //
357 // A
358 // |- B
359 // `- C
360 // |- D
361 // `- E
362 //
363 // It is wrong to assume that the relation is a chain. A correct
Daniel Jasper76dafa72012-09-07 12:48:17 +0000364 // implementation of isDerivedFrom() needs to recognize that B and
Manuel Klimek4da21662012-07-06 05:48:52 +0000365 // E are aliases, even though neither is a typedef of the other.
366 // Therefore, we cannot simply walk through one typedef chain to
367 // find out whether the type name matches.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000368 const Type *TypeNode = DeclNode->getUnderlyingType().getTypePtr();
369 const Type *CanonicalType = // root of the typedef tree
Manuel Klimek4da21662012-07-06 05:48:52 +0000370 ActiveASTContext->getCanonicalType(TypeNode);
Daniel Jasper20b802d2012-07-17 07:39:27 +0000371 TypeAliases[CanonicalType].insert(DeclNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000372 return true;
373 }
374
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000375 bool TraverseDecl(Decl *DeclNode);
376 bool TraverseStmt(Stmt *StmtNode);
377 bool TraverseType(QualType TypeNode);
378 bool TraverseTypeLoc(TypeLoc TypeNode);
Daniel Jaspera7564432012-09-13 13:11:25 +0000379 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS);
380 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Manuel Klimek4da21662012-07-06 05:48:52 +0000381
382 // Matches children or descendants of 'Node' with 'BaseMatcher'.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000383 bool memoizedMatchesRecursively(const ast_type_traits::DynTypedNode &Node,
384 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000385 BoundNodesTreeBuilder *Builder, int MaxDepth,
386 TraversalKind Traversal, BindKind Bind) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000387 const UntypedMatchInput input(Matcher.getID(), Node.getMemoizationData());
Daniel Jaspera267cf62012-10-29 10:14:44 +0000388
389 // For AST-nodes that don't have an identity, we can't memoize.
390 if (!input.second)
391 return matchesRecursively(Node, Matcher, Builder, MaxDepth, Traversal,
392 Bind);
393
Manuel Klimek4da21662012-07-06 05:48:52 +0000394 std::pair<MemoizationMap::iterator, bool> InsertResult
395 = ResultCache.insert(std::make_pair(input, MemoizedMatchResult()));
396 if (InsertResult.second) {
397 BoundNodesTreeBuilder DescendantBoundNodesBuilder;
398 InsertResult.first->second.ResultOfMatch =
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000399 matchesRecursively(Node, Matcher, &DescendantBoundNodesBuilder,
Manuel Klimek4da21662012-07-06 05:48:52 +0000400 MaxDepth, Traversal, Bind);
401 InsertResult.first->second.Nodes =
402 DescendantBoundNodesBuilder.build();
403 }
404 InsertResult.first->second.Nodes.copyTo(Builder);
405 return InsertResult.first->second.ResultOfMatch;
406 }
407
408 // Matches children or descendants of 'Node' with 'BaseMatcher'.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000409 bool matchesRecursively(const ast_type_traits::DynTypedNode &Node,
410 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000411 BoundNodesTreeBuilder *Builder, int MaxDepth,
412 TraversalKind Traversal, BindKind Bind) {
413 MatchChildASTVisitor Visitor(
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000414 &Matcher, this, Builder, MaxDepth, Traversal, Bind);
Manuel Klimek4da21662012-07-06 05:48:52 +0000415 return Visitor.findMatch(Node);
416 }
417
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000418 virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
Daniel Jasper20b802d2012-07-17 07:39:27 +0000419 const Matcher<NamedDecl> &Base,
420 BoundNodesTreeBuilder *Builder);
Manuel Klimek4da21662012-07-06 05:48:52 +0000421
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000422 // Implements ASTMatchFinder::matchesChildOf.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000423 virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node,
424 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000425 BoundNodesTreeBuilder *Builder,
426 TraversalKind Traversal,
427 BindKind Bind) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000428 return matchesRecursively(Node, Matcher, Builder, 1, Traversal,
Manuel Klimek4da21662012-07-06 05:48:52 +0000429 Bind);
430 }
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000431 // Implements ASTMatchFinder::matchesDescendantOf.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000432 virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node,
433 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000434 BoundNodesTreeBuilder *Builder,
435 BindKind Bind) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000436 return memoizedMatchesRecursively(Node, Matcher, Builder, INT_MAX,
Manuel Klimek4da21662012-07-06 05:48:52 +0000437 TK_AsIs, Bind);
438 }
Manuel Klimek579b1202012-09-07 09:26:10 +0000439 // Implements ASTMatchFinder::matchesAncestorOf.
440 virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node,
441 const DynTypedMatcher &Matcher,
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000442 BoundNodesTreeBuilder *Builder,
443 AncestorMatchMode MatchMode) {
Manuel Klimek579b1202012-09-07 09:26:10 +0000444 if (!Parents) {
445 // We always need to run over the whole translation unit, as
446 // \c hasAncestor can escape any subtree.
447 Parents.reset(ParentMapASTVisitor::buildMap(
448 *ActiveASTContext->getTranslationUnitDecl()));
449 }
450 ast_type_traits::DynTypedNode Ancestor = Node;
451 while (Ancestor.get<TranslationUnitDecl>() !=
452 ActiveASTContext->getTranslationUnitDecl()) {
453 assert(Ancestor.getMemoizationData() &&
454 "Invariant broken: only nodes that support memoization may be "
455 "used in the parent map.");
456 ParentMapASTVisitor::ParentMap::const_iterator I =
457 Parents->find(Ancestor.getMemoizationData());
458 if (I == Parents->end()) {
459 assert(false &&
460 "Found node that is not in the parent map.");
461 return false;
462 }
463 Ancestor = I->second;
464 if (Matcher.matches(Ancestor, this, Builder))
465 return true;
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000466 if (MatchMode == ASTMatchFinder::AMM_ParentOnly)
467 return false;
Manuel Klimek579b1202012-09-07 09:26:10 +0000468 }
469 return false;
470 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000471
472 bool shouldVisitTemplateInstantiations() const { return true; }
473 bool shouldVisitImplicitCode() const { return true; }
474
475private:
476 // Implements a BoundNodesTree::Visitor that calls a MatchCallback with
477 // the aggregated bound nodes for each match.
478 class MatchVisitor : public BoundNodesTree::Visitor {
479 public:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000480 MatchVisitor(ASTContext* Context,
Manuel Klimek4da21662012-07-06 05:48:52 +0000481 MatchFinder::MatchCallback* Callback)
482 : Context(Context),
483 Callback(Callback) {}
484
485 virtual void visitMatch(const BoundNodes& BoundNodesView) {
486 Callback->run(MatchFinder::MatchResult(BoundNodesView, Context));
487 }
488
489 private:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000490 ASTContext* Context;
Manuel Klimek4da21662012-07-06 05:48:52 +0000491 MatchFinder::MatchCallback* Callback;
492 };
493
Daniel Jasper20b802d2012-07-17 07:39:27 +0000494 // Returns true if 'TypeNode' has an alias that matches the given matcher.
495 bool typeHasMatchingAlias(const Type *TypeNode,
496 const Matcher<NamedDecl> Matcher,
497 BoundNodesTreeBuilder *Builder) {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000498 const Type *const CanonicalType =
Manuel Klimek4da21662012-07-06 05:48:52 +0000499 ActiveASTContext->getCanonicalType(TypeNode);
Daniel Jasper20b802d2012-07-17 07:39:27 +0000500 const std::set<const TypedefDecl*> &Aliases = TypeAliases[CanonicalType];
501 for (std::set<const TypedefDecl*>::const_iterator
502 It = Aliases.begin(), End = Aliases.end();
503 It != End; ++It) {
504 if (Matcher.matches(**It, this, Builder))
505 return true;
506 }
507 return false;
Manuel Klimek4da21662012-07-06 05:48:52 +0000508 }
509
510 // Matches all registered matchers on the given node and calls the
511 // result callback for every node that matches.
512 template <typename T>
513 void match(const T &node) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000514 for (std::vector<std::pair<const internal::DynTypedMatcher*,
515 MatchCallback*> >::const_iterator
516 I = MatcherCallbackPairs->begin(), E = MatcherCallbackPairs->end();
517 I != E; ++I) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000518 BoundNodesTreeBuilder Builder;
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000519 if (I->first->matches(ast_type_traits::DynTypedNode::create(node),
520 this, &Builder)) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000521 BoundNodesTree BoundNodes = Builder.build();
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000522 MatchVisitor Visitor(ActiveASTContext, I->second);
Manuel Klimek4da21662012-07-06 05:48:52 +0000523 BoundNodes.visitMatches(&Visitor);
524 }
525 }
526 }
527
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000528 std::vector<std::pair<const internal::DynTypedMatcher*,
529 MatchCallback*> > *const MatcherCallbackPairs;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000530 ASTContext *ActiveASTContext;
Manuel Klimek4da21662012-07-06 05:48:52 +0000531
Daniel Jasper20b802d2012-07-17 07:39:27 +0000532 // Maps a canonical type to its TypedefDecls.
533 llvm::DenseMap<const Type*, std::set<const TypedefDecl*> > TypeAliases;
Manuel Klimek4da21662012-07-06 05:48:52 +0000534
535 // Maps (matcher, node) -> the match result for memoization.
536 typedef llvm::DenseMap<UntypedMatchInput, MemoizedMatchResult> MemoizationMap;
537 MemoizationMap ResultCache;
Manuel Klimek579b1202012-09-07 09:26:10 +0000538
539 llvm::OwningPtr<ParentMapASTVisitor::ParentMap> Parents;
Manuel Klimek4da21662012-07-06 05:48:52 +0000540};
541
542// Returns true if the given class is directly or indirectly derived
Daniel Jasper76dafa72012-09-07 12:48:17 +0000543// from a base type with the given name. A class is not considered to be
544// derived from itself.
Daniel Jasper20b802d2012-07-17 07:39:27 +0000545bool MatchASTVisitor::classIsDerivedFrom(const CXXRecordDecl *Declaration,
546 const Matcher<NamedDecl> &Base,
547 BoundNodesTreeBuilder *Builder) {
Daniel Jasper20b802d2012-07-17 07:39:27 +0000548 if (!Declaration->hasDefinition())
Manuel Klimek4da21662012-07-06 05:48:52 +0000549 return false;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000550 typedef CXXRecordDecl::base_class_const_iterator BaseIterator;
Manuel Klimek4da21662012-07-06 05:48:52 +0000551 for (BaseIterator It = Declaration->bases_begin(),
552 End = Declaration->bases_end(); It != End; ++It) {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000553 const Type *TypeNode = It->getType().getTypePtr();
Manuel Klimek4da21662012-07-06 05:48:52 +0000554
Daniel Jasper20b802d2012-07-17 07:39:27 +0000555 if (typeHasMatchingAlias(TypeNode, Base, Builder))
Manuel Klimek4da21662012-07-06 05:48:52 +0000556 return true;
557
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000558 // Type::getAs<...>() drills through typedefs.
559 if (TypeNode->getAs<DependentNameType>() != NULL ||
Daniel Jasper08f0c532012-09-18 14:17:42 +0000560 TypeNode->getAs<DependentTemplateSpecializationType>() != NULL ||
Daniel Jasper20b802d2012-07-17 07:39:27 +0000561 TypeNode->getAs<TemplateTypeParmType>() != NULL)
Manuel Klimek4da21662012-07-06 05:48:52 +0000562 // Dependent names and template TypeNode parameters will be matched when
563 // the template is instantiated.
564 continue;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000565 CXXRecordDecl *ClassDecl = NULL;
566 TemplateSpecializationType const *TemplateType =
567 TypeNode->getAs<TemplateSpecializationType>();
Manuel Klimek4da21662012-07-06 05:48:52 +0000568 if (TemplateType != NULL) {
Daniel Jasper20b802d2012-07-17 07:39:27 +0000569 if (TemplateType->getTemplateName().isDependent())
Manuel Klimek4da21662012-07-06 05:48:52 +0000570 // Dependent template specializations will be matched when the
571 // template is instantiated.
572 continue;
Daniel Jasper20b802d2012-07-17 07:39:27 +0000573
Manuel Klimek4da21662012-07-06 05:48:52 +0000574 // For template specialization types which are specializing a template
575 // declaration which is an explicit or partial specialization of another
576 // template declaration, getAsCXXRecordDecl() returns the corresponding
577 // ClassTemplateSpecializationDecl.
578 //
579 // For template specialization types which are specializing a template
580 // declaration which is neither an explicit nor partial specialization of
581 // another template declaration, getAsCXXRecordDecl() returns NULL and
582 // we get the CXXRecordDecl of the templated declaration.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000583 CXXRecordDecl *SpecializationDecl =
Manuel Klimek4da21662012-07-06 05:48:52 +0000584 TemplateType->getAsCXXRecordDecl();
585 if (SpecializationDecl != NULL) {
586 ClassDecl = SpecializationDecl;
587 } else {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000588 ClassDecl = llvm::dyn_cast<CXXRecordDecl>(
Manuel Klimek4da21662012-07-06 05:48:52 +0000589 TemplateType->getTemplateName()
590 .getAsTemplateDecl()->getTemplatedDecl());
591 }
592 } else {
593 ClassDecl = TypeNode->getAsCXXRecordDecl();
594 }
595 assert(ClassDecl != NULL);
596 assert(ClassDecl != Declaration);
Daniel Jasper76dafa72012-09-07 12:48:17 +0000597 if (Base.matches(*ClassDecl, this, Builder))
598 return true;
Daniel Jasper20b802d2012-07-17 07:39:27 +0000599 if (classIsDerivedFrom(ClassDecl, Base, Builder))
Manuel Klimek4da21662012-07-06 05:48:52 +0000600 return true;
Manuel Klimek4da21662012-07-06 05:48:52 +0000601 }
602 return false;
603}
604
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000605bool MatchASTVisitor::TraverseDecl(Decl *DeclNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000606 if (DeclNode == NULL) {
607 return true;
608 }
609 match(*DeclNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000610 return RecursiveASTVisitor<MatchASTVisitor>::TraverseDecl(DeclNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000611}
612
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000613bool MatchASTVisitor::TraverseStmt(Stmt *StmtNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000614 if (StmtNode == NULL) {
615 return true;
616 }
617 match(*StmtNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000618 return RecursiveASTVisitor<MatchASTVisitor>::TraverseStmt(StmtNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000619}
620
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000621bool MatchASTVisitor::TraverseType(QualType TypeNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000622 match(TypeNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000623 return RecursiveASTVisitor<MatchASTVisitor>::TraverseType(TypeNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000624}
625
Daniel Jasperce620072012-10-17 08:52:59 +0000626bool MatchASTVisitor::TraverseTypeLoc(TypeLoc TypeLocNode) {
627 // The RecursiveASTVisitor only visits types if they're not within TypeLocs.
628 // We still want to find those types via matchers, so we match them here. Note
629 // that the TypeLocs are structurally a shadow-hierarchy to the expressed
630 // type, so we visit all involved parts of a compound type when matching on
631 // each TypeLoc.
632 match(TypeLocNode);
633 match(TypeLocNode.getType());
634 return RecursiveASTVisitor<MatchASTVisitor>::TraverseTypeLoc(TypeLocNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000635}
636
Daniel Jaspera7564432012-09-13 13:11:25 +0000637bool MatchASTVisitor::TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
638 match(*NNS);
639 return RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifier(NNS);
640}
641
642bool MatchASTVisitor::TraverseNestedNameSpecifierLoc(
643 NestedNameSpecifierLoc NNS) {
644 match(NNS);
645 // We only match the nested name specifier here (as opposed to traversing it)
646 // because the traversal is already done in the parallel "Loc"-hierarchy.
647 match(*NNS.getNestedNameSpecifier());
648 return
649 RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifierLoc(NNS);
650}
651
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000652class MatchASTConsumer : public ASTConsumer {
Manuel Klimek4da21662012-07-06 05:48:52 +0000653public:
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000654 MatchASTConsumer(
655 std::vector<std::pair<const internal::DynTypedMatcher*,
656 MatchCallback*> > *MatcherCallbackPairs,
657 MatchFinder::ParsingDoneTestCallback *ParsingDone)
658 : Visitor(MatcherCallbackPairs),
659 ParsingDone(ParsingDone) {}
Manuel Klimek4da21662012-07-06 05:48:52 +0000660
661private:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000662 virtual void HandleTranslationUnit(ASTContext &Context) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000663 if (ParsingDone != NULL) {
664 ParsingDone->run();
665 }
666 Visitor.set_active_ast_context(&Context);
Manuel Klimeke5793282012-11-02 01:31:03 +0000667 Visitor.onStartOfTranslationUnit();
Manuel Klimek4da21662012-07-06 05:48:52 +0000668 Visitor.TraverseDecl(Context.getTranslationUnitDecl());
669 Visitor.set_active_ast_context(NULL);
670 }
671
672 MatchASTVisitor Visitor;
673 MatchFinder::ParsingDoneTestCallback *ParsingDone;
674};
675
676} // end namespace
677} // end namespace internal
678
679MatchFinder::MatchResult::MatchResult(const BoundNodes &Nodes,
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000680 ASTContext *Context)
Manuel Klimek4da21662012-07-06 05:48:52 +0000681 : Nodes(Nodes), Context(Context),
682 SourceManager(&Context->getSourceManager()) {}
683
684MatchFinder::MatchCallback::~MatchCallback() {}
685MatchFinder::ParsingDoneTestCallback::~ParsingDoneTestCallback() {}
686
687MatchFinder::MatchFinder() : ParsingDone(NULL) {}
688
689MatchFinder::~MatchFinder() {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000690 for (std::vector<std::pair<const internal::DynTypedMatcher*,
691 MatchCallback*> >::const_iterator
692 It = MatcherCallbackPairs.begin(), End = MatcherCallbackPairs.end();
Manuel Klimek4da21662012-07-06 05:48:52 +0000693 It != End; ++It) {
694 delete It->first;
695 }
696}
697
698void MatchFinder::addMatcher(const DeclarationMatcher &NodeMatch,
699 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000700 MatcherCallbackPairs.push_back(std::make_pair(
701 new internal::Matcher<Decl>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000702}
703
704void MatchFinder::addMatcher(const TypeMatcher &NodeMatch,
705 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000706 MatcherCallbackPairs.push_back(std::make_pair(
707 new internal::Matcher<QualType>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000708}
709
710void MatchFinder::addMatcher(const StatementMatcher &NodeMatch,
711 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000712 MatcherCallbackPairs.push_back(std::make_pair(
713 new internal::Matcher<Stmt>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000714}
715
Daniel Jaspera7564432012-09-13 13:11:25 +0000716void MatchFinder::addMatcher(const NestedNameSpecifierMatcher &NodeMatch,
717 MatchCallback *Action) {
718 MatcherCallbackPairs.push_back(std::make_pair(
719 new NestedNameSpecifierMatcher(NodeMatch), Action));
720}
721
722void MatchFinder::addMatcher(const NestedNameSpecifierLocMatcher &NodeMatch,
723 MatchCallback *Action) {
724 MatcherCallbackPairs.push_back(std::make_pair(
725 new NestedNameSpecifierLocMatcher(NodeMatch), Action));
726}
727
Daniel Jasperce620072012-10-17 08:52:59 +0000728void MatchFinder::addMatcher(const TypeLocMatcher &NodeMatch,
729 MatchCallback *Action) {
730 MatcherCallbackPairs.push_back(std::make_pair(
731 new TypeLocMatcher(NodeMatch), Action));
732}
733
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000734ASTConsumer *MatchFinder::newASTConsumer() {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000735 return new internal::MatchASTConsumer(&MatcherCallbackPairs, ParsingDone);
Manuel Klimek4da21662012-07-06 05:48:52 +0000736}
737
Manuel Klimek3e2aa992012-10-24 14:47:44 +0000738void MatchFinder::findAll(const Decl &Node, ASTContext &Context) {
739 internal::MatchASTVisitor Visitor(&MatcherCallbackPairs);
740 Visitor.set_active_ast_context(&Context);
741 Visitor.TraverseDecl(const_cast<Decl*>(&Node));
742}
743
744void MatchFinder::findAll(const Stmt &Node, ASTContext &Context) {
745 internal::MatchASTVisitor Visitor(&MatcherCallbackPairs);
746 Visitor.set_active_ast_context(&Context);
747 Visitor.TraverseStmt(const_cast<Stmt*>(&Node));
748}
749
Manuel Klimek4da21662012-07-06 05:48:52 +0000750void MatchFinder::registerTestCallbackAfterParsing(
751 MatchFinder::ParsingDoneTestCallback *NewParsingDone) {
752 ParsingDone = NewParsingDone;
753}
754
755} // end namespace ast_matchers
756} // end namespace clang