1 //===--- 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 <deque>
24 #include <set>
25 
26 namespace clang {
27 namespace ast_matchers {
28 namespace internal {
29 namespace {
30 
31 typedef MatchFinder::MatchCallback MatchCallback;
32 
33 // 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.
37 //
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.
44 typedef std::pair<uint64_t, const void*> UntypedMatchInput;
45 
46 // Used to store the result of a match and possibly bound nodes.
47 struct MemoizedMatchResult {
48   bool ResultOfMatch;
49   BoundNodesTree Nodes;
50 };
51 
52 // A RecursiveASTVisitor that traverses all children or all descendants of
53 // a node.
54 class MatchChildASTVisitor
55     : public RecursiveASTVisitor<MatchChildASTVisitor> {
56 public:
57   typedef RecursiveASTVisitor<MatchChildASTVisitor> VisitorBase;
58 
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.
63   MatchChildASTVisitor(const DynTypedMatcher *Matcher,
64                        ASTMatchFinder *Finder,
65                        BoundNodesTreeBuilder *Builder,
66                        int MaxDepth,
67                        ASTMatchFinder::TraversalKind Traversal,
68                        ASTMatchFinder::BindKind Bind)
69       : Matcher(Matcher),
70         Finder(Finder),
71         Builder(Builder),
72         CurrentDepth(0),
73         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.
89   bool findMatch(const ast_type_traits::DynTypedNode &DynNode) {
90     reset();
91     if (const Decl *D = DynNode.get<Decl>())
92       traverse(*D);
93     else if (const Stmt *S = DynNode.get<Stmt>())
94       traverse(*S);
95     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);
101     else if (const QualType *Q = DynNode.get<QualType>())
102       traverse(*Q);
103     else if (const TypeLoc *T = DynNode.get<TypeLoc>())
104       traverse(*T);
105     // FIXME: Add other base types after adding tests.
106     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.
112   bool TraverseDecl(Decl *DeclNode) {
113     ScopedIncrement ScopedDepth(&CurrentDepth);
114     return (DeclNode == NULL) || traverse(*DeclNode);
115   }
116   bool TraverseStmt(Stmt *StmtNode) {
117     ScopedIncrement ScopedDepth(&CurrentDepth);
118     const Stmt *StmtToTraverse = StmtNode;
119     if (Traversal ==
120         ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses) {
121       const Expr *ExprNode = dyn_cast_or_null<Expr>(StmtNode);
122       if (ExprNode != NULL) {
123         StmtToTraverse = ExprNode->IgnoreParenImpCasts();
124       }
125     }
126     return (StmtToTraverse == NULL) || traverse(*StmtToTraverse);
127   }
128   // We assume that the QualType and the contained type are on the same
129   // hierarchy level. Thus, we try to match either of them.
130   bool TraverseType(QualType TypeNode) {
131     if (TypeNode.isNull())
132       return true;
133     ScopedIncrement ScopedDepth(&CurrentDepth);
134     // Match the Type.
135     if (!match(*TypeNode))
136       return false;
137     // The QualType is matched inside traverse.
138     return traverse(TypeNode);
139   }
140   // 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) {
143     if (TypeLocNode.isNull())
144       return true;
145     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   }
155   bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
156     ScopedIncrement ScopedDepth(&CurrentDepth);
157     return (NNS == NULL) || traverse(*NNS);
158   }
159   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
160     if (!NNS)
161       return true;
162     ScopedIncrement ScopedDepth(&CurrentDepth);
163     if (!match(*NNS.getNestedNameSpecifier()))
164       return false;
165     return traverse(NNS);
166   }
167 
168   bool shouldVisitTemplateInstantiations() const { return true; }
169   bool shouldVisitImplicitCode() const { return true; }
170   // 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; }
173 
174 private:
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;
187     CurrentDepth = 0;
188   }
189 
190   // Forwards the call to the corresponding Traverse*() method in the
191   // base visitor class.
192   bool baseTraverse(const Decl &DeclNode) {
193     return VisitorBase::TraverseDecl(const_cast<Decl*>(&DeclNode));
194   }
195   bool baseTraverse(const Stmt &StmtNode) {
196     return VisitorBase::TraverseStmt(const_cast<Stmt*>(&StmtNode));
197   }
198   bool baseTraverse(QualType TypeNode) {
199     return VisitorBase::TraverseType(TypeNode);
200   }
201   bool baseTraverse(TypeLoc TypeLocNode) {
202     return VisitorBase::TraverseTypeLoc(TypeLocNode);
203   }
204   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   }
211 
212   // 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'.
217   template <typename T>
218   bool match(const T &Node) {
219     if (CurrentDepth == 0 || CurrentDepth > MaxDepth) {
220       return true;
221     }
222     if (Bind != ASTMatchFinder::BK_All) {
223       if (Matcher->matches(ast_type_traits::DynTypedNode::create(Node),
224                            Finder, Builder)) {
225         Matches = true;
226         return false;  // Abort as soon as a match is found.
227       }
228     } else {
229       BoundNodesTreeBuilder RecursiveBuilder;
230       if (Matcher->matches(ast_type_traits::DynTypedNode::create(Node),
231                            Finder, &RecursiveBuilder)) {
232         // After the first match the matcher succeeds.
233         Matches = true;
234         Builder->addMatch(RecursiveBuilder.build());
235       }
236     }
237     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);
249   }
250 
251   const DynTypedMatcher *const Matcher;
252   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.
263 class MatchASTVisitor : public RecursiveASTVisitor<MatchASTVisitor>,
264                         public ASTMatchFinder {
265 public:
266   MatchASTVisitor(std::vector<std::pair<const internal::DynTypedMatcher*,
267                                         MatchCallback*> > *MatcherCallbackPairs)
268      : MatcherCallbackPairs(MatcherCallbackPairs),
269        ActiveASTContext(NULL) {
270   }
271 
272   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 
281   void onEndOfTranslationUnit() {
282     for (std::vector<std::pair<const internal::DynTypedMatcher*,
283                                MatchCallback*> >::const_iterator
284              I = MatcherCallbackPairs->begin(), E = MatcherCallbackPairs->end();
285          I != E; ++I) {
286       I->second->onEndOfTranslationUnit();
287     }
288   }
289 
290   void set_active_ast_context(ASTContext *NewActiveASTContext) {
291     ActiveASTContext = NewActiveASTContext;
292   }
293 
294   // The following Visit*() and Traverse*() functions "override"
295   // methods in RecursiveASTVisitor.
296 
297   bool VisitTypedefDecl(TypedefDecl *DeclNode) {
298     // When we see 'typedef A B', we add name 'B' to the set of names
299     // A's canonical type maps to.  This is necessary for implementing
300     // isDerivedFrom(x) properly, where x can be the name of the base
301     // class or any of its aliases.
302     //
303     // In general, the is-alias-of (as defined by typedefs) relation
304     // is tree-shaped, as you can typedef a type more than once.  For
305     // example,
306     //
307     //   typedef A B;
308     //   typedef A C;
309     //   typedef C D;
310     //   typedef C E;
311     //
312     // gives you
313     //
314     //   A
315     //   |- B
316     //   `- C
317     //      |- D
318     //      `- E
319     //
320     // It is wrong to assume that the relation is a chain.  A correct
321     // implementation of isDerivedFrom() needs to recognize that B and
322     // E are aliases, even though neither is a typedef of the other.
323     // Therefore, we cannot simply walk through one typedef chain to
324     // find out whether the type name matches.
325     const Type *TypeNode = DeclNode->getUnderlyingType().getTypePtr();
326     const Type *CanonicalType =  // root of the typedef tree
327         ActiveASTContext->getCanonicalType(TypeNode);
328     TypeAliases[CanonicalType].insert(DeclNode);
329     return true;
330   }
331 
332   bool TraverseDecl(Decl *DeclNode);
333   bool TraverseStmt(Stmt *StmtNode);
334   bool TraverseType(QualType TypeNode);
335   bool TraverseTypeLoc(TypeLoc TypeNode);
336   bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS);
337   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
338 
339   // Matches children or descendants of 'Node' with 'BaseMatcher'.
340   bool memoizedMatchesRecursively(const ast_type_traits::DynTypedNode &Node,
341                                   const DynTypedMatcher &Matcher,
342                                   BoundNodesTreeBuilder *Builder, int MaxDepth,
343                                   TraversalKind Traversal, BindKind Bind) {
344     const UntypedMatchInput input(Matcher.getID(), Node.getMemoizationData());
345 
346     // For AST-nodes that don't have an identity, we can't memoize.
347     if (!input.second)
348       return matchesRecursively(Node, Matcher, Builder, MaxDepth, Traversal,
349                                 Bind);
350 
351     std::pair<MemoizationMap::iterator, bool> InsertResult
352       = ResultCache.insert(std::make_pair(input, MemoizedMatchResult()));
353     if (InsertResult.second) {
354       BoundNodesTreeBuilder DescendantBoundNodesBuilder;
355       InsertResult.first->second.ResultOfMatch =
356         matchesRecursively(Node, Matcher, &DescendantBoundNodesBuilder,
357                            MaxDepth, Traversal, Bind);
358       InsertResult.first->second.Nodes =
359         DescendantBoundNodesBuilder.build();
360     }
361     InsertResult.first->second.Nodes.copyTo(Builder);
362     return InsertResult.first->second.ResultOfMatch;
363   }
364 
365   // Matches children or descendants of 'Node' with 'BaseMatcher'.
366   bool matchesRecursively(const ast_type_traits::DynTypedNode &Node,
367                           const DynTypedMatcher &Matcher,
368                           BoundNodesTreeBuilder *Builder, int MaxDepth,
369                           TraversalKind Traversal, BindKind Bind) {
370     MatchChildASTVisitor Visitor(
371       &Matcher, this, Builder, MaxDepth, Traversal, Bind);
372     return Visitor.findMatch(Node);
373   }
374 
375   virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
376                                   const Matcher<NamedDecl> &Base,
377                                   BoundNodesTreeBuilder *Builder);
378 
379   // Implements ASTMatchFinder::matchesChildOf.
380   virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node,
381                               const DynTypedMatcher &Matcher,
382                               BoundNodesTreeBuilder *Builder,
383                               TraversalKind Traversal,
384                               BindKind Bind) {
385     return matchesRecursively(Node, Matcher, Builder, 1, Traversal,
386                               Bind);
387   }
388   // Implements ASTMatchFinder::matchesDescendantOf.
389   virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node,
390                                    const DynTypedMatcher &Matcher,
391                                    BoundNodesTreeBuilder *Builder,
392                                    BindKind Bind) {
393     return memoizedMatchesRecursively(Node, Matcher, Builder, INT_MAX,
394                                       TK_AsIs, Bind);
395   }
396   // Implements ASTMatchFinder::matchesAncestorOf.
397   virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node,
398                                  const DynTypedMatcher &Matcher,
399                                  BoundNodesTreeBuilder *Builder,
400                                  AncestorMatchMode MatchMode) {
401     return memoizedMatchesAncestorOfRecursively(Node, Matcher, Builder,
402                                                 MatchMode);
403   }
404 
405   // Matches all registered matchers on the given node and calls the
406   // result callback for every node that matches.
407   void match(const ast_type_traits::DynTypedNode& Node) {
408     for (std::vector<std::pair<const internal::DynTypedMatcher*,
409                                MatchCallback*> >::const_iterator
410              I = MatcherCallbackPairs->begin(), E = MatcherCallbackPairs->end();
411          I != E; ++I) {
412       BoundNodesTreeBuilder Builder;
413       if (I->first->matches(Node, this, &Builder)) {
414         BoundNodesTree BoundNodes = Builder.build();
415         MatchVisitor Visitor(ActiveASTContext, I->second);
416         BoundNodes.visitMatches(&Visitor);
417       }
418     }
419   }
420 
421   template <typename T> void match(const T &Node) {
422     match(ast_type_traits::DynTypedNode::create(Node));
423   }
424 
425   // Implements ASTMatchFinder::getASTContext.
426   virtual ASTContext &getASTContext() const { return *ActiveASTContext; }
427 
428   bool shouldVisitTemplateInstantiations() const { return true; }
429   bool shouldVisitImplicitCode() const { return true; }
430   // Disables data recursion. We intercept Traverse* methods in the RAV, which
431   // are not triggered during data recursion.
432   bool shouldUseDataRecursionFor(clang::Stmt *S) const { return false; }
433 
434 private:
435   // Returns whether an ancestor of \p Node matches \p Matcher.
436   //
437   // The order of matching ((which can lead to different nodes being bound in
438   // case there are multiple matches) is breadth first search.
439   //
440   // To allow memoization in the very common case of having deeply nested
441   // expressions inside a template function, we first walk up the AST, memoizing
442   // the result of the match along the way, as long as there is only a single
443   // parent.
444   //
445   // Once there are multiple parents, the breadth first search order does not
446   // allow simple memoization on the ancestors. Thus, we only memoize as long
447   // as there is a single parent.
448   bool memoizedMatchesAncestorOfRecursively(
449       const ast_type_traits::DynTypedNode &Node, const DynTypedMatcher &Matcher,
450       BoundNodesTreeBuilder *Builder, AncestorMatchMode MatchMode) {
451     if (Node.get<TranslationUnitDecl>() ==
452         ActiveASTContext->getTranslationUnitDecl())
453       return false;
454     assert(Node.getMemoizationData() &&
455            "Invariant broken: only nodes that support memoization may be "
456            "used in the parent map.");
457     ASTContext::ParentVector Parents = ActiveASTContext->getParents(Node);
458     if (Parents.empty()) {
459       assert(false && "Found node that is not in the parent map.");
460       return false;
461     }
462     const UntypedMatchInput input(Matcher.getID(), Node.getMemoizationData());
463     MemoizationMap::iterator I = ResultCache.find(input);
464     if (I == ResultCache.end()) {
465       BoundNodesTreeBuilder AncestorBoundNodesBuilder;
466       bool Matches = false;
467       if (Parents.size() == 1) {
468         // Only one parent - do recursive memoization.
469         const ast_type_traits::DynTypedNode Parent = Parents[0];
470         if (Matcher.matches(Parent, this, &AncestorBoundNodesBuilder)) {
471           Matches = true;
472         } else if (MatchMode != ASTMatchFinder::AMM_ParentOnly) {
473           Matches = memoizedMatchesAncestorOfRecursively(
474               Parent, Matcher, &AncestorBoundNodesBuilder, MatchMode);
475         }
476       } else {
477         // Multiple parents - BFS over the rest of the nodes.
478         llvm::DenseSet<const void *> Visited;
479         std::deque<ast_type_traits::DynTypedNode> Queue(Parents.begin(),
480                                                         Parents.end());
481         while (!Queue.empty()) {
482           if (Matcher.matches(Queue.front(), this,
483                               &AncestorBoundNodesBuilder)) {
484             Matches = true;
485             break;
486           }
487           if (MatchMode != ASTMatchFinder::AMM_ParentOnly) {
488             ASTContext::ParentVector Ancestors =
489                 ActiveASTContext->getParents(Queue.front());
490             for (ASTContext::ParentVector::const_iterator I = Ancestors.begin(),
491                                                           E = Ancestors.end();
492                  I != E; ++I) {
493               // Make sure we do not visit the same node twice.
494               // Otherwise, we'll visit the common ancestors as often as there
495               // are splits on the way down.
496               if (Visited.insert(I->getMemoizationData()).second)
497                 Queue.push_back(*I);
498             }
499           }
500           Queue.pop_front();
501         }
502       }
503 
504       I = ResultCache.insert(std::make_pair(input, MemoizedMatchResult()))
505           .first;
506       I->second.Nodes = AncestorBoundNodesBuilder.build();
507       I->second.ResultOfMatch = Matches;
508     }
509     I->second.Nodes.copyTo(Builder);
510     return I->second.ResultOfMatch;
511   }
512 
513   // Implements a BoundNodesTree::Visitor that calls a MatchCallback with
514   // the aggregated bound nodes for each match.
515   class MatchVisitor : public BoundNodesTree::Visitor {
516   public:
517     MatchVisitor(ASTContext* Context,
518                  MatchFinder::MatchCallback* Callback)
519       : Context(Context),
520         Callback(Callback) {}
521 
522     virtual void visitMatch(const BoundNodes& BoundNodesView) {
523       Callback->run(MatchFinder::MatchResult(BoundNodesView, Context));
524     }
525 
526   private:
527     ASTContext* Context;
528     MatchFinder::MatchCallback* Callback;
529   };
530 
531   // Returns true if 'TypeNode' has an alias that matches the given matcher.
532   bool typeHasMatchingAlias(const Type *TypeNode,
533                             const Matcher<NamedDecl> Matcher,
534                             BoundNodesTreeBuilder *Builder) {
535     const Type *const CanonicalType =
536       ActiveASTContext->getCanonicalType(TypeNode);
537     const std::set<const TypedefDecl*> &Aliases = TypeAliases[CanonicalType];
538     for (std::set<const TypedefDecl*>::const_iterator
539            It = Aliases.begin(), End = Aliases.end();
540          It != End; ++It) {
541       if (Matcher.matches(**It, this, Builder))
542         return true;
543     }
544     return false;
545   }
546 
547   std::vector<std::pair<const internal::DynTypedMatcher*,
548                         MatchCallback*> > *const MatcherCallbackPairs;
549   ASTContext *ActiveASTContext;
550 
551   // Maps a canonical type to its TypedefDecls.
552   llvm::DenseMap<const Type*, std::set<const TypedefDecl*> > TypeAliases;
553 
554   // Maps (matcher, node) -> the match result for memoization.
555   typedef llvm::DenseMap<UntypedMatchInput, MemoizedMatchResult> MemoizationMap;
556   MemoizationMap ResultCache;
557 };
558 
559 // Returns true if the given class is directly or indirectly derived
560 // from a base type with the given name.  A class is not considered to be
561 // derived from itself.
562 bool MatchASTVisitor::classIsDerivedFrom(const CXXRecordDecl *Declaration,
563                                          const Matcher<NamedDecl> &Base,
564                                          BoundNodesTreeBuilder *Builder) {
565   if (!Declaration->hasDefinition())
566     return false;
567   typedef CXXRecordDecl::base_class_const_iterator BaseIterator;
568   for (BaseIterator It = Declaration->bases_begin(),
569                     End = Declaration->bases_end(); It != End; ++It) {
570     const Type *TypeNode = It->getType().getTypePtr();
571 
572     if (typeHasMatchingAlias(TypeNode, Base, Builder))
573       return true;
574 
575     // Type::getAs<...>() drills through typedefs.
576     if (TypeNode->getAs<DependentNameType>() != NULL ||
577         TypeNode->getAs<DependentTemplateSpecializationType>() != NULL ||
578         TypeNode->getAs<TemplateTypeParmType>() != NULL)
579       // Dependent names and template TypeNode parameters will be matched when
580       // the template is instantiated.
581       continue;
582     CXXRecordDecl *ClassDecl = NULL;
583     TemplateSpecializationType const *TemplateType =
584       TypeNode->getAs<TemplateSpecializationType>();
585     if (TemplateType != NULL) {
586       if (TemplateType->getTemplateName().isDependent())
587         // Dependent template specializations will be matched when the
588         // template is instantiated.
589         continue;
590 
591       // For template specialization types which are specializing a template
592       // declaration which is an explicit or partial specialization of another
593       // template declaration, getAsCXXRecordDecl() returns the corresponding
594       // ClassTemplateSpecializationDecl.
595       //
596       // For template specialization types which are specializing a template
597       // declaration which is neither an explicit nor partial specialization of
598       // another template declaration, getAsCXXRecordDecl() returns NULL and
599       // we get the CXXRecordDecl of the templated declaration.
600       CXXRecordDecl *SpecializationDecl =
601         TemplateType->getAsCXXRecordDecl();
602       if (SpecializationDecl != NULL) {
603         ClassDecl = SpecializationDecl;
604       } else {
605         ClassDecl = dyn_cast<CXXRecordDecl>(
606             TemplateType->getTemplateName()
607                 .getAsTemplateDecl()->getTemplatedDecl());
608       }
609     } else {
610       ClassDecl = TypeNode->getAsCXXRecordDecl();
611     }
612     assert(ClassDecl != NULL);
613     if (ClassDecl == Declaration) {
614       // This can happen for recursive template definitions; if the
615       // current declaration did not match, we can safely return false.
616       assert(TemplateType);
617       return false;
618     }
619     if (Base.matches(*ClassDecl, this, Builder))
620       return true;
621     if (classIsDerivedFrom(ClassDecl, Base, Builder))
622       return true;
623   }
624   return false;
625 }
626 
627 bool MatchASTVisitor::TraverseDecl(Decl *DeclNode) {
628   if (DeclNode == NULL) {
629     return true;
630   }
631   match(*DeclNode);
632   return RecursiveASTVisitor<MatchASTVisitor>::TraverseDecl(DeclNode);
633 }
634 
635 bool MatchASTVisitor::TraverseStmt(Stmt *StmtNode) {
636   if (StmtNode == NULL) {
637     return true;
638   }
639   match(*StmtNode);
640   return RecursiveASTVisitor<MatchASTVisitor>::TraverseStmt(StmtNode);
641 }
642 
643 bool MatchASTVisitor::TraverseType(QualType TypeNode) {
644   match(TypeNode);
645   return RecursiveASTVisitor<MatchASTVisitor>::TraverseType(TypeNode);
646 }
647 
648 bool MatchASTVisitor::TraverseTypeLoc(TypeLoc TypeLocNode) {
649   // The RecursiveASTVisitor only visits types if they're not within TypeLocs.
650   // We still want to find those types via matchers, so we match them here. Note
651   // that the TypeLocs are structurally a shadow-hierarchy to the expressed
652   // type, so we visit all involved parts of a compound type when matching on
653   // each TypeLoc.
654   match(TypeLocNode);
655   match(TypeLocNode.getType());
656   return RecursiveASTVisitor<MatchASTVisitor>::TraverseTypeLoc(TypeLocNode);
657 }
658 
659 bool MatchASTVisitor::TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
660   match(*NNS);
661   return RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifier(NNS);
662 }
663 
664 bool MatchASTVisitor::TraverseNestedNameSpecifierLoc(
665     NestedNameSpecifierLoc NNS) {
666   match(NNS);
667   // We only match the nested name specifier here (as opposed to traversing it)
668   // because the traversal is already done in the parallel "Loc"-hierarchy.
669   match(*NNS.getNestedNameSpecifier());
670   return
671       RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifierLoc(NNS);
672 }
673 
674 class MatchASTConsumer : public ASTConsumer {
675 public:
676   MatchASTConsumer(
677     std::vector<std::pair<const internal::DynTypedMatcher*,
678                           MatchCallback*> > *MatcherCallbackPairs,
679     MatchFinder::ParsingDoneTestCallback *ParsingDone)
680     : Visitor(MatcherCallbackPairs),
681       ParsingDone(ParsingDone) {}
682 
683 private:
684   virtual void HandleTranslationUnit(ASTContext &Context) {
685     if (ParsingDone != NULL) {
686       ParsingDone->run();
687     }
688     Visitor.set_active_ast_context(&Context);
689     Visitor.onStartOfTranslationUnit();
690     Visitor.TraverseDecl(Context.getTranslationUnitDecl());
691     Visitor.onEndOfTranslationUnit();
692     Visitor.set_active_ast_context(NULL);
693   }
694 
695   MatchASTVisitor Visitor;
696   MatchFinder::ParsingDoneTestCallback *ParsingDone;
697 };
698 
699 } // end namespace
700 } // end namespace internal
701 
702 MatchFinder::MatchResult::MatchResult(const BoundNodes &Nodes,
703                                       ASTContext *Context)
704   : Nodes(Nodes), Context(Context),
705     SourceManager(&Context->getSourceManager()) {}
706 
707 MatchFinder::MatchCallback::~MatchCallback() {}
708 MatchFinder::ParsingDoneTestCallback::~ParsingDoneTestCallback() {}
709 
710 MatchFinder::MatchFinder() : ParsingDone(NULL) {}
711 
712 MatchFinder::~MatchFinder() {
713   for (std::vector<std::pair<const internal::DynTypedMatcher*,
714                              MatchCallback*> >::const_iterator
715            It = MatcherCallbackPairs.begin(), End = MatcherCallbackPairs.end();
716        It != End; ++It) {
717     delete It->first;
718   }
719 }
720 
721 void MatchFinder::addMatcher(const DeclarationMatcher &NodeMatch,
722                              MatchCallback *Action) {
723   MatcherCallbackPairs.push_back(std::make_pair(
724     new internal::Matcher<Decl>(NodeMatch), Action));
725 }
726 
727 void MatchFinder::addMatcher(const TypeMatcher &NodeMatch,
728                              MatchCallback *Action) {
729   MatcherCallbackPairs.push_back(std::make_pair(
730     new internal::Matcher<QualType>(NodeMatch), Action));
731 }
732 
733 void MatchFinder::addMatcher(const StatementMatcher &NodeMatch,
734                              MatchCallback *Action) {
735   MatcherCallbackPairs.push_back(std::make_pair(
736     new internal::Matcher<Stmt>(NodeMatch), Action));
737 }
738 
739 void MatchFinder::addMatcher(const NestedNameSpecifierMatcher &NodeMatch,
740                              MatchCallback *Action) {
741   MatcherCallbackPairs.push_back(std::make_pair(
742     new NestedNameSpecifierMatcher(NodeMatch), Action));
743 }
744 
745 void MatchFinder::addMatcher(const NestedNameSpecifierLocMatcher &NodeMatch,
746                              MatchCallback *Action) {
747   MatcherCallbackPairs.push_back(std::make_pair(
748     new NestedNameSpecifierLocMatcher(NodeMatch), Action));
749 }
750 
751 void MatchFinder::addMatcher(const TypeLocMatcher &NodeMatch,
752                              MatchCallback *Action) {
753   MatcherCallbackPairs.push_back(std::make_pair(
754     new TypeLocMatcher(NodeMatch), Action));
755 }
756 
757 bool MatchFinder::addDynamicMatcher(const internal::DynTypedMatcher &NodeMatch,
758                                     MatchCallback *Action) {
759   MatcherCallbackPairs.push_back(std::make_pair(NodeMatch.clone(), Action));
760   // TODO: Do runtime type checking to make sure the matcher is one of the valid
761   // top-level matchers.
762   return true;
763 }
764 
765 ASTConsumer *MatchFinder::newASTConsumer() {
766   return new internal::MatchASTConsumer(&MatcherCallbackPairs, ParsingDone);
767 }
768 
769 void MatchFinder::match(const clang::ast_type_traits::DynTypedNode &Node,
770                         ASTContext &Context) {
771   internal::MatchASTVisitor Visitor(&MatcherCallbackPairs);
772   Visitor.set_active_ast_context(&Context);
773   Visitor.match(Node);
774 }
775 
776 void MatchFinder::registerTestCallbackAfterParsing(
777     MatchFinder::ParsingDoneTestCallback *NewParsingDone) {
778   ParsingDone = NewParsingDone;
779 }
780 
781 } // end namespace ast_matchers
782 } // end namespace clang
783