blob: 6ebd736e3ce466da12f378d1673e0243467e414d [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"
Manuel Klimek374516c2013-03-14 16:33:21 +000023#include <deque>
Manuel Klimek4da21662012-07-06 05:48:52 +000024#include <set>
25
26namespace clang {
27namespace ast_matchers {
28namespace internal {
29namespace {
30
Manuel Klimeka78d0d62012-09-05 12:12:07 +000031typedef MatchFinder::MatchCallback MatchCallback;
32
Manuel Klimek4da21662012-07-06 05:48:52 +000033// We use memoization to avoid running the same matcher on the same
34// AST node twice. This pair is the key for looking up match
35// result. It consists of an ID of the MatcherInterface (for
36// identifying the matcher) and a pointer to the AST node.
Manuel Klimeka78d0d62012-09-05 12:12:07 +000037//
38// We currently only memoize on nodes whose pointers identify the
39// nodes (\c Stmt and \c Decl, but not \c QualType or \c TypeLoc).
40// For \c QualType and \c TypeLoc it is possible to implement
41// generation of keys for each type.
42// FIXME: Benchmark whether memoization of non-pointer typed nodes
43// provides enough benefit for the additional amount of code.
Manuel Klimek4da21662012-07-06 05:48:52 +000044typedef std::pair<uint64_t, const void*> UntypedMatchInput;
45
46// Used to store the result of a match and possibly bound nodes.
47struct MemoizedMatchResult {
48 bool ResultOfMatch;
49 BoundNodesTree Nodes;
50};
51
52// A RecursiveASTVisitor that traverses all children or all descendants of
53// a node.
54class MatchChildASTVisitor
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +000055 : public RecursiveASTVisitor<MatchChildASTVisitor> {
Manuel Klimek4da21662012-07-06 05:48:52 +000056public:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +000057 typedef RecursiveASTVisitor<MatchChildASTVisitor> VisitorBase;
Manuel Klimek4da21662012-07-06 05:48:52 +000058
59 // Creates an AST visitor that matches 'matcher' on all children or
60 // descendants of a traversed node. max_depth is the maximum depth
61 // to traverse: use 1 for matching the children and INT_MAX for
62 // matching the descendants.
Manuel Klimeka78d0d62012-09-05 12:12:07 +000063 MatchChildASTVisitor(const DynTypedMatcher *Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +000064 ASTMatchFinder *Finder,
65 BoundNodesTreeBuilder *Builder,
66 int MaxDepth,
67 ASTMatchFinder::TraversalKind Traversal,
68 ASTMatchFinder::BindKind Bind)
Manuel Klimeka78d0d62012-09-05 12:12:07 +000069 : Matcher(Matcher),
Manuel Klimek4da21662012-07-06 05:48:52 +000070 Finder(Finder),
71 Builder(Builder),
Daniel Jaspera267cf62012-10-29 10:14:44 +000072 CurrentDepth(0),
Manuel Klimek4da21662012-07-06 05:48:52 +000073 MaxDepth(MaxDepth),
74 Traversal(Traversal),
75 Bind(Bind),
76 Matches(false) {}
77
78 // Returns true if a match is found in the subtree rooted at the
79 // given AST node. This is done via a set of mutually recursive
80 // functions. Here's how the recursion is done (the *wildcard can
81 // actually be Decl, Stmt, or Type):
82 //
83 // - Traverse(node) calls BaseTraverse(node) when it needs
84 // to visit the descendants of node.
85 // - BaseTraverse(node) then calls (via VisitorBase::Traverse*(node))
86 // Traverse*(c) for each child c of 'node'.
87 // - Traverse*(c) in turn calls Traverse(c), completing the
88 // recursion.
Manuel Klimeka78d0d62012-09-05 12:12:07 +000089 bool findMatch(const ast_type_traits::DynTypedNode &DynNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +000090 reset();
Manuel Klimeka78d0d62012-09-05 12:12:07 +000091 if (const Decl *D = DynNode.get<Decl>())
92 traverse(*D);
93 else if (const Stmt *S = DynNode.get<Stmt>())
94 traverse(*S);
Daniel Jasperd1ce3c12012-10-30 15:42:00 +000095 else if (const NestedNameSpecifier *NNS =
96 DynNode.get<NestedNameSpecifier>())
97 traverse(*NNS);
98 else if (const NestedNameSpecifierLoc *NNSLoc =
99 DynNode.get<NestedNameSpecifierLoc>())
100 traverse(*NNSLoc);
Daniel Jaspera267cf62012-10-29 10:14:44 +0000101 else if (const QualType *Q = DynNode.get<QualType>())
102 traverse(*Q);
103 else if (const TypeLoc *T = DynNode.get<TypeLoc>())
104 traverse(*T);
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000105 // FIXME: Add other base types after adding tests.
Manuel Klimek4da21662012-07-06 05:48:52 +0000106 return Matches;
107 }
108
109 // The following are overriding methods from the base visitor class.
110 // They are public only to allow CRTP to work. They are *not *part
111 // of the public API of this class.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000112 bool TraverseDecl(Decl *DeclNode) {
Daniel Jaspera267cf62012-10-29 10:14:44 +0000113 ScopedIncrement ScopedDepth(&CurrentDepth);
Manuel Klimek4da21662012-07-06 05:48:52 +0000114 return (DeclNode == NULL) || traverse(*DeclNode);
115 }
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000116 bool TraverseStmt(Stmt *StmtNode) {
Daniel Jaspera267cf62012-10-29 10:14:44 +0000117 ScopedIncrement ScopedDepth(&CurrentDepth);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000118 const Stmt *StmtToTraverse = StmtNode;
Manuel Klimek4da21662012-07-06 05:48:52 +0000119 if (Traversal ==
120 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses) {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000121 const Expr *ExprNode = dyn_cast_or_null<Expr>(StmtNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000122 if (ExprNode != NULL) {
123 StmtToTraverse = ExprNode->IgnoreParenImpCasts();
124 }
125 }
126 return (StmtToTraverse == NULL) || traverse(*StmtToTraverse);
127 }
Daniel Jaspera267cf62012-10-29 10:14:44 +0000128 // We assume that the QualType and the contained type are on the same
129 // hierarchy level. Thus, we try to match either of them.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000130 bool TraverseType(QualType TypeNode) {
Daniel Jasperb55c67d2012-11-13 17:14:11 +0000131 if (TypeNode.isNull())
132 return true;
Daniel Jaspera267cf62012-10-29 10:14:44 +0000133 ScopedIncrement ScopedDepth(&CurrentDepth);
134 // Match the Type.
135 if (!match(*TypeNode))
136 return false;
137 // The QualType is matched inside traverse.
Manuel Klimek4da21662012-07-06 05:48:52 +0000138 return traverse(TypeNode);
139 }
Daniel Jaspera267cf62012-10-29 10:14:44 +0000140 // We assume that the TypeLoc, contained QualType and contained Type all are
141 // on the same hierarchy level. Thus, we try to match all of them.
142 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Daniel Jasperb55c67d2012-11-13 17:14:11 +0000143 if (TypeLocNode.isNull())
144 return true;
Daniel Jaspera267cf62012-10-29 10:14:44 +0000145 ScopedIncrement ScopedDepth(&CurrentDepth);
146 // Match the Type.
147 if (!match(*TypeLocNode.getType()))
148 return false;
149 // Match the QualType.
150 if (!match(TypeLocNode.getType()))
151 return false;
152 // The TypeLoc is matched inside traverse.
153 return traverse(TypeLocNode);
154 }
Daniel Jasperd1ce3c12012-10-30 15:42:00 +0000155 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
156 ScopedIncrement ScopedDepth(&CurrentDepth);
157 return (NNS == NULL) || traverse(*NNS);
158 }
159 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
Daniel Jasperb55c67d2012-11-13 17:14:11 +0000160 if (!NNS)
161 return true;
Daniel Jasperd1ce3c12012-10-30 15:42:00 +0000162 ScopedIncrement ScopedDepth(&CurrentDepth);
163 if (!match(*NNS.getNestedNameSpecifier()))
164 return false;
Daniel Jasperb55c67d2012-11-13 17:14:11 +0000165 return traverse(NNS);
Daniel Jasperd1ce3c12012-10-30 15:42:00 +0000166 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000167
168 bool shouldVisitTemplateInstantiations() const { return true; }
169 bool shouldVisitImplicitCode() const { return true; }
Daniel Jasper278057f2012-11-15 03:29:05 +0000170 // Disables data recursion. We intercept Traverse* methods in the RAV, which
171 // are not triggered during data recursion.
172 bool shouldUseDataRecursionFor(clang::Stmt *S) const { return false; }
Manuel Klimek4da21662012-07-06 05:48:52 +0000173
174private:
175 // Used for updating the depth during traversal.
176 struct ScopedIncrement {
177 explicit ScopedIncrement(int *Depth) : Depth(Depth) { ++(*Depth); }
178 ~ScopedIncrement() { --(*Depth); }
179
180 private:
181 int *Depth;
182 };
183
184 // Resets the state of this object.
185 void reset() {
186 Matches = false;
Daniel Jaspera267cf62012-10-29 10:14:44 +0000187 CurrentDepth = 0;
Manuel Klimek4da21662012-07-06 05:48:52 +0000188 }
189
190 // Forwards the call to the corresponding Traverse*() method in the
191 // base visitor class.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000192 bool baseTraverse(const Decl &DeclNode) {
193 return VisitorBase::TraverseDecl(const_cast<Decl*>(&DeclNode));
Manuel Klimek4da21662012-07-06 05:48:52 +0000194 }
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000195 bool baseTraverse(const Stmt &StmtNode) {
196 return VisitorBase::TraverseStmt(const_cast<Stmt*>(&StmtNode));
Manuel Klimek4da21662012-07-06 05:48:52 +0000197 }
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000198 bool baseTraverse(QualType TypeNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000199 return VisitorBase::TraverseType(TypeNode);
200 }
Daniel Jaspera267cf62012-10-29 10:14:44 +0000201 bool baseTraverse(TypeLoc TypeLocNode) {
202 return VisitorBase::TraverseTypeLoc(TypeLocNode);
203 }
Daniel Jasperd1ce3c12012-10-30 15:42:00 +0000204 bool baseTraverse(const NestedNameSpecifier &NNS) {
205 return VisitorBase::TraverseNestedNameSpecifier(
206 const_cast<NestedNameSpecifier*>(&NNS));
207 }
208 bool baseTraverse(NestedNameSpecifierLoc NNS) {
209 return VisitorBase::TraverseNestedNameSpecifierLoc(NNS);
210 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000211
Daniel Jaspera267cf62012-10-29 10:14:44 +0000212 // Sets 'Matched' to true if 'Matcher' matches 'Node' and:
213 // 0 < CurrentDepth <= MaxDepth.
214 //
215 // Returns 'true' if traversal should continue after this function
216 // returns, i.e. if no match is found or 'Bind' is 'BK_All'.
Manuel Klimek4da21662012-07-06 05:48:52 +0000217 template <typename T>
Daniel Jaspera267cf62012-10-29 10:14:44 +0000218 bool match(const T &Node) {
219 if (CurrentDepth == 0 || CurrentDepth > MaxDepth) {
220 return true;
Manuel Klimek4da21662012-07-06 05:48:52 +0000221 }
222 if (Bind != ASTMatchFinder::BK_All) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000223 if (Matcher->matches(ast_type_traits::DynTypedNode::create(Node),
224 Finder, Builder)) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000225 Matches = true;
226 return false; // Abort as soon as a match is found.
227 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000228 } else {
229 BoundNodesTreeBuilder RecursiveBuilder;
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000230 if (Matcher->matches(ast_type_traits::DynTypedNode::create(Node),
231 Finder, &RecursiveBuilder)) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000232 // After the first match the matcher succeeds.
233 Matches = true;
234 Builder->addMatch(RecursiveBuilder.build());
235 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000236 }
Daniel Jaspera267cf62012-10-29 10:14:44 +0000237 return true;
238 }
239
240 // Traverses the subtree rooted at 'Node'; returns true if the
241 // traversal should continue after this function returns.
242 template <typename T>
243 bool traverse(const T &Node) {
244 TOOLING_COMPILE_ASSERT(IsBaseType<T>::value,
245 traverse_can_only_be_instantiated_with_base_type);
246 if (!match(Node))
247 return false;
248 return baseTraverse(Node);
Manuel Klimek4da21662012-07-06 05:48:52 +0000249 }
250
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000251 const DynTypedMatcher *const Matcher;
Manuel Klimek4da21662012-07-06 05:48:52 +0000252 ASTMatchFinder *const Finder;
253 BoundNodesTreeBuilder *const Builder;
254 int CurrentDepth;
255 const int MaxDepth;
256 const ASTMatchFinder::TraversalKind Traversal;
257 const ASTMatchFinder::BindKind Bind;
258 bool Matches;
259};
260
261// Controls the outermost traversal of the AST and allows to match multiple
262// matchers.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000263class MatchASTVisitor : public RecursiveASTVisitor<MatchASTVisitor>,
Manuel Klimek4da21662012-07-06 05:48:52 +0000264 public ASTMatchFinder {
265public:
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000266 MatchASTVisitor(std::vector<std::pair<const internal::DynTypedMatcher*,
267 MatchCallback*> > *MatcherCallbackPairs)
268 : MatcherCallbackPairs(MatcherCallbackPairs),
Manuel Klimek4da21662012-07-06 05:48:52 +0000269 ActiveASTContext(NULL) {
270 }
271
Manuel Klimeke5793282012-11-02 01:31:03 +0000272 void onStartOfTranslationUnit() {
273 for (std::vector<std::pair<const internal::DynTypedMatcher*,
274 MatchCallback*> >::const_iterator
275 I = MatcherCallbackPairs->begin(), E = MatcherCallbackPairs->end();
276 I != E; ++I) {
277 I->second->onStartOfTranslationUnit();
278 }
279 }
280
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000281 void set_active_ast_context(ASTContext *NewActiveASTContext) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000282 ActiveASTContext = NewActiveASTContext;
283 }
284
285 // The following Visit*() and Traverse*() functions "override"
286 // methods in RecursiveASTVisitor.
287
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000288 bool VisitTypedefDecl(TypedefDecl *DeclNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000289 // When we see 'typedef A B', we add name 'B' to the set of names
290 // A's canonical type maps to. This is necessary for implementing
Daniel Jasper76dafa72012-09-07 12:48:17 +0000291 // isDerivedFrom(x) properly, where x can be the name of the base
Manuel Klimek4da21662012-07-06 05:48:52 +0000292 // class or any of its aliases.
293 //
294 // In general, the is-alias-of (as defined by typedefs) relation
295 // is tree-shaped, as you can typedef a type more than once. For
296 // example,
297 //
298 // typedef A B;
299 // typedef A C;
300 // typedef C D;
301 // typedef C E;
302 //
303 // gives you
304 //
305 // A
306 // |- B
307 // `- C
308 // |- D
309 // `- E
310 //
311 // It is wrong to assume that the relation is a chain. A correct
Daniel Jasper76dafa72012-09-07 12:48:17 +0000312 // implementation of isDerivedFrom() needs to recognize that B and
Manuel Klimek4da21662012-07-06 05:48:52 +0000313 // E are aliases, even though neither is a typedef of the other.
314 // Therefore, we cannot simply walk through one typedef chain to
315 // find out whether the type name matches.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000316 const Type *TypeNode = DeclNode->getUnderlyingType().getTypePtr();
317 const Type *CanonicalType = // root of the typedef tree
Manuel Klimek4da21662012-07-06 05:48:52 +0000318 ActiveASTContext->getCanonicalType(TypeNode);
Daniel Jasper20b802d2012-07-17 07:39:27 +0000319 TypeAliases[CanonicalType].insert(DeclNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000320 return true;
321 }
322
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000323 bool TraverseDecl(Decl *DeclNode);
324 bool TraverseStmt(Stmt *StmtNode);
325 bool TraverseType(QualType TypeNode);
326 bool TraverseTypeLoc(TypeLoc TypeNode);
Daniel Jaspera7564432012-09-13 13:11:25 +0000327 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS);
328 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Manuel Klimek4da21662012-07-06 05:48:52 +0000329
330 // Matches children or descendants of 'Node' with 'BaseMatcher'.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000331 bool memoizedMatchesRecursively(const ast_type_traits::DynTypedNode &Node,
332 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000333 BoundNodesTreeBuilder *Builder, int MaxDepth,
334 TraversalKind Traversal, BindKind Bind) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000335 const UntypedMatchInput input(Matcher.getID(), Node.getMemoizationData());
Daniel Jaspera267cf62012-10-29 10:14:44 +0000336
337 // For AST-nodes that don't have an identity, we can't memoize.
338 if (!input.second)
339 return matchesRecursively(Node, Matcher, Builder, MaxDepth, Traversal,
340 Bind);
341
Manuel Klimek4da21662012-07-06 05:48:52 +0000342 std::pair<MemoizationMap::iterator, bool> InsertResult
343 = ResultCache.insert(std::make_pair(input, MemoizedMatchResult()));
344 if (InsertResult.second) {
345 BoundNodesTreeBuilder DescendantBoundNodesBuilder;
346 InsertResult.first->second.ResultOfMatch =
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000347 matchesRecursively(Node, Matcher, &DescendantBoundNodesBuilder,
Manuel Klimek4da21662012-07-06 05:48:52 +0000348 MaxDepth, Traversal, Bind);
349 InsertResult.first->second.Nodes =
350 DescendantBoundNodesBuilder.build();
351 }
352 InsertResult.first->second.Nodes.copyTo(Builder);
353 return InsertResult.first->second.ResultOfMatch;
354 }
355
356 // Matches children or descendants of 'Node' with 'BaseMatcher'.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000357 bool matchesRecursively(const ast_type_traits::DynTypedNode &Node,
358 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000359 BoundNodesTreeBuilder *Builder, int MaxDepth,
360 TraversalKind Traversal, BindKind Bind) {
361 MatchChildASTVisitor Visitor(
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000362 &Matcher, this, Builder, MaxDepth, Traversal, Bind);
Manuel Klimek4da21662012-07-06 05:48:52 +0000363 return Visitor.findMatch(Node);
364 }
365
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000366 virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
Daniel Jasper20b802d2012-07-17 07:39:27 +0000367 const Matcher<NamedDecl> &Base,
368 BoundNodesTreeBuilder *Builder);
Manuel Klimek4da21662012-07-06 05:48:52 +0000369
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000370 // Implements ASTMatchFinder::matchesChildOf.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000371 virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node,
372 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000373 BoundNodesTreeBuilder *Builder,
374 TraversalKind Traversal,
375 BindKind Bind) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000376 return matchesRecursively(Node, Matcher, Builder, 1, Traversal,
Manuel Klimek4da21662012-07-06 05:48:52 +0000377 Bind);
378 }
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000379 // Implements ASTMatchFinder::matchesDescendantOf.
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000380 virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node,
381 const DynTypedMatcher &Matcher,
Manuel Klimek4da21662012-07-06 05:48:52 +0000382 BoundNodesTreeBuilder *Builder,
383 BindKind Bind) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000384 return memoizedMatchesRecursively(Node, Matcher, Builder, INT_MAX,
Manuel Klimek4da21662012-07-06 05:48:52 +0000385 TK_AsIs, Bind);
386 }
Manuel Klimek579b1202012-09-07 09:26:10 +0000387 // Implements ASTMatchFinder::matchesAncestorOf.
388 virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node,
389 const DynTypedMatcher &Matcher,
Daniel Jasperc99a3ad2012-10-22 16:26:51 +0000390 BoundNodesTreeBuilder *Builder,
391 AncestorMatchMode MatchMode) {
Manuel Klimek374516c2013-03-14 16:33:21 +0000392 return memoizedMatchesAncestorOfRecursively(Node, Matcher, Builder,
393 MatchMode);
Manuel Klimek579b1202012-09-07 09:26:10 +0000394 }
Manuel Klimek4da21662012-07-06 05:48:52 +0000395
Manuel Klimek60969f52013-02-01 13:41:35 +0000396 // Matches all registered matchers on the given node and calls the
397 // result callback for every node that matches.
398 void match(const ast_type_traits::DynTypedNode& Node) {
399 for (std::vector<std::pair<const internal::DynTypedMatcher*,
400 MatchCallback*> >::const_iterator
401 I = MatcherCallbackPairs->begin(), E = MatcherCallbackPairs->end();
402 I != E; ++I) {
403 BoundNodesTreeBuilder Builder;
404 if (I->first->matches(Node, this, &Builder)) {
405 BoundNodesTree BoundNodes = Builder.build();
406 MatchVisitor Visitor(ActiveASTContext, I->second);
407 BoundNodes.visitMatches(&Visitor);
408 }
409 }
410 }
411
412 template <typename T> void match(const T &Node) {
413 match(ast_type_traits::DynTypedNode::create(Node));
414 }
415
Manuel Klimek7f2d4802012-11-30 13:45:19 +0000416 // Implements ASTMatchFinder::getASTContext.
417 virtual ASTContext &getASTContext() const { return *ActiveASTContext; }
418
Manuel Klimek4da21662012-07-06 05:48:52 +0000419 bool shouldVisitTemplateInstantiations() const { return true; }
420 bool shouldVisitImplicitCode() const { return true; }
Daniel Jasper278057f2012-11-15 03:29:05 +0000421 // Disables data recursion. We intercept Traverse* methods in the RAV, which
422 // are not triggered during data recursion.
423 bool shouldUseDataRecursionFor(clang::Stmt *S) const { return false; }
Manuel Klimek4da21662012-07-06 05:48:52 +0000424
425private:
Manuel Klimek374516c2013-03-14 16:33:21 +0000426 // Returns whether an ancestor of \p Node matches \p Matcher.
427 //
428 // The order of matching ((which can lead to different nodes being bound in
429 // case there are multiple matches) is breadth first search.
430 //
431 // To allow memoization in the very common case of having deeply nested
432 // expressions inside a template function, we first walk up the AST, memoizing
433 // the result of the match along the way, as long as there is only a single
434 // parent.
435 //
436 // Once there are multiple parents, the breadth first search order does not
437 // allow simple memoization on the ancestors. Thus, we only memoize as long
438 // as there is a single parent.
439 bool memoizedMatchesAncestorOfRecursively(
Manuel Klimek30ace372012-12-06 14:42:48 +0000440 const ast_type_traits::DynTypedNode &Node, const DynTypedMatcher &Matcher,
441 BoundNodesTreeBuilder *Builder, AncestorMatchMode MatchMode) {
442 if (Node.get<TranslationUnitDecl>() ==
443 ActiveASTContext->getTranslationUnitDecl())
444 return false;
445 assert(Node.getMemoizationData() &&
446 "Invariant broken: only nodes that support memoization may be "
447 "used in the parent map.");
Manuel Klimekff9a0102013-02-28 13:21:39 +0000448 ASTContext::ParentVector Parents = ActiveASTContext->getParents(Node);
449 if (Parents.empty()) {
Manuel Klimek30ace372012-12-06 14:42:48 +0000450 assert(false && "Found node that is not in the parent map.");
451 return false;
452 }
Manuel Klimek374516c2013-03-14 16:33:21 +0000453 const UntypedMatchInput input(Matcher.getID(), Node.getMemoizationData());
454 MemoizationMap::iterator I = ResultCache.find(input);
455 if (I == ResultCache.end()) {
456 BoundNodesTreeBuilder AncestorBoundNodesBuilder;
457 bool Matches = false;
458 if (Parents.size() == 1) {
459 // Only one parent - do recursive memoization.
460 const ast_type_traits::DynTypedNode Parent = Parents[0];
461 if (Matcher.matches(Parent, this, &AncestorBoundNodesBuilder)) {
462 Matches = true;
463 } else if (MatchMode != ASTMatchFinder::AMM_ParentOnly) {
464 Matches = memoizedMatchesAncestorOfRecursively(
465 Parent, Matcher, &AncestorBoundNodesBuilder, MatchMode);
466 }
467 } else {
468 // Multiple parents - BFS over the rest of the nodes.
469 llvm::DenseSet<const void *> Visited;
470 std::deque<ast_type_traits::DynTypedNode> Queue(Parents.begin(),
471 Parents.end());
472 while (!Queue.empty()) {
473 if (Matcher.matches(Queue.front(), this,
474 &AncestorBoundNodesBuilder)) {
475 Matches = true;
476 break;
477 }
478 if (MatchMode != ASTMatchFinder::AMM_ParentOnly) {
479 ASTContext::ParentVector Ancestors =
480 ActiveASTContext->getParents(Queue.front());
481 for (ASTContext::ParentVector::const_iterator I = Ancestors.begin(),
482 E = Ancestors.end();
483 I != E; ++I) {
484 // Make sure we do not visit the same node twice.
485 // Otherwise, we'll visit the common ancestors as often as there
486 // are splits on the way down.
487 if (Visited.insert(I->getMemoizationData()).second)
488 Queue.push_back(*I);
489 }
490 }
491 Queue.pop_front();
492 }
493 }
Manuel Klimek30ace372012-12-06 14:42:48 +0000494
Manuel Klimek374516c2013-03-14 16:33:21 +0000495 I = ResultCache.insert(std::make_pair(input, MemoizedMatchResult()))
496 .first;
497 I->second.Nodes = AncestorBoundNodesBuilder.build();
498 I->second.ResultOfMatch = Matches;
499 }
500 I->second.Nodes.copyTo(Builder);
501 return I->second.ResultOfMatch;
502 }
Manuel Klimek30ace372012-12-06 14:42:48 +0000503
Manuel Klimek4da21662012-07-06 05:48:52 +0000504 // Implements a BoundNodesTree::Visitor that calls a MatchCallback with
505 // the aggregated bound nodes for each match.
506 class MatchVisitor : public BoundNodesTree::Visitor {
507 public:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000508 MatchVisitor(ASTContext* Context,
Manuel Klimek4da21662012-07-06 05:48:52 +0000509 MatchFinder::MatchCallback* Callback)
510 : Context(Context),
511 Callback(Callback) {}
512
513 virtual void visitMatch(const BoundNodes& BoundNodesView) {
514 Callback->run(MatchFinder::MatchResult(BoundNodesView, Context));
515 }
516
517 private:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000518 ASTContext* Context;
Manuel Klimek4da21662012-07-06 05:48:52 +0000519 MatchFinder::MatchCallback* Callback;
520 };
521
Daniel Jasper20b802d2012-07-17 07:39:27 +0000522 // Returns true if 'TypeNode' has an alias that matches the given matcher.
523 bool typeHasMatchingAlias(const Type *TypeNode,
524 const Matcher<NamedDecl> Matcher,
525 BoundNodesTreeBuilder *Builder) {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000526 const Type *const CanonicalType =
Manuel Klimek4da21662012-07-06 05:48:52 +0000527 ActiveASTContext->getCanonicalType(TypeNode);
Daniel Jasper20b802d2012-07-17 07:39:27 +0000528 const std::set<const TypedefDecl*> &Aliases = TypeAliases[CanonicalType];
529 for (std::set<const TypedefDecl*>::const_iterator
530 It = Aliases.begin(), End = Aliases.end();
531 It != End; ++It) {
532 if (Matcher.matches(**It, this, Builder))
533 return true;
534 }
535 return false;
Manuel Klimek4da21662012-07-06 05:48:52 +0000536 }
537
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000538 std::vector<std::pair<const internal::DynTypedMatcher*,
539 MatchCallback*> > *const MatcherCallbackPairs;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000540 ASTContext *ActiveASTContext;
Manuel Klimek4da21662012-07-06 05:48:52 +0000541
Daniel Jasper20b802d2012-07-17 07:39:27 +0000542 // Maps a canonical type to its TypedefDecls.
543 llvm::DenseMap<const Type*, std::set<const TypedefDecl*> > TypeAliases;
Manuel Klimek4da21662012-07-06 05:48:52 +0000544
545 // Maps (matcher, node) -> the match result for memoization.
546 typedef llvm::DenseMap<UntypedMatchInput, MemoizedMatchResult> MemoizationMap;
547 MemoizationMap ResultCache;
548};
549
550// Returns true if the given class is directly or indirectly derived
Daniel Jasper76dafa72012-09-07 12:48:17 +0000551// from a base type with the given name. A class is not considered to be
552// derived from itself.
Daniel Jasper20b802d2012-07-17 07:39:27 +0000553bool MatchASTVisitor::classIsDerivedFrom(const CXXRecordDecl *Declaration,
554 const Matcher<NamedDecl> &Base,
555 BoundNodesTreeBuilder *Builder) {
Daniel Jasper20b802d2012-07-17 07:39:27 +0000556 if (!Declaration->hasDefinition())
Manuel Klimek4da21662012-07-06 05:48:52 +0000557 return false;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000558 typedef CXXRecordDecl::base_class_const_iterator BaseIterator;
Manuel Klimek4da21662012-07-06 05:48:52 +0000559 for (BaseIterator It = Declaration->bases_begin(),
560 End = Declaration->bases_end(); It != End; ++It) {
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000561 const Type *TypeNode = It->getType().getTypePtr();
Manuel Klimek4da21662012-07-06 05:48:52 +0000562
Daniel Jasper20b802d2012-07-17 07:39:27 +0000563 if (typeHasMatchingAlias(TypeNode, Base, Builder))
Manuel Klimek4da21662012-07-06 05:48:52 +0000564 return true;
565
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000566 // Type::getAs<...>() drills through typedefs.
567 if (TypeNode->getAs<DependentNameType>() != NULL ||
Daniel Jasper08f0c532012-09-18 14:17:42 +0000568 TypeNode->getAs<DependentTemplateSpecializationType>() != NULL ||
Daniel Jasper20b802d2012-07-17 07:39:27 +0000569 TypeNode->getAs<TemplateTypeParmType>() != NULL)
Manuel Klimek4da21662012-07-06 05:48:52 +0000570 // Dependent names and template TypeNode parameters will be matched when
571 // the template is instantiated.
572 continue;
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000573 CXXRecordDecl *ClassDecl = NULL;
574 TemplateSpecializationType const *TemplateType =
575 TypeNode->getAs<TemplateSpecializationType>();
Manuel Klimek4da21662012-07-06 05:48:52 +0000576 if (TemplateType != NULL) {
Daniel Jasper20b802d2012-07-17 07:39:27 +0000577 if (TemplateType->getTemplateName().isDependent())
Manuel Klimek4da21662012-07-06 05:48:52 +0000578 // Dependent template specializations will be matched when the
579 // template is instantiated.
580 continue;
Daniel Jasper20b802d2012-07-17 07:39:27 +0000581
Manuel Klimek4da21662012-07-06 05:48:52 +0000582 // For template specialization types which are specializing a template
583 // declaration which is an explicit or partial specialization of another
584 // template declaration, getAsCXXRecordDecl() returns the corresponding
585 // ClassTemplateSpecializationDecl.
586 //
587 // For template specialization types which are specializing a template
588 // declaration which is neither an explicit nor partial specialization of
589 // another template declaration, getAsCXXRecordDecl() returns NULL and
590 // we get the CXXRecordDecl of the templated declaration.
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000591 CXXRecordDecl *SpecializationDecl =
Manuel Klimek4da21662012-07-06 05:48:52 +0000592 TemplateType->getAsCXXRecordDecl();
593 if (SpecializationDecl != NULL) {
594 ClassDecl = SpecializationDecl;
595 } else {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000596 ClassDecl = dyn_cast<CXXRecordDecl>(
Manuel Klimek4da21662012-07-06 05:48:52 +0000597 TemplateType->getTemplateName()
598 .getAsTemplateDecl()->getTemplatedDecl());
599 }
600 } else {
601 ClassDecl = TypeNode->getAsCXXRecordDecl();
602 }
603 assert(ClassDecl != NULL);
Manuel Klimek987c2f52012-12-04 13:40:29 +0000604 if (ClassDecl == Declaration) {
605 // This can happen for recursive template definitions; if the
606 // current declaration did not match, we can safely return false.
607 assert(TemplateType);
608 return false;
609 }
Daniel Jasper76dafa72012-09-07 12:48:17 +0000610 if (Base.matches(*ClassDecl, this, Builder))
611 return true;
Daniel Jasper20b802d2012-07-17 07:39:27 +0000612 if (classIsDerivedFrom(ClassDecl, Base, Builder))
Manuel Klimek4da21662012-07-06 05:48:52 +0000613 return true;
Manuel Klimek4da21662012-07-06 05:48:52 +0000614 }
615 return false;
616}
617
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000618bool MatchASTVisitor::TraverseDecl(Decl *DeclNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000619 if (DeclNode == NULL) {
620 return true;
621 }
622 match(*DeclNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000623 return RecursiveASTVisitor<MatchASTVisitor>::TraverseDecl(DeclNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000624}
625
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000626bool MatchASTVisitor::TraverseStmt(Stmt *StmtNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000627 if (StmtNode == NULL) {
628 return true;
629 }
630 match(*StmtNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000631 return RecursiveASTVisitor<MatchASTVisitor>::TraverseStmt(StmtNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000632}
633
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000634bool MatchASTVisitor::TraverseType(QualType TypeNode) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000635 match(TypeNode);
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000636 return RecursiveASTVisitor<MatchASTVisitor>::TraverseType(TypeNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000637}
638
Daniel Jasperce620072012-10-17 08:52:59 +0000639bool MatchASTVisitor::TraverseTypeLoc(TypeLoc TypeLocNode) {
640 // The RecursiveASTVisitor only visits types if they're not within TypeLocs.
641 // We still want to find those types via matchers, so we match them here. Note
642 // that the TypeLocs are structurally a shadow-hierarchy to the expressed
643 // type, so we visit all involved parts of a compound type when matching on
644 // each TypeLoc.
645 match(TypeLocNode);
646 match(TypeLocNode.getType());
647 return RecursiveASTVisitor<MatchASTVisitor>::TraverseTypeLoc(TypeLocNode);
Manuel Klimek4da21662012-07-06 05:48:52 +0000648}
649
Daniel Jaspera7564432012-09-13 13:11:25 +0000650bool MatchASTVisitor::TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
651 match(*NNS);
652 return RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifier(NNS);
653}
654
655bool MatchASTVisitor::TraverseNestedNameSpecifierLoc(
656 NestedNameSpecifierLoc NNS) {
657 match(NNS);
658 // We only match the nested name specifier here (as opposed to traversing it)
659 // because the traversal is already done in the parallel "Loc"-hierarchy.
660 match(*NNS.getNestedNameSpecifier());
661 return
662 RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifierLoc(NNS);
663}
664
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000665class MatchASTConsumer : public ASTConsumer {
Manuel Klimek4da21662012-07-06 05:48:52 +0000666public:
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000667 MatchASTConsumer(
668 std::vector<std::pair<const internal::DynTypedMatcher*,
669 MatchCallback*> > *MatcherCallbackPairs,
670 MatchFinder::ParsingDoneTestCallback *ParsingDone)
671 : Visitor(MatcherCallbackPairs),
672 ParsingDone(ParsingDone) {}
Manuel Klimek4da21662012-07-06 05:48:52 +0000673
674private:
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000675 virtual void HandleTranslationUnit(ASTContext &Context) {
Manuel Klimek4da21662012-07-06 05:48:52 +0000676 if (ParsingDone != NULL) {
677 ParsingDone->run();
678 }
679 Visitor.set_active_ast_context(&Context);
Manuel Klimeke5793282012-11-02 01:31:03 +0000680 Visitor.onStartOfTranslationUnit();
Manuel Klimek4da21662012-07-06 05:48:52 +0000681 Visitor.TraverseDecl(Context.getTranslationUnitDecl());
682 Visitor.set_active_ast_context(NULL);
683 }
684
685 MatchASTVisitor Visitor;
686 MatchFinder::ParsingDoneTestCallback *ParsingDone;
687};
688
689} // end namespace
690} // end namespace internal
691
692MatchFinder::MatchResult::MatchResult(const BoundNodes &Nodes,
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000693 ASTContext *Context)
Manuel Klimek4da21662012-07-06 05:48:52 +0000694 : Nodes(Nodes), Context(Context),
695 SourceManager(&Context->getSourceManager()) {}
696
697MatchFinder::MatchCallback::~MatchCallback() {}
698MatchFinder::ParsingDoneTestCallback::~ParsingDoneTestCallback() {}
699
700MatchFinder::MatchFinder() : ParsingDone(NULL) {}
701
702MatchFinder::~MatchFinder() {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000703 for (std::vector<std::pair<const internal::DynTypedMatcher*,
704 MatchCallback*> >::const_iterator
705 It = MatcherCallbackPairs.begin(), End = MatcherCallbackPairs.end();
Manuel Klimek4da21662012-07-06 05:48:52 +0000706 It != End; ++It) {
707 delete It->first;
708 }
709}
710
711void MatchFinder::addMatcher(const DeclarationMatcher &NodeMatch,
712 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000713 MatcherCallbackPairs.push_back(std::make_pair(
714 new internal::Matcher<Decl>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000715}
716
717void MatchFinder::addMatcher(const TypeMatcher &NodeMatch,
718 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000719 MatcherCallbackPairs.push_back(std::make_pair(
720 new internal::Matcher<QualType>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000721}
722
723void MatchFinder::addMatcher(const StatementMatcher &NodeMatch,
724 MatchCallback *Action) {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000725 MatcherCallbackPairs.push_back(std::make_pair(
726 new internal::Matcher<Stmt>(NodeMatch), Action));
Manuel Klimek4da21662012-07-06 05:48:52 +0000727}
728
Daniel Jaspera7564432012-09-13 13:11:25 +0000729void MatchFinder::addMatcher(const NestedNameSpecifierMatcher &NodeMatch,
730 MatchCallback *Action) {
731 MatcherCallbackPairs.push_back(std::make_pair(
732 new NestedNameSpecifierMatcher(NodeMatch), Action));
733}
734
735void MatchFinder::addMatcher(const NestedNameSpecifierLocMatcher &NodeMatch,
736 MatchCallback *Action) {
737 MatcherCallbackPairs.push_back(std::make_pair(
738 new NestedNameSpecifierLocMatcher(NodeMatch), Action));
739}
740
Daniel Jasperce620072012-10-17 08:52:59 +0000741void MatchFinder::addMatcher(const TypeLocMatcher &NodeMatch,
742 MatchCallback *Action) {
743 MatcherCallbackPairs.push_back(std::make_pair(
744 new TypeLocMatcher(NodeMatch), Action));
745}
746
Daniel Jaspere0e6b9e2012-07-10 20:20:19 +0000747ASTConsumer *MatchFinder::newASTConsumer() {
Manuel Klimeka78d0d62012-09-05 12:12:07 +0000748 return new internal::MatchASTConsumer(&MatcherCallbackPairs, ParsingDone);
Manuel Klimek4da21662012-07-06 05:48:52 +0000749}
750
Manuel Klimek60969f52013-02-01 13:41:35 +0000751void MatchFinder::match(const clang::ast_type_traits::DynTypedNode &Node,
752 ASTContext &Context) {
Manuel Klimek3e2aa992012-10-24 14:47:44 +0000753 internal::MatchASTVisitor Visitor(&MatcherCallbackPairs);
754 Visitor.set_active_ast_context(&Context);
Manuel Klimek60969f52013-02-01 13:41:35 +0000755 Visitor.match(Node);
Manuel Klimek3e2aa992012-10-24 14:47:44 +0000756}
757
Manuel Klimek4da21662012-07-06 05:48:52 +0000758void MatchFinder::registerTestCallbackAfterParsing(
759 MatchFinder::ParsingDoneTestCallback *NewParsingDone) {
760 ParsingDone = NewParsingDone;
761}
762
763} // end namespace ast_matchers
764} // end namespace clang