blob: 685b17e9129992a63b277ab24307a44b9fded0ba [file] [log] [blame]
Manuel Klimek04616e42012-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 Klimekb64d6b72013-03-14 16:33:21 +000023#include <deque>
Manuel Klimek04616e42012-07-06 05:48:52 +000024#include <set>
25
26namespace clang {
27namespace ast_matchers {
28namespace internal {
29namespace {
30
Manuel Klimekeb958de2012-09-05 12:12:07 +000031typedef MatchFinder::MatchCallback MatchCallback;
32
Manuel Klimeka0c025f2013-06-19 15:42:45 +000033// The maximum number of memoization entries to store.
34// 10k has been experimentally found to give a good trade-off
35// of performance vs. memory consumption by running matcher
36// that match on every statement over a very large codebase.
37//
38// FIXME: Do some performance optimization in general and
39// revisit this number; also, put up micro-benchmarks that we can
40// optimize this on.
41static const unsigned MaxMemoizationEntries = 10000;
42
Manuel Klimek04616e42012-07-06 05:48:52 +000043// We use memoization to avoid running the same matcher on the same
Manuel Klimeka0c025f2013-06-19 15:42:45 +000044// AST node twice. This struct is the key for looking up match
Manuel Klimek04616e42012-07-06 05:48:52 +000045// result. It consists of an ID of the MatcherInterface (for
Manuel Klimeka0c025f2013-06-19 15:42:45 +000046// identifying the matcher), a pointer to the AST node and the
47// bound nodes before the matcher was executed.
Manuel Klimekeb958de2012-09-05 12:12:07 +000048//
49// We currently only memoize on nodes whose pointers identify the
50// nodes (\c Stmt and \c Decl, but not \c QualType or \c TypeLoc).
51// For \c QualType and \c TypeLoc it is possible to implement
52// generation of keys for each type.
53// FIXME: Benchmark whether memoization of non-pointer typed nodes
54// provides enough benefit for the additional amount of code.
Manuel Klimeka0c025f2013-06-19 15:42:45 +000055struct MatchKey {
Samuel Benzaquenf28d9972014-10-01 15:08:07 +000056 DynTypedMatcher::MatcherIDType MatcherID;
Manuel Klimeka0c025f2013-06-19 15:42:45 +000057 ast_type_traits::DynTypedNode Node;
58 BoundNodesTreeBuilder BoundNodes;
59
60 bool operator<(const MatchKey &Other) const {
Benjamin Kramera741b8c2014-03-03 20:26:46 +000061 return std::tie(MatcherID, Node, BoundNodes) <
62 std::tie(Other.MatcherID, Other.Node, Other.BoundNodes);
Manuel Klimeka0c025f2013-06-19 15:42:45 +000063 }
64};
Manuel Klimek04616e42012-07-06 05:48:52 +000065
66// Used to store the result of a match and possibly bound nodes.
67struct MemoizedMatchResult {
68 bool ResultOfMatch;
Manuel Klimeka0c025f2013-06-19 15:42:45 +000069 BoundNodesTreeBuilder Nodes;
Manuel Klimek04616e42012-07-06 05:48:52 +000070};
71
72// A RecursiveASTVisitor that traverses all children or all descendants of
73// a node.
74class MatchChildASTVisitor
Daniel Jasper1dad1832012-07-10 20:20:19 +000075 : public RecursiveASTVisitor<MatchChildASTVisitor> {
Manuel Klimek04616e42012-07-06 05:48:52 +000076public:
Daniel Jasper1dad1832012-07-10 20:20:19 +000077 typedef RecursiveASTVisitor<MatchChildASTVisitor> VisitorBase;
Manuel Klimek04616e42012-07-06 05:48:52 +000078
79 // Creates an AST visitor that matches 'matcher' on all children or
80 // descendants of a traversed node. max_depth is the maximum depth
81 // to traverse: use 1 for matching the children and INT_MAX for
82 // matching the descendants.
Manuel Klimekeb958de2012-09-05 12:12:07 +000083 MatchChildASTVisitor(const DynTypedMatcher *Matcher,
Manuel Klimek04616e42012-07-06 05:48:52 +000084 ASTMatchFinder *Finder,
85 BoundNodesTreeBuilder *Builder,
86 int MaxDepth,
87 ASTMatchFinder::TraversalKind Traversal,
88 ASTMatchFinder::BindKind Bind)
Manuel Klimekeb958de2012-09-05 12:12:07 +000089 : Matcher(Matcher),
Manuel Klimek04616e42012-07-06 05:48:52 +000090 Finder(Finder),
91 Builder(Builder),
Daniel Jasperd29d5fa2012-10-29 10:14:44 +000092 CurrentDepth(0),
Manuel Klimek04616e42012-07-06 05:48:52 +000093 MaxDepth(MaxDepth),
94 Traversal(Traversal),
95 Bind(Bind),
96 Matches(false) {}
97
98 // Returns true if a match is found in the subtree rooted at the
99 // given AST node. This is done via a set of mutually recursive
100 // functions. Here's how the recursion is done (the *wildcard can
101 // actually be Decl, Stmt, or Type):
102 //
103 // - Traverse(node) calls BaseTraverse(node) when it needs
104 // to visit the descendants of node.
105 // - BaseTraverse(node) then calls (via VisitorBase::Traverse*(node))
106 // Traverse*(c) for each child c of 'node'.
107 // - Traverse*(c) in turn calls Traverse(c), completing the
108 // recursion.
Manuel Klimekeb958de2012-09-05 12:12:07 +0000109 bool findMatch(const ast_type_traits::DynTypedNode &DynNode) {
Manuel Klimek04616e42012-07-06 05:48:52 +0000110 reset();
Manuel Klimekeb958de2012-09-05 12:12:07 +0000111 if (const Decl *D = DynNode.get<Decl>())
112 traverse(*D);
113 else if (const Stmt *S = DynNode.get<Stmt>())
114 traverse(*S);
Daniel Jasper6fc34332012-10-30 15:42:00 +0000115 else if (const NestedNameSpecifier *NNS =
116 DynNode.get<NestedNameSpecifier>())
117 traverse(*NNS);
118 else if (const NestedNameSpecifierLoc *NNSLoc =
119 DynNode.get<NestedNameSpecifierLoc>())
120 traverse(*NNSLoc);
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000121 else if (const QualType *Q = DynNode.get<QualType>())
122 traverse(*Q);
123 else if (const TypeLoc *T = DynNode.get<TypeLoc>())
124 traverse(*T);
Manuel Klimekeb958de2012-09-05 12:12:07 +0000125 // FIXME: Add other base types after adding tests.
Manuel Klimeka0c025f2013-06-19 15:42:45 +0000126
127 // It's OK to always overwrite the bound nodes, as if there was
128 // no match in this recursive branch, the result set is empty
129 // anyway.
130 *Builder = ResultBindings;
131
Manuel Klimek04616e42012-07-06 05:48:52 +0000132 return Matches;
133 }
134
135 // The following are overriding methods from the base visitor class.
136 // They are public only to allow CRTP to work. They are *not *part
137 // of the public API of this class.
Daniel Jasper1dad1832012-07-10 20:20:19 +0000138 bool TraverseDecl(Decl *DeclNode) {
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000139 ScopedIncrement ScopedDepth(&CurrentDepth);
Craig Topper210e1ad2014-05-17 18:49:24 +0000140 return (DeclNode == nullptr) || traverse(*DeclNode);
Manuel Klimek04616e42012-07-06 05:48:52 +0000141 }
Daniel Jasper1dad1832012-07-10 20:20:19 +0000142 bool TraverseStmt(Stmt *StmtNode) {
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000143 ScopedIncrement ScopedDepth(&CurrentDepth);
Daniel Jasper1dad1832012-07-10 20:20:19 +0000144 const Stmt *StmtToTraverse = StmtNode;
Manuel Klimek04616e42012-07-06 05:48:52 +0000145 if (Traversal ==
146 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses) {
Daniel Jasper1dad1832012-07-10 20:20:19 +0000147 const Expr *ExprNode = dyn_cast_or_null<Expr>(StmtNode);
Craig Topper210e1ad2014-05-17 18:49:24 +0000148 if (ExprNode) {
Manuel Klimek04616e42012-07-06 05:48:52 +0000149 StmtToTraverse = ExprNode->IgnoreParenImpCasts();
150 }
151 }
Craig Topper210e1ad2014-05-17 18:49:24 +0000152 return (StmtToTraverse == nullptr) || traverse(*StmtToTraverse);
Manuel Klimek04616e42012-07-06 05:48:52 +0000153 }
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000154 // We assume that the QualType and the contained type are on the same
155 // hierarchy level. Thus, we try to match either of them.
Daniel Jasper1dad1832012-07-10 20:20:19 +0000156 bool TraverseType(QualType TypeNode) {
Daniel Jaspera05bb6b2012-11-13 17:14:11 +0000157 if (TypeNode.isNull())
158 return true;
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000159 ScopedIncrement ScopedDepth(&CurrentDepth);
160 // Match the Type.
161 if (!match(*TypeNode))
162 return false;
163 // The QualType is matched inside traverse.
Manuel Klimek04616e42012-07-06 05:48:52 +0000164 return traverse(TypeNode);
165 }
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000166 // We assume that the TypeLoc, contained QualType and contained Type all are
167 // on the same hierarchy level. Thus, we try to match all of them.
168 bool TraverseTypeLoc(TypeLoc TypeLocNode) {
Daniel Jaspera05bb6b2012-11-13 17:14:11 +0000169 if (TypeLocNode.isNull())
170 return true;
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000171 ScopedIncrement ScopedDepth(&CurrentDepth);
172 // Match the Type.
173 if (!match(*TypeLocNode.getType()))
174 return false;
175 // Match the QualType.
176 if (!match(TypeLocNode.getType()))
177 return false;
178 // The TypeLoc is matched inside traverse.
179 return traverse(TypeLocNode);
180 }
Daniel Jasper6fc34332012-10-30 15:42:00 +0000181 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
182 ScopedIncrement ScopedDepth(&CurrentDepth);
Craig Topper210e1ad2014-05-17 18:49:24 +0000183 return (NNS == nullptr) || traverse(*NNS);
Daniel Jasper6fc34332012-10-30 15:42:00 +0000184 }
185 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
Daniel Jaspera05bb6b2012-11-13 17:14:11 +0000186 if (!NNS)
187 return true;
Daniel Jasper6fc34332012-10-30 15:42:00 +0000188 ScopedIncrement ScopedDepth(&CurrentDepth);
189 if (!match(*NNS.getNestedNameSpecifier()))
190 return false;
Daniel Jaspera05bb6b2012-11-13 17:14:11 +0000191 return traverse(NNS);
Daniel Jasper6fc34332012-10-30 15:42:00 +0000192 }
Manuel Klimek04616e42012-07-06 05:48:52 +0000193
194 bool shouldVisitTemplateInstantiations() const { return true; }
195 bool shouldVisitImplicitCode() const { return true; }
Daniel Jasper0f9f0192012-11-15 03:29:05 +0000196 // Disables data recursion. We intercept Traverse* methods in the RAV, which
197 // are not triggered during data recursion.
198 bool shouldUseDataRecursionFor(clang::Stmt *S) const { return false; }
Manuel Klimek04616e42012-07-06 05:48:52 +0000199
200private:
201 // Used for updating the depth during traversal.
202 struct ScopedIncrement {
203 explicit ScopedIncrement(int *Depth) : Depth(Depth) { ++(*Depth); }
204 ~ScopedIncrement() { --(*Depth); }
205
206 private:
207 int *Depth;
208 };
209
210 // Resets the state of this object.
211 void reset() {
212 Matches = false;
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000213 CurrentDepth = 0;
Manuel Klimek04616e42012-07-06 05:48:52 +0000214 }
215
216 // Forwards the call to the corresponding Traverse*() method in the
217 // base visitor class.
Daniel Jasper1dad1832012-07-10 20:20:19 +0000218 bool baseTraverse(const Decl &DeclNode) {
219 return VisitorBase::TraverseDecl(const_cast<Decl*>(&DeclNode));
Manuel Klimek04616e42012-07-06 05:48:52 +0000220 }
Daniel Jasper1dad1832012-07-10 20:20:19 +0000221 bool baseTraverse(const Stmt &StmtNode) {
222 return VisitorBase::TraverseStmt(const_cast<Stmt*>(&StmtNode));
Manuel Klimek04616e42012-07-06 05:48:52 +0000223 }
Daniel Jasper1dad1832012-07-10 20:20:19 +0000224 bool baseTraverse(QualType TypeNode) {
Manuel Klimek04616e42012-07-06 05:48:52 +0000225 return VisitorBase::TraverseType(TypeNode);
226 }
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000227 bool baseTraverse(TypeLoc TypeLocNode) {
228 return VisitorBase::TraverseTypeLoc(TypeLocNode);
229 }
Daniel Jasper6fc34332012-10-30 15:42:00 +0000230 bool baseTraverse(const NestedNameSpecifier &NNS) {
231 return VisitorBase::TraverseNestedNameSpecifier(
232 const_cast<NestedNameSpecifier*>(&NNS));
233 }
234 bool baseTraverse(NestedNameSpecifierLoc NNS) {
235 return VisitorBase::TraverseNestedNameSpecifierLoc(NNS);
236 }
Manuel Klimek04616e42012-07-06 05:48:52 +0000237
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000238 // Sets 'Matched' to true if 'Matcher' matches 'Node' and:
239 // 0 < CurrentDepth <= MaxDepth.
240 //
241 // Returns 'true' if traversal should continue after this function
242 // returns, i.e. if no match is found or 'Bind' is 'BK_All'.
Manuel Klimek04616e42012-07-06 05:48:52 +0000243 template <typename T>
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000244 bool match(const T &Node) {
245 if (CurrentDepth == 0 || CurrentDepth > MaxDepth) {
246 return true;
Manuel Klimek04616e42012-07-06 05:48:52 +0000247 }
248 if (Bind != ASTMatchFinder::BK_All) {
Manuel Klimeka0c025f2013-06-19 15:42:45 +0000249 BoundNodesTreeBuilder RecursiveBuilder(*Builder);
250 if (Matcher->matches(ast_type_traits::DynTypedNode::create(Node), Finder,
251 &RecursiveBuilder)) {
Manuel Klimek04616e42012-07-06 05:48:52 +0000252 Matches = true;
Manuel Klimeka0c025f2013-06-19 15:42:45 +0000253 ResultBindings.addMatch(RecursiveBuilder);
254 return false; // Abort as soon as a match is found.
Manuel Klimek04616e42012-07-06 05:48:52 +0000255 }
Manuel Klimek04616e42012-07-06 05:48:52 +0000256 } else {
Manuel Klimeka0c025f2013-06-19 15:42:45 +0000257 BoundNodesTreeBuilder RecursiveBuilder(*Builder);
258 if (Matcher->matches(ast_type_traits::DynTypedNode::create(Node), Finder,
259 &RecursiveBuilder)) {
Manuel Klimek04616e42012-07-06 05:48:52 +0000260 // After the first match the matcher succeeds.
261 Matches = true;
Manuel Klimeka0c025f2013-06-19 15:42:45 +0000262 ResultBindings.addMatch(RecursiveBuilder);
Manuel Klimek04616e42012-07-06 05:48:52 +0000263 }
Manuel Klimek04616e42012-07-06 05:48:52 +0000264 }
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000265 return true;
266 }
267
268 // Traverses the subtree rooted at 'Node'; returns true if the
269 // traversal should continue after this function returns.
270 template <typename T>
271 bool traverse(const T &Node) {
Benjamin Kramerbd39f6e2014-03-02 17:08:43 +0000272 static_assert(IsBaseType<T>::value,
273 "traverse can only be instantiated with base type");
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000274 if (!match(Node))
275 return false;
276 return baseTraverse(Node);
Manuel Klimek04616e42012-07-06 05:48:52 +0000277 }
278
Manuel Klimekeb958de2012-09-05 12:12:07 +0000279 const DynTypedMatcher *const Matcher;
Manuel Klimek04616e42012-07-06 05:48:52 +0000280 ASTMatchFinder *const Finder;
281 BoundNodesTreeBuilder *const Builder;
Manuel Klimeka0c025f2013-06-19 15:42:45 +0000282 BoundNodesTreeBuilder ResultBindings;
Manuel Klimek04616e42012-07-06 05:48:52 +0000283 int CurrentDepth;
284 const int MaxDepth;
285 const ASTMatchFinder::TraversalKind Traversal;
286 const ASTMatchFinder::BindKind Bind;
287 bool Matches;
288};
289
290// Controls the outermost traversal of the AST and allows to match multiple
291// matchers.
Daniel Jasper1dad1832012-07-10 20:20:19 +0000292class MatchASTVisitor : public RecursiveASTVisitor<MatchASTVisitor>,
Manuel Klimek04616e42012-07-06 05:48:52 +0000293 public ASTMatchFinder {
294public:
Samuel Benzaquen7ec2cb22014-09-05 20:15:31 +0000295 MatchASTVisitor(const MatchFinder::MatchersByType *Matchers)
296 : Matchers(Matchers), ActiveASTContext(nullptr) {}
Manuel Klimek04616e42012-07-06 05:48:52 +0000297
Manuel Klimekbd0e2b72012-11-02 01:31:03 +0000298 void onStartOfTranslationUnit() {
Samuel Benzaquen7ec2cb22014-09-05 20:15:31 +0000299 for (MatchCallback *MC : Matchers->AllCallbacks)
300 MC->onStartOfTranslationUnit();
Manuel Klimekbd0e2b72012-11-02 01:31:03 +0000301 }
302
Peter Collingbourne6a55bb22013-05-28 19:21:51 +0000303 void onEndOfTranslationUnit() {
Samuel Benzaquen7ec2cb22014-09-05 20:15:31 +0000304 for (MatchCallback *MC : Matchers->AllCallbacks)
305 MC->onEndOfTranslationUnit();
Peter Collingbourne6a55bb22013-05-28 19:21:51 +0000306 }
307
Daniel Jasper1dad1832012-07-10 20:20:19 +0000308 void set_active_ast_context(ASTContext *NewActiveASTContext) {
Manuel Klimek04616e42012-07-06 05:48:52 +0000309 ActiveASTContext = NewActiveASTContext;
310 }
311
312 // The following Visit*() and Traverse*() functions "override"
313 // methods in RecursiveASTVisitor.
314
Manuel Klimek1863e502013-08-02 21:24:09 +0000315 bool VisitTypedefNameDecl(TypedefNameDecl *DeclNode) {
Manuel Klimek04616e42012-07-06 05:48:52 +0000316 // When we see 'typedef A B', we add name 'B' to the set of names
317 // A's canonical type maps to. This is necessary for implementing
Daniel Jasperf49d1e02012-09-07 12:48:17 +0000318 // isDerivedFrom(x) properly, where x can be the name of the base
Manuel Klimek04616e42012-07-06 05:48:52 +0000319 // class or any of its aliases.
320 //
321 // In general, the is-alias-of (as defined by typedefs) relation
322 // is tree-shaped, as you can typedef a type more than once. For
323 // example,
324 //
325 // typedef A B;
326 // typedef A C;
327 // typedef C D;
328 // typedef C E;
329 //
330 // gives you
331 //
332 // A
333 // |- B
334 // `- C
335 // |- D
336 // `- E
337 //
338 // It is wrong to assume that the relation is a chain. A correct
Daniel Jasperf49d1e02012-09-07 12:48:17 +0000339 // implementation of isDerivedFrom() needs to recognize that B and
Manuel Klimek04616e42012-07-06 05:48:52 +0000340 // E are aliases, even though neither is a typedef of the other.
341 // Therefore, we cannot simply walk through one typedef chain to
342 // find out whether the type name matches.
Daniel Jasper1dad1832012-07-10 20:20:19 +0000343 const Type *TypeNode = DeclNode->getUnderlyingType().getTypePtr();
344 const Type *CanonicalType = // root of the typedef tree
Manuel Klimek04616e42012-07-06 05:48:52 +0000345 ActiveASTContext->getCanonicalType(TypeNode);
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000346 TypeAliases[CanonicalType].insert(DeclNode);
Manuel Klimek04616e42012-07-06 05:48:52 +0000347 return true;
348 }
349
Daniel Jasper1dad1832012-07-10 20:20:19 +0000350 bool TraverseDecl(Decl *DeclNode);
351 bool TraverseStmt(Stmt *StmtNode);
352 bool TraverseType(QualType TypeNode);
353 bool TraverseTypeLoc(TypeLoc TypeNode);
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000354 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS);
355 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
Manuel Klimek04616e42012-07-06 05:48:52 +0000356
357 // Matches children or descendants of 'Node' with 'BaseMatcher'.
Manuel Klimekeb958de2012-09-05 12:12:07 +0000358 bool memoizedMatchesRecursively(const ast_type_traits::DynTypedNode &Node,
359 const DynTypedMatcher &Matcher,
Manuel Klimek04616e42012-07-06 05:48:52 +0000360 BoundNodesTreeBuilder *Builder, int MaxDepth,
361 TraversalKind Traversal, BindKind Bind) {
Manuel Klimek55d8fb52013-07-16 13:20:30 +0000362 // For AST-nodes that don't have an identity, we can't memoize.
Daniel Jasper3dfa09b2014-07-23 13:17:47 +0000363 if (!Node.getMemoizationData() || !Builder->isComparable())
Manuel Klimek55d8fb52013-07-16 13:20:30 +0000364 return matchesRecursively(Node, Matcher, Builder, MaxDepth, Traversal,
365 Bind);
366
Manuel Klimeka0c025f2013-06-19 15:42:45 +0000367 MatchKey Key;
368 Key.MatcherID = Matcher.getID();
369 Key.Node = Node;
370 // Note that we key on the bindings *before* the match.
371 Key.BoundNodes = *Builder;
Daniel Jasperd29d5fa2012-10-29 10:14:44 +0000372
Manuel Klimek55d8fb52013-07-16 13:20:30 +0000373 MemoizationMap::iterator I = ResultCache.find(Key);
374 if (I != ResultCache.end()) {
375 *Builder = I->second.Nodes;
376 return I->second.ResultOfMatch;
Manuel Klimek04616e42012-07-06 05:48:52 +0000377 }
Manuel Klimek55d8fb52013-07-16 13:20:30 +0000378
379 MemoizedMatchResult Result;
Manuel Klimek55d8fb52013-07-16 13:20:30 +0000380 Result.Nodes = *Builder;
381 Result.ResultOfMatch = matchesRecursively(Node, Matcher, &Result.Nodes,
382 MaxDepth, Traversal, Bind);
383 ResultCache[Key] = Result;
384 *Builder = Result.Nodes;
385 return Result.ResultOfMatch;
Manuel Klimek04616e42012-07-06 05:48:52 +0000386 }
387
388 // Matches children or descendants of 'Node' with 'BaseMatcher'.
Manuel Klimekeb958de2012-09-05 12:12:07 +0000389 bool matchesRecursively(const ast_type_traits::DynTypedNode &Node,
390 const DynTypedMatcher &Matcher,
Manuel Klimek04616e42012-07-06 05:48:52 +0000391 BoundNodesTreeBuilder *Builder, int MaxDepth,
392 TraversalKind Traversal, BindKind Bind) {
393 MatchChildASTVisitor Visitor(
Manuel Klimekeb958de2012-09-05 12:12:07 +0000394 &Matcher, this, Builder, MaxDepth, Traversal, Bind);
Manuel Klimek04616e42012-07-06 05:48:52 +0000395 return Visitor.findMatch(Node);
396 }
397
Craig Topper2e5c11f2014-03-13 08:12:15 +0000398 bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
399 const Matcher<NamedDecl> &Base,
400 BoundNodesTreeBuilder *Builder) override;
Manuel Klimek04616e42012-07-06 05:48:52 +0000401
Daniel Jasper632aea92012-10-22 16:26:51 +0000402 // Implements ASTMatchFinder::matchesChildOf.
Craig Topper2e5c11f2014-03-13 08:12:15 +0000403 bool matchesChildOf(const ast_type_traits::DynTypedNode &Node,
404 const DynTypedMatcher &Matcher,
405 BoundNodesTreeBuilder *Builder,
406 TraversalKind Traversal,
407 BindKind Bind) override {
Daniel Jasperabe2a362013-07-25 09:32:14 +0000408 if (ResultCache.size() > MaxMemoizationEntries)
409 ResultCache.clear();
410 return memoizedMatchesRecursively(Node, Matcher, Builder, 1, Traversal,
411 Bind);
Manuel Klimek04616e42012-07-06 05:48:52 +0000412 }
Daniel Jasper632aea92012-10-22 16:26:51 +0000413 // Implements ASTMatchFinder::matchesDescendantOf.
Craig Topper2e5c11f2014-03-13 08:12:15 +0000414 bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node,
415 const DynTypedMatcher &Matcher,
416 BoundNodesTreeBuilder *Builder,
417 BindKind Bind) override {
Manuel Klimek7e3d9692013-07-08 14:16:30 +0000418 if (ResultCache.size() > MaxMemoizationEntries)
419 ResultCache.clear();
Manuel Klimekeb958de2012-09-05 12:12:07 +0000420 return memoizedMatchesRecursively(Node, Matcher, Builder, INT_MAX,
Manuel Klimek04616e42012-07-06 05:48:52 +0000421 TK_AsIs, Bind);
422 }
Manuel Klimek3ca12c52012-09-07 09:26:10 +0000423 // Implements ASTMatchFinder::matchesAncestorOf.
Craig Topper2e5c11f2014-03-13 08:12:15 +0000424 bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node,
425 const DynTypedMatcher &Matcher,
426 BoundNodesTreeBuilder *Builder,
427 AncestorMatchMode MatchMode) override {
Manuel Klimek7e3d9692013-07-08 14:16:30 +0000428 // Reset the cache outside of the recursive call to make sure we
429 // don't invalidate any iterators.
430 if (ResultCache.size() > MaxMemoizationEntries)
431 ResultCache.clear();
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000432 return memoizedMatchesAncestorOfRecursively(Node, Matcher, Builder,
433 MatchMode);
Manuel Klimek3ca12c52012-09-07 09:26:10 +0000434 }
Manuel Klimek04616e42012-07-06 05:48:52 +0000435
Manuel Klimek191c0932013-02-01 13:41:35 +0000436 // Matches all registered matchers on the given node and calls the
437 // result callback for every node that matches.
Samuel Benzaquen7ec2cb22014-09-05 20:15:31 +0000438 void match(const ast_type_traits::DynTypedNode &Node) {
439 // FIXME: Improve this with a switch or a visitor pattern.
440 if (auto *N = Node.get<Decl>()) {
441 match(*N);
442 } else if (auto *N = Node.get<Stmt>()) {
443 match(*N);
444 } else if (auto *N = Node.get<Type>()) {
445 match(*N);
446 } else if (auto *N = Node.get<QualType>()) {
447 match(*N);
448 } else if (auto *N = Node.get<NestedNameSpecifier>()) {
449 match(*N);
450 } else if (auto *N = Node.get<NestedNameSpecifierLoc>()) {
451 match(*N);
452 } else if (auto *N = Node.get<TypeLoc>()) {
453 match(*N);
Manuel Klimek191c0932013-02-01 13:41:35 +0000454 }
455 }
456
457 template <typename T> void match(const T &Node) {
Samuel Benzaquen7ec2cb22014-09-05 20:15:31 +0000458 matchDispatch(&Node);
Manuel Klimek191c0932013-02-01 13:41:35 +0000459 }
460
Manuel Klimek9d041232012-11-30 13:45:19 +0000461 // Implements ASTMatchFinder::getASTContext.
Craig Topper2e5c11f2014-03-13 08:12:15 +0000462 ASTContext &getASTContext() const override { return *ActiveASTContext; }
Manuel Klimek9d041232012-11-30 13:45:19 +0000463
Manuel Klimek04616e42012-07-06 05:48:52 +0000464 bool shouldVisitTemplateInstantiations() const { return true; }
465 bool shouldVisitImplicitCode() const { return true; }
Daniel Jasper0f9f0192012-11-15 03:29:05 +0000466 // Disables data recursion. We intercept Traverse* methods in the RAV, which
467 // are not triggered during data recursion.
468 bool shouldUseDataRecursionFor(clang::Stmt *S) const { return false; }
Manuel Klimek04616e42012-07-06 05:48:52 +0000469
470private:
Samuel Benzaquen7ec2cb22014-09-05 20:15:31 +0000471 /// \brief Runs all the \p Matchers on \p Node.
472 ///
473 /// Used by \c matchDispatch() below.
474 template <typename T, typename MC>
475 void matchImpl(const T &Node, const MC &Matchers) {
476 for (const auto &MP : Matchers) {
477 BoundNodesTreeBuilder Builder;
478 if (MP.first.matches(Node, this, &Builder)) {
479 MatchVisitor Visitor(ActiveASTContext, MP.second);
480 Builder.visitMatches(&Visitor);
481 }
482 }
483 }
484
485 /// @{
486 /// \brief Overloads to pair the different node types to their matchers.
487 void matchDispatch(const Decl *Node) { matchImpl(*Node, Matchers->Decl); }
488 void matchDispatch(const Stmt *Node) { matchImpl(*Node, Matchers->Stmt); }
489 void matchDispatch(const Type *Node) {
490 matchImpl(QualType(Node, 0), Matchers->Type);
491 }
492 void matchDispatch(const TypeLoc *Node) {
493 matchImpl(*Node, Matchers->TypeLoc);
494 }
495 void matchDispatch(const QualType *Node) { matchImpl(*Node, Matchers->Type); }
496 void matchDispatch(const NestedNameSpecifier *Node) {
497 matchImpl(*Node, Matchers->NestedNameSpecifier);
498 }
499 void matchDispatch(const NestedNameSpecifierLoc *Node) {
500 matchImpl(*Node, Matchers->NestedNameSpecifierLoc);
501 }
502 void matchDispatch(const void *) { /* Do nothing. */ }
503 /// @}
504
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000505 // Returns whether an ancestor of \p Node matches \p Matcher.
506 //
507 // The order of matching ((which can lead to different nodes being bound in
508 // case there are multiple matches) is breadth first search.
509 //
510 // To allow memoization in the very common case of having deeply nested
511 // expressions inside a template function, we first walk up the AST, memoizing
512 // the result of the match along the way, as long as there is only a single
513 // parent.
514 //
515 // Once there are multiple parents, the breadth first search order does not
516 // allow simple memoization on the ancestors. Thus, we only memoize as long
517 // as there is a single parent.
518 bool memoizedMatchesAncestorOfRecursively(
Manuel Klimekc844a462012-12-06 14:42:48 +0000519 const ast_type_traits::DynTypedNode &Node, const DynTypedMatcher &Matcher,
520 BoundNodesTreeBuilder *Builder, AncestorMatchMode MatchMode) {
521 if (Node.get<TranslationUnitDecl>() ==
522 ActiveASTContext->getTranslationUnitDecl())
523 return false;
524 assert(Node.getMemoizationData() &&
525 "Invariant broken: only nodes that support memoization may be "
526 "used in the parent map.");
Manuel Klimekd4be4082013-02-28 13:21:39 +0000527 ASTContext::ParentVector Parents = ActiveASTContext->getParents(Node);
528 if (Parents.empty()) {
Manuel Klimekc844a462012-12-06 14:42:48 +0000529 assert(false && "Found node that is not in the parent map.");
530 return false;
531 }
Manuel Klimeka0c025f2013-06-19 15:42:45 +0000532 MatchKey Key;
533 Key.MatcherID = Matcher.getID();
534 Key.Node = Node;
535 Key.BoundNodes = *Builder;
Manuel Klimekc844a462012-12-06 14:42:48 +0000536
Manuel Klimek55d8fb52013-07-16 13:20:30 +0000537 // Note that we cannot use insert and reuse the iterator, as recursive
538 // calls to match might invalidate the result cache iterators.
539 MemoizationMap::iterator I = ResultCache.find(Key);
540 if (I != ResultCache.end()) {
541 *Builder = I->second.Nodes;
542 return I->second.ResultOfMatch;
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000543 }
Manuel Klimek55d8fb52013-07-16 13:20:30 +0000544 MemoizedMatchResult Result;
545 Result.ResultOfMatch = false;
546 Result.Nodes = *Builder;
547 if (Parents.size() == 1) {
548 // Only one parent - do recursive memoization.
549 const ast_type_traits::DynTypedNode Parent = Parents[0];
550 if (Matcher.matches(Parent, this, &Result.Nodes)) {
551 Result.ResultOfMatch = true;
552 } else if (MatchMode != ASTMatchFinder::AMM_ParentOnly) {
553 // Reset the results to not include the bound nodes from the failed
554 // match above.
555 Result.Nodes = *Builder;
556 Result.ResultOfMatch = memoizedMatchesAncestorOfRecursively(
557 Parent, Matcher, &Result.Nodes, MatchMode);
558 // Once we get back from the recursive call, the result will be the
559 // same as the parent's result.
560 }
561 } else {
562 // Multiple parents - BFS over the rest of the nodes.
563 llvm::DenseSet<const void *> Visited;
564 std::deque<ast_type_traits::DynTypedNode> Queue(Parents.begin(),
565 Parents.end());
566 while (!Queue.empty()) {
567 Result.Nodes = *Builder;
568 if (Matcher.matches(Queue.front(), this, &Result.Nodes)) {
569 Result.ResultOfMatch = true;
570 break;
571 }
572 if (MatchMode != ASTMatchFinder::AMM_ParentOnly) {
573 ASTContext::ParentVector Ancestors =
574 ActiveASTContext->getParents(Queue.front());
575 for (ASTContext::ParentVector::const_iterator I = Ancestors.begin(),
576 E = Ancestors.end();
577 I != E; ++I) {
578 // Make sure we do not visit the same node twice.
579 // Otherwise, we'll visit the common ancestors as often as there
580 // are splits on the way down.
581 if (Visited.insert(I->getMemoizationData()).second)
582 Queue.push_back(*I);
583 }
584 }
585 Queue.pop_front();
586 }
587 }
588 ResultCache[Key] = Result;
589
590 *Builder = Result.Nodes;
591 return Result.ResultOfMatch;
Manuel Klimekb64d6b72013-03-14 16:33:21 +0000592 }
Manuel Klimekc844a462012-12-06 14:42:48 +0000593
Manuel Klimek04616e42012-07-06 05:48:52 +0000594 // Implements a BoundNodesTree::Visitor that calls a MatchCallback with
595 // the aggregated bound nodes for each match.
Manuel Klimeka0c025f2013-06-19 15:42:45 +0000596 class MatchVisitor : public BoundNodesTreeBuilder::Visitor {
Manuel Klimek04616e42012-07-06 05:48:52 +0000597 public:
Daniel Jasper1dad1832012-07-10 20:20:19 +0000598 MatchVisitor(ASTContext* Context,
Manuel Klimek04616e42012-07-06 05:48:52 +0000599 MatchFinder::MatchCallback* Callback)
600 : Context(Context),
601 Callback(Callback) {}
602
Craig Topper2e5c11f2014-03-13 08:12:15 +0000603 void visitMatch(const BoundNodes& BoundNodesView) override {
Manuel Klimek04616e42012-07-06 05:48:52 +0000604 Callback->run(MatchFinder::MatchResult(BoundNodesView, Context));
605 }
606
607 private:
Daniel Jasper1dad1832012-07-10 20:20:19 +0000608 ASTContext* Context;
Manuel Klimek04616e42012-07-06 05:48:52 +0000609 MatchFinder::MatchCallback* Callback;
610 };
611
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000612 // Returns true if 'TypeNode' has an alias that matches the given matcher.
613 bool typeHasMatchingAlias(const Type *TypeNode,
614 const Matcher<NamedDecl> Matcher,
615 BoundNodesTreeBuilder *Builder) {
Daniel Jasper1dad1832012-07-10 20:20:19 +0000616 const Type *const CanonicalType =
Manuel Klimek04616e42012-07-06 05:48:52 +0000617 ActiveASTContext->getCanonicalType(TypeNode);
Manuel Klimek1863e502013-08-02 21:24:09 +0000618 const std::set<const TypedefNameDecl *> &Aliases =
619 TypeAliases[CanonicalType];
620 for (std::set<const TypedefNameDecl*>::const_iterator
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000621 It = Aliases.begin(), End = Aliases.end();
622 It != End; ++It) {
Manuel Klimeka0c025f2013-06-19 15:42:45 +0000623 BoundNodesTreeBuilder Result(*Builder);
624 if (Matcher.matches(**It, this, &Result)) {
625 *Builder = Result;
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000626 return true;
Manuel Klimeka0c025f2013-06-19 15:42:45 +0000627 }
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000628 }
629 return false;
Manuel Klimek04616e42012-07-06 05:48:52 +0000630 }
631
Samuel Benzaquen7ec2cb22014-09-05 20:15:31 +0000632 const MatchFinder::MatchersByType *Matchers;
Daniel Jasper1dad1832012-07-10 20:20:19 +0000633 ASTContext *ActiveASTContext;
Manuel Klimek04616e42012-07-06 05:48:52 +0000634
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000635 // Maps a canonical type to its TypedefDecls.
Manuel Klimek1863e502013-08-02 21:24:09 +0000636 llvm::DenseMap<const Type*, std::set<const TypedefNameDecl*> > TypeAliases;
Manuel Klimek04616e42012-07-06 05:48:52 +0000637
638 // Maps (matcher, node) -> the match result for memoization.
Manuel Klimeka0c025f2013-06-19 15:42:45 +0000639 typedef std::map<MatchKey, MemoizedMatchResult> MemoizationMap;
Manuel Klimek04616e42012-07-06 05:48:52 +0000640 MemoizationMap ResultCache;
641};
642
Manuel Klimek1863e502013-08-02 21:24:09 +0000643static CXXRecordDecl *getAsCXXRecordDecl(const Type *TypeNode) {
644 // Type::getAs<...>() drills through typedefs.
Craig Topper210e1ad2014-05-17 18:49:24 +0000645 if (TypeNode->getAs<DependentNameType>() != nullptr ||
646 TypeNode->getAs<DependentTemplateSpecializationType>() != nullptr ||
647 TypeNode->getAs<TemplateTypeParmType>() != nullptr)
Manuel Klimek1863e502013-08-02 21:24:09 +0000648 // Dependent names and template TypeNode parameters will be matched when
649 // the template is instantiated.
Craig Topper210e1ad2014-05-17 18:49:24 +0000650 return nullptr;
Manuel Klimek1863e502013-08-02 21:24:09 +0000651 TemplateSpecializationType const *TemplateType =
652 TypeNode->getAs<TemplateSpecializationType>();
Craig Topper210e1ad2014-05-17 18:49:24 +0000653 if (!TemplateType) {
Manuel Klimek1863e502013-08-02 21:24:09 +0000654 return TypeNode->getAsCXXRecordDecl();
655 }
656 if (TemplateType->getTemplateName().isDependent())
657 // Dependent template specializations will be matched when the
658 // template is instantiated.
Craig Topper210e1ad2014-05-17 18:49:24 +0000659 return nullptr;
Manuel Klimek1863e502013-08-02 21:24:09 +0000660
661 // For template specialization types which are specializing a template
662 // declaration which is an explicit or partial specialization of another
663 // template declaration, getAsCXXRecordDecl() returns the corresponding
664 // ClassTemplateSpecializationDecl.
665 //
666 // For template specialization types which are specializing a template
667 // declaration which is neither an explicit nor partial specialization of
668 // another template declaration, getAsCXXRecordDecl() returns NULL and
669 // we get the CXXRecordDecl of the templated declaration.
670 CXXRecordDecl *SpecializationDecl = TemplateType->getAsCXXRecordDecl();
Craig Topper210e1ad2014-05-17 18:49:24 +0000671 if (SpecializationDecl) {
Manuel Klimek1863e502013-08-02 21:24:09 +0000672 return SpecializationDecl;
673 }
674 NamedDecl *Templated =
675 TemplateType->getTemplateName().getAsTemplateDecl()->getTemplatedDecl();
676 if (CXXRecordDecl *TemplatedRecord = dyn_cast<CXXRecordDecl>(Templated)) {
677 return TemplatedRecord;
678 }
679 // Now it can still be that we have an alias template.
680 TypeAliasDecl *AliasDecl = dyn_cast<TypeAliasDecl>(Templated);
681 assert(AliasDecl);
682 return getAsCXXRecordDecl(AliasDecl->getUnderlyingType().getTypePtr());
683}
684
Manuel Klimek04616e42012-07-06 05:48:52 +0000685// Returns true if the given class is directly or indirectly derived
Daniel Jasperf49d1e02012-09-07 12:48:17 +0000686// from a base type with the given name. A class is not considered to be
687// derived from itself.
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000688bool MatchASTVisitor::classIsDerivedFrom(const CXXRecordDecl *Declaration,
689 const Matcher<NamedDecl> &Base,
690 BoundNodesTreeBuilder *Builder) {
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000691 if (!Declaration->hasDefinition())
Manuel Klimek04616e42012-07-06 05:48:52 +0000692 return false;
Aaron Ballman574705e2014-03-13 15:41:46 +0000693 for (const auto &It : Declaration->bases()) {
694 const Type *TypeNode = It.getType().getTypePtr();
Manuel Klimek04616e42012-07-06 05:48:52 +0000695
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000696 if (typeHasMatchingAlias(TypeNode, Base, Builder))
Manuel Klimek04616e42012-07-06 05:48:52 +0000697 return true;
698
Manuel Klimek1863e502013-08-02 21:24:09 +0000699 CXXRecordDecl *ClassDecl = getAsCXXRecordDecl(TypeNode);
Craig Topper210e1ad2014-05-17 18:49:24 +0000700 if (!ClassDecl)
Manuel Klimek04616e42012-07-06 05:48:52 +0000701 continue;
Manuel Klimek5472a522012-12-04 13:40:29 +0000702 if (ClassDecl == Declaration) {
703 // This can happen for recursive template definitions; if the
704 // current declaration did not match, we can safely return false.
Manuel Klimek5472a522012-12-04 13:40:29 +0000705 return false;
706 }
Manuel Klimeka0c025f2013-06-19 15:42:45 +0000707 BoundNodesTreeBuilder Result(*Builder);
708 if (Base.matches(*ClassDecl, this, &Result)) {
709 *Builder = Result;
Daniel Jasperf49d1e02012-09-07 12:48:17 +0000710 return true;
Manuel Klimeka0c025f2013-06-19 15:42:45 +0000711 }
Daniel Jasper2b3c7d42012-07-17 07:39:27 +0000712 if (classIsDerivedFrom(ClassDecl, Base, Builder))
Manuel Klimek04616e42012-07-06 05:48:52 +0000713 return true;
Manuel Klimek04616e42012-07-06 05:48:52 +0000714 }
715 return false;
716}
717
Daniel Jasper1dad1832012-07-10 20:20:19 +0000718bool MatchASTVisitor::TraverseDecl(Decl *DeclNode) {
Craig Topper210e1ad2014-05-17 18:49:24 +0000719 if (!DeclNode) {
Manuel Klimek04616e42012-07-06 05:48:52 +0000720 return true;
721 }
722 match(*DeclNode);
Daniel Jasper1dad1832012-07-10 20:20:19 +0000723 return RecursiveASTVisitor<MatchASTVisitor>::TraverseDecl(DeclNode);
Manuel Klimek04616e42012-07-06 05:48:52 +0000724}
725
Daniel Jasper1dad1832012-07-10 20:20:19 +0000726bool MatchASTVisitor::TraverseStmt(Stmt *StmtNode) {
Craig Topper210e1ad2014-05-17 18:49:24 +0000727 if (!StmtNode) {
Manuel Klimek04616e42012-07-06 05:48:52 +0000728 return true;
729 }
730 match(*StmtNode);
Daniel Jasper1dad1832012-07-10 20:20:19 +0000731 return RecursiveASTVisitor<MatchASTVisitor>::TraverseStmt(StmtNode);
Manuel Klimek04616e42012-07-06 05:48:52 +0000732}
733
Daniel Jasper1dad1832012-07-10 20:20:19 +0000734bool MatchASTVisitor::TraverseType(QualType TypeNode) {
Manuel Klimek04616e42012-07-06 05:48:52 +0000735 match(TypeNode);
Daniel Jasper1dad1832012-07-10 20:20:19 +0000736 return RecursiveASTVisitor<MatchASTVisitor>::TraverseType(TypeNode);
Manuel Klimek04616e42012-07-06 05:48:52 +0000737}
738
Daniel Jasper516b02e2012-10-17 08:52:59 +0000739bool MatchASTVisitor::TraverseTypeLoc(TypeLoc TypeLocNode) {
740 // The RecursiveASTVisitor only visits types if they're not within TypeLocs.
741 // We still want to find those types via matchers, so we match them here. Note
742 // that the TypeLocs are structurally a shadow-hierarchy to the expressed
743 // type, so we visit all involved parts of a compound type when matching on
744 // each TypeLoc.
745 match(TypeLocNode);
746 match(TypeLocNode.getType());
747 return RecursiveASTVisitor<MatchASTVisitor>::TraverseTypeLoc(TypeLocNode);
Manuel Klimek04616e42012-07-06 05:48:52 +0000748}
749
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000750bool MatchASTVisitor::TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
751 match(*NNS);
752 return RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifier(NNS);
753}
754
755bool MatchASTVisitor::TraverseNestedNameSpecifierLoc(
756 NestedNameSpecifierLoc NNS) {
757 match(NNS);
758 // We only match the nested name specifier here (as opposed to traversing it)
759 // because the traversal is already done in the parallel "Loc"-hierarchy.
Alexey Samsonovd07864a2014-08-28 22:18:42 +0000760 if (NNS.hasQualifier())
761 match(*NNS.getNestedNameSpecifier());
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000762 return
763 RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifierLoc(NNS);
764}
765
Daniel Jasper1dad1832012-07-10 20:20:19 +0000766class MatchASTConsumer : public ASTConsumer {
Manuel Klimek04616e42012-07-06 05:48:52 +0000767public:
Peter Collingbournea2334162013-11-07 22:30:36 +0000768 MatchASTConsumer(MatchFinder *Finder,
769 MatchFinder::ParsingDoneTestCallback *ParsingDone)
770 : Finder(Finder), ParsingDone(ParsingDone) {}
Manuel Klimek04616e42012-07-06 05:48:52 +0000771
772private:
Craig Topper2e5c11f2014-03-13 08:12:15 +0000773 void HandleTranslationUnit(ASTContext &Context) override {
Craig Topper210e1ad2014-05-17 18:49:24 +0000774 if (ParsingDone != nullptr) {
Manuel Klimek04616e42012-07-06 05:48:52 +0000775 ParsingDone->run();
776 }
Peter Collingbournea2334162013-11-07 22:30:36 +0000777 Finder->matchAST(Context);
Manuel Klimek04616e42012-07-06 05:48:52 +0000778 }
779
Peter Collingbournea2334162013-11-07 22:30:36 +0000780 MatchFinder *Finder;
Manuel Klimek04616e42012-07-06 05:48:52 +0000781 MatchFinder::ParsingDoneTestCallback *ParsingDone;
782};
783
784} // end namespace
785} // end namespace internal
786
787MatchFinder::MatchResult::MatchResult(const BoundNodes &Nodes,
Daniel Jasper1dad1832012-07-10 20:20:19 +0000788 ASTContext *Context)
Manuel Klimek04616e42012-07-06 05:48:52 +0000789 : Nodes(Nodes), Context(Context),
790 SourceManager(&Context->getSourceManager()) {}
791
792MatchFinder::MatchCallback::~MatchCallback() {}
793MatchFinder::ParsingDoneTestCallback::~ParsingDoneTestCallback() {}
794
Craig Topper210e1ad2014-05-17 18:49:24 +0000795MatchFinder::MatchFinder() : ParsingDone(nullptr) {}
Manuel Klimek04616e42012-07-06 05:48:52 +0000796
Samuel Benzaquenf34ac3e2013-10-29 14:37:15 +0000797MatchFinder::~MatchFinder() {}
Manuel Klimek04616e42012-07-06 05:48:52 +0000798
799void MatchFinder::addMatcher(const DeclarationMatcher &NodeMatch,
800 MatchCallback *Action) {
Samuel Benzaquen7ec2cb22014-09-05 20:15:31 +0000801 Matchers.Decl.push_back(std::make_pair(NodeMatch, Action));
802 Matchers.AllCallbacks.push_back(Action);
Manuel Klimek04616e42012-07-06 05:48:52 +0000803}
804
805void MatchFinder::addMatcher(const TypeMatcher &NodeMatch,
806 MatchCallback *Action) {
Samuel Benzaquen7ec2cb22014-09-05 20:15:31 +0000807 Matchers.Type.push_back(std::make_pair(NodeMatch, Action));
808 Matchers.AllCallbacks.push_back(Action);
Manuel Klimek04616e42012-07-06 05:48:52 +0000809}
810
811void MatchFinder::addMatcher(const StatementMatcher &NodeMatch,
812 MatchCallback *Action) {
Samuel Benzaquen7ec2cb22014-09-05 20:15:31 +0000813 Matchers.Stmt.push_back(std::make_pair(NodeMatch, Action));
814 Matchers.AllCallbacks.push_back(Action);
Manuel Klimek04616e42012-07-06 05:48:52 +0000815}
816
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000817void MatchFinder::addMatcher(const NestedNameSpecifierMatcher &NodeMatch,
818 MatchCallback *Action) {
Samuel Benzaquen7ec2cb22014-09-05 20:15:31 +0000819 Matchers.NestedNameSpecifier.push_back(std::make_pair(NodeMatch, Action));
820 Matchers.AllCallbacks.push_back(Action);
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000821}
822
823void MatchFinder::addMatcher(const NestedNameSpecifierLocMatcher &NodeMatch,
824 MatchCallback *Action) {
Samuel Benzaquen7ec2cb22014-09-05 20:15:31 +0000825 Matchers.NestedNameSpecifierLoc.push_back(std::make_pair(NodeMatch, Action));
826 Matchers.AllCallbacks.push_back(Action);
Daniel Jaspera6bc1f62012-09-13 13:11:25 +0000827}
828
Daniel Jasper516b02e2012-10-17 08:52:59 +0000829void MatchFinder::addMatcher(const TypeLocMatcher &NodeMatch,
830 MatchCallback *Action) {
Samuel Benzaquen7ec2cb22014-09-05 20:15:31 +0000831 Matchers.TypeLoc.push_back(std::make_pair(NodeMatch, Action));
832 Matchers.AllCallbacks.push_back(Action);
Daniel Jasper516b02e2012-10-17 08:52:59 +0000833}
834
Peter Collingbourne2b9471302013-11-07 22:30:32 +0000835bool MatchFinder::addDynamicMatcher(const internal::DynTypedMatcher &NodeMatch,
836 MatchCallback *Action) {
837 if (NodeMatch.canConvertTo<Decl>()) {
838 addMatcher(NodeMatch.convertTo<Decl>(), Action);
839 return true;
840 } else if (NodeMatch.canConvertTo<QualType>()) {
841 addMatcher(NodeMatch.convertTo<QualType>(), Action);
842 return true;
843 } else if (NodeMatch.canConvertTo<Stmt>()) {
844 addMatcher(NodeMatch.convertTo<Stmt>(), Action);
845 return true;
846 } else if (NodeMatch.canConvertTo<NestedNameSpecifier>()) {
847 addMatcher(NodeMatch.convertTo<NestedNameSpecifier>(), Action);
848 return true;
849 } else if (NodeMatch.canConvertTo<NestedNameSpecifierLoc>()) {
850 addMatcher(NodeMatch.convertTo<NestedNameSpecifierLoc>(), Action);
851 return true;
852 } else if (NodeMatch.canConvertTo<TypeLoc>()) {
853 addMatcher(NodeMatch.convertTo<TypeLoc>(), Action);
854 return true;
855 }
856 return false;
857}
858
David Blaikie6beb6aa2014-08-10 19:56:51 +0000859std::unique_ptr<ASTConsumer> MatchFinder::newASTConsumer() {
860 return llvm::make_unique<internal::MatchASTConsumer>(this, ParsingDone);
Manuel Klimek04616e42012-07-06 05:48:52 +0000861}
862
Manuel Klimek191c0932013-02-01 13:41:35 +0000863void MatchFinder::match(const clang::ast_type_traits::DynTypedNode &Node,
864 ASTContext &Context) {
Samuel Benzaquen7ec2cb22014-09-05 20:15:31 +0000865 internal::MatchASTVisitor Visitor(&Matchers);
Manuel Klimekc2687452012-10-24 14:47:44 +0000866 Visitor.set_active_ast_context(&Context);
Manuel Klimek191c0932013-02-01 13:41:35 +0000867 Visitor.match(Node);
Manuel Klimekc2687452012-10-24 14:47:44 +0000868}
869
Peter Collingbournea2334162013-11-07 22:30:36 +0000870void MatchFinder::matchAST(ASTContext &Context) {
Samuel Benzaquen7ec2cb22014-09-05 20:15:31 +0000871 internal::MatchASTVisitor Visitor(&Matchers);
Peter Collingbournea2334162013-11-07 22:30:36 +0000872 Visitor.set_active_ast_context(&Context);
873 Visitor.onStartOfTranslationUnit();
874 Visitor.TraverseDecl(Context.getTranslationUnitDecl());
875 Visitor.onEndOfTranslationUnit();
876}
877
Manuel Klimek04616e42012-07-06 05:48:52 +0000878void MatchFinder::registerTestCallbackAfterParsing(
879 MatchFinder::ParsingDoneTestCallback *NewParsingDone) {
880 ParsingDone = NewParsingDone;
881}
882
883} // end namespace ast_matchers
884} // end namespace clang