]> CyberLeo.Net >> Repos - FreeBSD/releng/9.2.git/blob - contrib/llvm/tools/clang/include/clang/ASTMatchers/ASTMatchersInternal.h
- Copy stable/9 to releng/9.2 as part of the 9.2-RELEASE cycle.
[FreeBSD/releng/9.2.git] / contrib / llvm / tools / clang / include / clang / ASTMatchers / ASTMatchersInternal.h
1 //===--- ASTMatchersInternal.h - Structural query framework -----*- C++ -*-===//
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 the base layer of the matcher framework.
11 //
12 //  Matchers are methods that return a Matcher<T> which provides a method
13 //  Matches(...) which is a predicate on an AST node. The Matches method's
14 //  parameters define the context of the match, which allows matchers to recurse
15 //  or store the current node as bound to a specific string, so that it can be
16 //  retrieved later.
17 //
18 //  In general, matchers have two parts:
19 //  1. A function Matcher<T> MatcherName(<arguments>) which returns a Matcher<T>
20 //     based on the arguments and optionally on template type deduction based
21 //     on the arguments. Matcher<T>s form an implicit reverse hierarchy
22 //     to clang's AST class hierarchy, meaning that you can use a Matcher<Base>
23 //     everywhere a Matcher<Derived> is required.
24 //  2. An implementation of a class derived from MatcherInterface<T>.
25 //
26 //  The matcher functions are defined in ASTMatchers.h. To make it possible
27 //  to implement both the matcher function and the implementation of the matcher
28 //  interface in one place, ASTMatcherMacros.h defines macros that allow
29 //  implementing a matcher in a single place.
30 //
31 //  This file contains the base classes needed to construct the actual matchers.
32 //
33 //===----------------------------------------------------------------------===//
34
35 #ifndef LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H
36 #define LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H
37
38 #include "clang/AST/ASTTypeTraits.h"
39 #include "clang/AST/DeclCXX.h"
40 #include "clang/AST/Decl.h"
41 #include "clang/AST/ExprCXX.h"
42 #include "clang/AST/StmtCXX.h"
43 #include "clang/AST/Stmt.h"
44 #include "clang/AST/Type.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/type_traits.h"
47 #include <map>
48 #include <string>
49 #include <vector>
50
51 namespace clang {
52 namespace ast_matchers {
53
54 /// FIXME: Move into the llvm support library.
55 template <bool> struct CompileAssert {};
56 #define TOOLING_COMPILE_ASSERT(Expr, Msg) \
57   typedef CompileAssert<(bool(Expr))> Msg[bool(Expr) ? 1 : -1]
58
59 class BoundNodes;
60
61 namespace internal {
62
63 class BoundNodesTreeBuilder;
64 /// \brief Internal version of BoundNodes. Holds all the bound nodes.
65 class BoundNodesMap {
66 public:
67   /// \brief Adds \c Node to the map with key \c ID.
68   ///
69   /// The node's base type should be in NodeBaseType or it will be unaccessible.
70   template <typename T>
71   void addNode(StringRef ID, const T* Node) {
72     NodeMap[ID] = ast_type_traits::DynTypedNode::create(*Node);
73   }
74   void addNode(StringRef ID, ast_type_traits::DynTypedNode Node) {
75     NodeMap[ID] = Node;
76   }
77
78   /// \brief Returns the AST node bound to \c ID.
79   ///
80   /// Returns NULL if there was no node bound to \c ID or if there is a node but
81   /// it cannot be converted to the specified type.
82   template <typename T>
83   const T *getNodeAs(StringRef ID) const {
84     IDToNodeMap::const_iterator It = NodeMap.find(ID);
85     if (It == NodeMap.end()) {
86       return NULL;
87     }
88     return It->second.get<T>();
89   }
90
91   /// \brief Copies all ID/Node pairs to BoundNodesTreeBuilder \c Builder.
92   void copyTo(BoundNodesTreeBuilder *Builder) const;
93
94   /// \brief Copies all ID/Node pairs to BoundNodesMap \c Other.
95   void copyTo(BoundNodesMap *Other) const;
96
97 private:
98   /// \brief A map from IDs to the bound nodes.
99   typedef std::map<std::string, ast_type_traits::DynTypedNode> IDToNodeMap;
100
101   IDToNodeMap NodeMap;
102 };
103
104 /// \brief A tree of bound nodes in match results.
105 ///
106 /// If a match can contain multiple matches on the same node with different
107 /// matching subexpressions, BoundNodesTree contains a branch for each of
108 /// those matching subexpressions.
109 ///
110 /// BoundNodesTree's are created during the matching process; when a match
111 /// is found, we iterate over the tree and create a BoundNodes object containing
112 /// the union of all bound nodes on the path from the root to a each leaf.
113 class BoundNodesTree {
114 public:
115   /// \brief A visitor interface to visit all BoundNodes results for a
116   /// BoundNodesTree.
117   class Visitor {
118   public:
119     virtual ~Visitor() {}
120
121     /// \brief Called multiple times during a single call to VisitMatches(...).
122     ///
123     /// 'BoundNodesView' contains the bound nodes for a single match.
124     virtual void visitMatch(const BoundNodes& BoundNodesView) = 0;
125   };
126
127   BoundNodesTree();
128
129   /// \brief Create a BoundNodesTree from pre-filled maps of bindings.
130   BoundNodesTree(const BoundNodesMap& Bindings,
131                  const std::vector<BoundNodesTree> RecursiveBindings);
132
133   /// \brief Adds all bound nodes to \c Builder.
134   void copyTo(BoundNodesTreeBuilder* Builder) const;
135
136   /// \brief Visits all matches that this BoundNodesTree represents.
137   ///
138   /// The ownership of 'ResultVisitor' remains at the caller.
139   void visitMatches(Visitor* ResultVisitor);
140
141 private:
142   void visitMatchesRecursively(
143       Visitor* ResultVistior,
144       const BoundNodesMap& AggregatedBindings);
145
146   // FIXME: Find out whether we want to use different data structures here -
147   // first benchmarks indicate that it doesn't matter though.
148
149   BoundNodesMap Bindings;
150
151   std::vector<BoundNodesTree> RecursiveBindings;
152 };
153
154 /// \brief Creates BoundNodesTree objects.
155 ///
156 /// The tree builder is used during the matching process to insert the bound
157 /// nodes from the Id matcher.
158 class BoundNodesTreeBuilder {
159 public:
160   BoundNodesTreeBuilder();
161
162   /// \brief Add a binding from an id to a node.
163   template <typename T>
164   void setBinding(const std::string &Id, const T *Node) {
165     Bindings.addNode(Id, Node);
166   }
167   void setBinding(const std::string &Id, ast_type_traits::DynTypedNode Node) {
168     Bindings.addNode(Id, Node);
169   }
170
171   /// \brief Adds a branch in the tree.
172   void addMatch(const BoundNodesTree& Bindings);
173
174   /// \brief Returns a BoundNodes object containing all current bindings.
175   BoundNodesTree build() const;
176
177 private:
178   BoundNodesTreeBuilder(const BoundNodesTreeBuilder &) LLVM_DELETED_FUNCTION;
179   void operator=(const BoundNodesTreeBuilder &) LLVM_DELETED_FUNCTION;
180
181   BoundNodesMap Bindings;
182
183   std::vector<BoundNodesTree> RecursiveBindings;
184 };
185
186 class ASTMatchFinder;
187
188 /// \brief Generic interface for matchers on an AST node of type T.
189 ///
190 /// Implement this if your matcher may need to inspect the children or
191 /// descendants of the node or bind matched nodes to names. If you are
192 /// writing a simple matcher that only inspects properties of the
193 /// current node and doesn't care about its children or descendants,
194 /// implement SingleNodeMatcherInterface instead.
195 template <typename T>
196 class MatcherInterface : public RefCountedBaseVPTR {
197 public:
198   virtual ~MatcherInterface() {}
199
200   /// \brief Returns true if 'Node' can be matched.
201   ///
202   /// May bind 'Node' to an ID via 'Builder', or recurse into
203   /// the AST via 'Finder'.
204   virtual bool matches(const T &Node,
205                        ASTMatchFinder *Finder,
206                        BoundNodesTreeBuilder *Builder) const = 0;
207 };
208
209 /// \brief Interface for matchers that only evaluate properties on a single
210 /// node.
211 template <typename T>
212 class SingleNodeMatcherInterface : public MatcherInterface<T> {
213 public:
214   /// \brief Returns true if the matcher matches the provided node.
215   ///
216   /// A subclass must implement this instead of Matches().
217   virtual bool matchesNode(const T &Node) const = 0;
218
219 private:
220   /// Implements MatcherInterface::Matches.
221   virtual bool matches(const T &Node,
222                        ASTMatchFinder * /* Finder */,
223                        BoundNodesTreeBuilder * /*  Builder */) const {
224     return matchesNode(Node);
225   }
226 };
227
228 /// \brief Base class for all matchers that works on a \c DynTypedNode.
229 ///
230 /// Matcher implementations will check whether the \c DynTypedNode is
231 /// convertible into the respecitve types and then do the actual match
232 /// on the actual node, or return false if it is not convertible.
233 class DynTypedMatcher {
234 public:
235   virtual ~DynTypedMatcher() {}
236
237   /// \brief Returns true if the matcher matches the given \c DynNode.
238   virtual bool matches(const ast_type_traits::DynTypedNode DynNode,
239                        ASTMatchFinder *Finder,
240                        BoundNodesTreeBuilder *Builder) const = 0;
241
242   /// \brief Returns a unique ID for the matcher.
243   virtual uint64_t getID() const = 0;
244 };
245
246 /// \brief Wrapper of a MatcherInterface<T> *that allows copying.
247 ///
248 /// A Matcher<Base> can be used anywhere a Matcher<Derived> is
249 /// required. This establishes an is-a relationship which is reverse
250 /// to the AST hierarchy. In other words, Matcher<T> is contravariant
251 /// with respect to T. The relationship is built via a type conversion
252 /// operator rather than a type hierarchy to be able to templatize the
253 /// type hierarchy instead of spelling it out.
254 template <typename T>
255 class Matcher : public DynTypedMatcher {
256 public:
257   /// \brief Takes ownership of the provided implementation pointer.
258   explicit Matcher(MatcherInterface<T> *Implementation)
259       : Implementation(Implementation) {}
260
261   /// \brief Implicitly converts \c Other to a Matcher<T>.
262   ///
263   /// Requires \c T to be derived from \c From.
264   template <typename From>
265   Matcher(const Matcher<From> &Other,
266           typename llvm::enable_if_c<
267             llvm::is_base_of<From, T>::value &&
268             !llvm::is_same<From, T>::value >::type* = 0)
269       : Implementation(new ImplicitCastMatcher<From>(Other)) {}
270
271   /// \brief Implicitly converts \c Matcher<Type> to \c Matcher<QualType>.
272   ///
273   /// The resulting matcher is not strict, i.e. ignores qualifiers.
274   template <typename TypeT>
275   Matcher(const Matcher<TypeT> &Other,
276           typename llvm::enable_if_c<
277             llvm::is_same<T, QualType>::value &&
278             llvm::is_same<TypeT, Type>::value >::type* = 0)
279       : Implementation(new TypeToQualType<TypeT>(Other)) {}
280
281   /// \brief Forwards the call to the underlying MatcherInterface<T> pointer.
282   bool matches(const T &Node,
283                ASTMatchFinder *Finder,
284                BoundNodesTreeBuilder *Builder) const {
285     return Implementation->matches(Node, Finder, Builder);
286   }
287
288   /// \brief Returns an ID that uniquely identifies the matcher.
289   uint64_t getID() const {
290     /// FIXME: Document the requirements this imposes on matcher
291     /// implementations (no new() implementation_ during a Matches()).
292     return reinterpret_cast<uint64_t>(Implementation.getPtr());
293   }
294
295   /// \brief Returns whether the matcher matches on the given \c DynNode.
296   virtual bool matches(const ast_type_traits::DynTypedNode DynNode,
297                        ASTMatchFinder *Finder,
298                        BoundNodesTreeBuilder *Builder) const {
299     const T *Node = DynNode.get<T>();
300     if (!Node) return false;
301     return matches(*Node, Finder, Builder);
302   }
303
304   /// \brief Allows the conversion of a \c Matcher<Type> to a \c
305   /// Matcher<QualType>.
306   ///
307   /// Depending on the constructor argument, the matcher is either strict, i.e.
308   /// does only matches in the absence of qualifiers, or not, i.e. simply
309   /// ignores any qualifiers.
310   template <typename TypeT>
311   class TypeToQualType : public MatcherInterface<QualType> {
312    public:
313     TypeToQualType(const Matcher<TypeT> &InnerMatcher)
314         : InnerMatcher(InnerMatcher) {}
315
316     virtual bool matches(const QualType &Node,
317                          ASTMatchFinder *Finder,
318                          BoundNodesTreeBuilder *Builder) const {
319       if (Node.isNull())
320         return false;
321       return InnerMatcher.matches(*Node, Finder, Builder);
322     }
323    private:
324     const Matcher<TypeT> InnerMatcher;
325   };
326
327 private:
328   /// \brief Allows conversion from Matcher<Base> to Matcher<T> if T
329   /// is derived from Base.
330   template <typename Base>
331   class ImplicitCastMatcher : public MatcherInterface<T> {
332   public:
333     explicit ImplicitCastMatcher(const Matcher<Base> &From)
334         : From(From) {}
335
336     virtual bool matches(const T &Node,
337                          ASTMatchFinder *Finder,
338                          BoundNodesTreeBuilder *Builder) const {
339       return From.matches(Node, Finder, Builder);
340     }
341
342   private:
343     const Matcher<Base> From;
344   };
345
346   IntrusiveRefCntPtr< MatcherInterface<T> > Implementation;
347 };  // class Matcher
348
349 /// \brief A convenient helper for creating a Matcher<T> without specifying
350 /// the template type argument.
351 template <typename T>
352 inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) {
353   return Matcher<T>(Implementation);
354 }
355
356 /// \brief Metafunction to determine if type T has a member called getDecl.
357 template <typename T> struct has_getDecl {
358   struct Default { int getDecl; };
359   struct Derived : T, Default { };
360
361   template<typename C, C> struct CheckT;
362
363   // If T::getDecl exists, an ambiguity arises and CheckT will
364   // not be instantiable. This makes f(...) the only available
365   // overload.
366   template<typename C>
367   static char (&f(CheckT<int Default::*, &C::getDecl>*))[1];
368   template<typename C> static char (&f(...))[2];
369
370   static bool const value = sizeof(f<Derived>(0)) == 2;
371 };
372
373 /// \brief Matches overloaded operators with a specific name.
374 ///
375 /// The type argument ArgT is not used by this matcher but is used by
376 /// PolymorphicMatcherWithParam1 and should be StringRef.
377 template <typename T, typename ArgT>
378 class HasOverloadedOperatorNameMatcher : public SingleNodeMatcherInterface<T> {
379   TOOLING_COMPILE_ASSERT((llvm::is_same<T, CXXOperatorCallExpr>::value ||
380                           llvm::is_same<T, CXXMethodDecl>::value),
381                          unsupported_class_for_matcher);
382   TOOLING_COMPILE_ASSERT((llvm::is_same<ArgT, StringRef>::value),
383                          argument_type_must_be_StringRef);
384 public:
385   explicit HasOverloadedOperatorNameMatcher(const StringRef Name)
386       : SingleNodeMatcherInterface<T>(), Name(Name) {}
387
388   virtual bool matchesNode(const T &Node) const LLVM_OVERRIDE {
389     return matchesSpecialized(Node);
390   }
391
392 private:
393
394   /// \brief CXXOperatorCallExpr exist only for calls to overloaded operators
395   /// so this function returns true if the call is to an operator of the given
396   /// name.
397   bool matchesSpecialized(const CXXOperatorCallExpr &Node) const {
398     return getOperatorSpelling(Node.getOperator()) == Name;
399   }
400
401   /// \brief Returns true only if CXXMethodDecl represents an overloaded
402   /// operator and has the given operator name.
403   bool matchesSpecialized(const CXXMethodDecl &Node) const {
404     return Node.isOverloadedOperator() &&
405            getOperatorSpelling(Node.getOverloadedOperator()) == Name;
406   }
407
408   std::string Name;
409 };
410
411 /// \brief Matches declarations for QualType and CallExpr.
412 ///
413 /// Type argument DeclMatcherT is required by PolymorphicMatcherWithParam1 but
414 /// not actually used.
415 template <typename T, typename DeclMatcherT>
416 class HasDeclarationMatcher : public MatcherInterface<T> {
417   TOOLING_COMPILE_ASSERT((llvm::is_same< DeclMatcherT,
418                                          Matcher<Decl> >::value),
419                           instantiated_with_wrong_types);
420 public:
421   explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher)
422       : InnerMatcher(InnerMatcher) {}
423
424   virtual bool matches(const T &Node,
425                        ASTMatchFinder *Finder,
426                        BoundNodesTreeBuilder *Builder) const {
427     return matchesSpecialized(Node, Finder, Builder);
428   }
429
430 private:
431   /// \brief If getDecl exists as a member of U, returns whether the inner
432   /// matcher matches Node.getDecl().
433   template <typename U>
434   bool matchesSpecialized(
435       const U &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder,
436       typename llvm::enable_if<has_getDecl<U>, int>::type = 0) const {
437     return matchesDecl(Node.getDecl(), Finder, Builder);
438   }
439
440   /// \brief Extracts the CXXRecordDecl or EnumDecl of a QualType and returns
441   /// whether the inner matcher matches on it.
442   bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder,
443                           BoundNodesTreeBuilder *Builder) const {
444     /// FIXME: Add other ways to convert...
445     if (Node.isNull())
446       return false;
447     if (const EnumType *AsEnum = dyn_cast<EnumType>(Node.getTypePtr()))
448       return matchesDecl(AsEnum->getDecl(), Finder, Builder);
449     return matchesDecl(Node->getAsCXXRecordDecl(), Finder, Builder);
450   }
451
452   /// \brief Gets the TemplateDecl from a TemplateSpecializationType
453   /// and returns whether the inner matches on it.
454   bool matchesSpecialized(const TemplateSpecializationType &Node,
455                           ASTMatchFinder *Finder,
456                           BoundNodesTreeBuilder *Builder) const {
457     return matchesDecl(Node.getTemplateName().getAsTemplateDecl(),
458                        Finder, Builder);
459   }
460
461   /// \brief Extracts the Decl of the callee of a CallExpr and returns whether
462   /// the inner matcher matches on it.
463   bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder,
464                           BoundNodesTreeBuilder *Builder) const {
465     return matchesDecl(Node.getCalleeDecl(), Finder, Builder);
466   }
467
468   /// \brief Extracts the Decl of the constructor call and returns whether the
469   /// inner matcher matches on it.
470   bool matchesSpecialized(const CXXConstructExpr &Node,
471                           ASTMatchFinder *Finder,
472                           BoundNodesTreeBuilder *Builder) const {
473     return matchesDecl(Node.getConstructor(), Finder, Builder);
474   }
475
476   /// \brief Extracts the \c ValueDecl a \c MemberExpr refers to and returns
477   /// whether the inner matcher matches on it.
478   bool matchesSpecialized(const MemberExpr &Node,
479                           ASTMatchFinder *Finder,
480                           BoundNodesTreeBuilder *Builder) const {
481     return matchesDecl(Node.getMemberDecl(), Finder, Builder);
482   }
483
484   /// \brief Returns whether the inner matcher \c Node. Returns false if \c Node
485   /// is \c NULL.
486   bool matchesDecl(const Decl *Node,
487                    ASTMatchFinder *Finder,
488                    BoundNodesTreeBuilder *Builder) const {
489     return Node != NULL && InnerMatcher.matches(*Node, Finder, Builder);
490   }
491
492   const Matcher<Decl> InnerMatcher;
493 };
494
495 /// \brief IsBaseType<T>::value is true if T is a "base" type in the AST
496 /// node class hierarchies.
497 template <typename T>
498 struct IsBaseType {
499   static const bool value =
500       (llvm::is_same<T, Decl>::value ||
501        llvm::is_same<T, Stmt>::value ||
502        llvm::is_same<T, QualType>::value ||
503        llvm::is_same<T, Type>::value ||
504        llvm::is_same<T, TypeLoc>::value ||
505        llvm::is_same<T, NestedNameSpecifier>::value ||
506        llvm::is_same<T, NestedNameSpecifierLoc>::value ||
507        llvm::is_same<T, CXXCtorInitializer>::value);
508 };
509 template <typename T>
510 const bool IsBaseType<T>::value;
511
512 /// \brief Interface that allows matchers to traverse the AST.
513 /// FIXME: Find a better name.
514 ///
515 /// This provides three entry methods for each base node type in the AST:
516 /// - \c matchesChildOf:
517 ///   Matches a matcher on every child node of the given node. Returns true
518 ///   if at least one child node could be matched.
519 /// - \c matchesDescendantOf:
520 ///   Matches a matcher on all descendant nodes of the given node. Returns true
521 ///   if at least one descendant matched.
522 /// - \c matchesAncestorOf:
523 ///   Matches a matcher on all ancestors of the given node. Returns true if
524 ///   at least one ancestor matched.
525 ///
526 /// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal.
527 /// In the future, we wan to implement this for all nodes for which it makes
528 /// sense. In the case of matchesAncestorOf, we'll want to implement it for
529 /// all nodes, as all nodes have ancestors.
530 class ASTMatchFinder {
531 public:
532   /// \brief Defines how we descend a level in the AST when we pass
533   /// through expressions.
534   enum TraversalKind {
535     /// Will traverse any child nodes.
536     TK_AsIs,
537     /// Will not traverse implicit casts and parentheses.
538     TK_IgnoreImplicitCastsAndParentheses
539   };
540
541   /// \brief Defines how bindings are processed on recursive matches.
542   enum BindKind {
543     /// Stop at the first match and only bind the first match.
544     BK_First,
545     /// Create results for all combinations of bindings that match.
546     BK_All
547   };
548
549   /// \brief Defines which ancestors are considered for a match.
550   enum AncestorMatchMode {
551     /// All ancestors.
552     AMM_All,
553     /// Direct parent only.
554     AMM_ParentOnly
555   };
556
557   virtual ~ASTMatchFinder() {}
558
559   /// \brief Returns true if the given class is directly or indirectly derived
560   /// from a base type matching \c base.
561   ///
562   /// A class is considered to be also derived from itself.
563   virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
564                                   const Matcher<NamedDecl> &Base,
565                                   BoundNodesTreeBuilder *Builder) = 0;
566
567   template <typename T>
568   bool matchesChildOf(const T &Node,
569                       const DynTypedMatcher &Matcher,
570                       BoundNodesTreeBuilder *Builder,
571                       TraversalKind Traverse,
572                       BindKind Bind) {
573     TOOLING_COMPILE_ASSERT(
574         (llvm::is_base_of<Decl, T>::value ||
575          llvm::is_base_of<Stmt, T>::value ||
576          llvm::is_base_of<NestedNameSpecifier, T>::value ||
577          llvm::is_base_of<NestedNameSpecifierLoc, T>::value ||
578          llvm::is_base_of<TypeLoc, T>::value ||
579          llvm::is_base_of<QualType, T>::value),
580         unsupported_type_for_recursive_matching);
581    return matchesChildOf(ast_type_traits::DynTypedNode::create(Node),
582                           Matcher, Builder, Traverse, Bind);
583   }
584
585   template <typename T>
586   bool matchesDescendantOf(const T &Node,
587                            const DynTypedMatcher &Matcher,
588                            BoundNodesTreeBuilder *Builder,
589                            BindKind Bind) {
590     TOOLING_COMPILE_ASSERT(
591         (llvm::is_base_of<Decl, T>::value ||
592          llvm::is_base_of<Stmt, T>::value ||
593          llvm::is_base_of<NestedNameSpecifier, T>::value ||
594          llvm::is_base_of<NestedNameSpecifierLoc, T>::value ||
595          llvm::is_base_of<TypeLoc, T>::value ||
596          llvm::is_base_of<QualType, T>::value),
597         unsupported_type_for_recursive_matching);
598     return matchesDescendantOf(ast_type_traits::DynTypedNode::create(Node),
599                                Matcher, Builder, Bind);
600   }
601
602   // FIXME: Implement support for BindKind.
603   template <typename T>
604   bool matchesAncestorOf(const T &Node,
605                          const DynTypedMatcher &Matcher,
606                          BoundNodesTreeBuilder *Builder,
607                          AncestorMatchMode MatchMode) {
608     TOOLING_COMPILE_ASSERT((llvm::is_base_of<Decl, T>::value ||
609                             llvm::is_base_of<Stmt, T>::value),
610                            only_Decl_or_Stmt_allowed_for_recursive_matching);
611     return matchesAncestorOf(ast_type_traits::DynTypedNode::create(Node),
612                              Matcher, Builder, MatchMode);
613   }
614
615   virtual ASTContext &getASTContext() const = 0;
616
617 protected:
618   virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node,
619                               const DynTypedMatcher &Matcher,
620                               BoundNodesTreeBuilder *Builder,
621                               TraversalKind Traverse,
622                               BindKind Bind) = 0;
623
624   virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node,
625                                    const DynTypedMatcher &Matcher,
626                                    BoundNodesTreeBuilder *Builder,
627                                    BindKind Bind) = 0;
628
629   virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node,
630                                  const DynTypedMatcher &Matcher,
631                                  BoundNodesTreeBuilder *Builder,
632                                  AncestorMatchMode MatchMode) = 0;
633 };
634
635 /// \brief Converts a \c Matcher<T> to a matcher of desired type \c To by
636 /// "adapting" a \c To into a \c T.
637 ///
638 /// The \c ArgumentAdapterT argument specifies how the adaptation is done.
639 ///
640 /// For example:
641 ///   \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher);
642 /// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher
643 /// that is convertible into any matcher of type \c To by constructing
644 /// \c HasMatcher<To, T>(InnerMatcher).
645 ///
646 /// If a matcher does not need knowledge about the inner type, prefer to use
647 /// PolymorphicMatcherWithParam1.
648 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
649           typename T>
650 class ArgumentAdaptingMatcher {
651 public:
652   explicit ArgumentAdaptingMatcher(const Matcher<T> &InnerMatcher)
653       : InnerMatcher(InnerMatcher) {}
654
655   template <typename To>
656   operator Matcher<To>() const {
657     return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher));
658   }
659
660 private:
661   const Matcher<T> InnerMatcher;
662 };
663
664 /// \brief A PolymorphicMatcherWithParamN<MatcherT, P1, ..., PN> object can be
665 /// created from N parameters p1, ..., pN (of type P1, ..., PN) and
666 /// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN)
667 /// can be constructed.
668 ///
669 /// For example:
670 /// - PolymorphicMatcherWithParam0<IsDefinitionMatcher>()
671 ///   creates an object that can be used as a Matcher<T> for any type T
672 ///   where an IsDefinitionMatcher<T>() can be constructed.
673 /// - PolymorphicMatcherWithParam1<ValueEqualsMatcher, int>(42)
674 ///   creates an object that can be used as a Matcher<T> for any type T
675 ///   where a ValueEqualsMatcher<T, int>(42) can be constructed.
676 template <template <typename T> class MatcherT>
677 class PolymorphicMatcherWithParam0 {
678 public:
679   template <typename T>
680   operator Matcher<T>() const {
681     return Matcher<T>(new MatcherT<T>());
682   }
683 };
684
685 template <template <typename T, typename P1> class MatcherT,
686           typename P1>
687 class PolymorphicMatcherWithParam1 {
688 public:
689   explicit PolymorphicMatcherWithParam1(const P1 &Param1)
690       : Param1(Param1) {}
691
692   template <typename T>
693   operator Matcher<T>() const {
694     return Matcher<T>(new MatcherT<T, P1>(Param1));
695   }
696
697 private:
698   const P1 Param1;
699 };
700
701 template <template <typename T, typename P1, typename P2> class MatcherT,
702           typename P1, typename P2>
703 class PolymorphicMatcherWithParam2 {
704 public:
705   PolymorphicMatcherWithParam2(const P1 &Param1, const P2 &Param2)
706       : Param1(Param1), Param2(Param2) {}
707
708   template <typename T>
709   operator Matcher<T>() const {
710     return Matcher<T>(new MatcherT<T, P1, P2>(Param1, Param2));
711   }
712
713 private:
714   const P1 Param1;
715   const P2 Param2;
716 };
717
718 /// \brief Matches any instance of the given NodeType.
719 ///
720 /// This is useful when a matcher syntactically requires a child matcher,
721 /// but the context doesn't care. See for example: anything().
722 ///
723 /// FIXME: Alternatively we could also create a IsAMatcher or something
724 /// that checks that a dyn_cast is possible. This is purely needed for the
725 /// difference between calling for example:
726 ///   record()
727 /// and
728 ///   record(SomeMatcher)
729 /// In the second case we need the correct type we were dyn_cast'ed to in order
730 /// to get the right type for the inner matcher. In the first case we don't need
731 /// that, but we use the type conversion anyway and insert a TrueMatcher.
732 template <typename T>
733 class TrueMatcher : public SingleNodeMatcherInterface<T>  {
734 public:
735   virtual bool matchesNode(const T &Node) const {
736     return true;
737   }
738 };
739
740 /// \brief Provides a MatcherInterface<T> for a Matcher<To> that matches if T is
741 /// dyn_cast'able into To and the given Matcher<To> matches on the dyn_cast'ed
742 /// node.
743 template <typename T, typename To>
744 class DynCastMatcher : public MatcherInterface<T> {
745 public:
746   explicit DynCastMatcher(const Matcher<To> &InnerMatcher)
747       : InnerMatcher(InnerMatcher) {}
748
749   virtual bool matches(const T &Node,
750                        ASTMatchFinder *Finder,
751                        BoundNodesTreeBuilder *Builder) const {
752     const To *InnerMatchValue = dyn_cast<To>(&Node);
753     return InnerMatchValue != NULL &&
754       InnerMatcher.matches(*InnerMatchValue, Finder, Builder);
755   }
756
757 private:
758   const Matcher<To> InnerMatcher;
759 };
760
761 /// \brief Matcher<T> that wraps an inner Matcher<T> and binds the matched node
762 /// to an ID if the inner matcher matches on the node.
763 template <typename T>
764 class IdMatcher : public MatcherInterface<T> {
765 public:
766   /// \brief Creates an IdMatcher that binds to 'ID' if 'InnerMatcher' matches
767   /// the node.
768   IdMatcher(StringRef ID, const Matcher<T> &InnerMatcher)
769       : ID(ID), InnerMatcher(InnerMatcher) {}
770
771   virtual bool matches(const T &Node,
772                        ASTMatchFinder *Finder,
773                        BoundNodesTreeBuilder *Builder) const {
774     bool Result = InnerMatcher.matches(Node, Finder, Builder);
775     if (Result) {
776       Builder->setBinding(ID, &Node);
777     }
778     return Result;
779   }
780
781 private:
782   const std::string ID;
783   const Matcher<T> InnerMatcher;
784 };
785
786 /// \brief A Matcher that allows binding the node it matches to an id.
787 ///
788 /// BindableMatcher provides a \a bind() method that allows binding the
789 /// matched node to an id if the match was successful.
790 template <typename T>
791 class BindableMatcher : public Matcher<T> {
792 public:
793   BindableMatcher(MatcherInterface<T> *Implementation)
794     : Matcher<T>(Implementation) {}
795
796   /// \brief Returns a matcher that will bind the matched node on a match.
797   ///
798   /// The returned matcher is equivalent to this matcher, but will
799   /// bind the matched node on a match.
800   Matcher<T> bind(StringRef ID) const {
801     return Matcher<T>(new IdMatcher<T>(ID, *this));
802   }
803 };
804
805 /// \brief Matches nodes of type T that have child nodes of type ChildT for
806 /// which a specified child matcher matches.
807 ///
808 /// ChildT must be an AST base type.
809 template <typename T, typename ChildT>
810 class HasMatcher : public MatcherInterface<T> {
811   TOOLING_COMPILE_ASSERT(IsBaseType<ChildT>::value,
812                          has_only_accepts_base_type_matcher);
813 public:
814   explicit HasMatcher(const Matcher<ChildT> &ChildMatcher)
815       : ChildMatcher(ChildMatcher) {}
816
817   virtual bool matches(const T &Node,
818                        ASTMatchFinder *Finder,
819                        BoundNodesTreeBuilder *Builder) const {
820     return Finder->matchesChildOf(
821         Node, ChildMatcher, Builder,
822         ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
823         ASTMatchFinder::BK_First);
824   }
825
826  private:
827   const Matcher<ChildT> ChildMatcher;
828 };
829
830 /// \brief Matches nodes of type T that have child nodes of type ChildT for
831 /// which a specified child matcher matches. ChildT must be an AST base
832 /// type.
833 /// As opposed to the HasMatcher, the ForEachMatcher will produce a match
834 /// for each child that matches.
835 template <typename T, typename ChildT>
836 class ForEachMatcher : public MatcherInterface<T> {
837   TOOLING_COMPILE_ASSERT(IsBaseType<ChildT>::value,
838                          for_each_only_accepts_base_type_matcher);
839  public:
840   explicit ForEachMatcher(const Matcher<ChildT> &ChildMatcher)
841       : ChildMatcher(ChildMatcher) {}
842
843   virtual bool matches(const T& Node,
844                        ASTMatchFinder* Finder,
845                        BoundNodesTreeBuilder* Builder) const {
846     return Finder->matchesChildOf(
847       Node, ChildMatcher, Builder,
848       ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
849       ASTMatchFinder::BK_All);
850   }
851
852 private:
853   const Matcher<ChildT> ChildMatcher;
854 };
855
856 /// \brief Matches nodes of type T if the given Matcher<T> does not match.
857 ///
858 /// Type argument MatcherT is required by PolymorphicMatcherWithParam1
859 /// but not actually used. It will always be instantiated with a type
860 /// convertible to Matcher<T>.
861 template <typename T, typename MatcherT>
862 class NotMatcher : public MatcherInterface<T> {
863 public:
864   explicit NotMatcher(const Matcher<T> &InnerMatcher)
865       : InnerMatcher(InnerMatcher) {}
866
867   virtual bool matches(const T &Node,
868                        ASTMatchFinder *Finder,
869                        BoundNodesTreeBuilder *Builder) const {
870     return !InnerMatcher.matches(Node, Finder, Builder);
871   }
872
873 private:
874   const Matcher<T> InnerMatcher;
875 };
876
877 /// \brief Matches nodes of type T for which both provided matchers match.
878 ///
879 /// Type arguments MatcherT1 and MatcherT2 are required by
880 /// PolymorphicMatcherWithParam2 but not actually used. They will
881 /// always be instantiated with types convertible to Matcher<T>.
882 template <typename T, typename MatcherT1, typename MatcherT2>
883 class AllOfMatcher : public MatcherInterface<T> {
884 public:
885   AllOfMatcher(const Matcher<T> &InnerMatcher1, const Matcher<T> &InnerMatcher2)
886       : InnerMatcher1(InnerMatcher1), InnerMatcher2(InnerMatcher2) {}
887
888   virtual bool matches(const T &Node,
889                        ASTMatchFinder *Finder,
890                        BoundNodesTreeBuilder *Builder) const {
891     return InnerMatcher1.matches(Node, Finder, Builder) &&
892            InnerMatcher2.matches(Node, Finder, Builder);
893   }
894
895 private:
896   const Matcher<T> InnerMatcher1;
897   const Matcher<T> InnerMatcher2;
898 };
899
900 /// \brief Matches nodes of type T for which at least one of the two provided
901 /// matchers matches.
902 ///
903 /// Type arguments MatcherT1 and MatcherT2 are
904 /// required by PolymorphicMatcherWithParam2 but not actually
905 /// used. They will always be instantiated with types convertible to
906 /// Matcher<T>.
907 template <typename T, typename MatcherT1, typename MatcherT2>
908 class EachOfMatcher : public MatcherInterface<T> {
909 public:
910   EachOfMatcher(const Matcher<T> &InnerMatcher1,
911                 const Matcher<T> &InnerMatcher2)
912       : InnerMatcher1(InnerMatcher1), InnerMatcher2(InnerMatcher2) {
913   }
914
915   virtual bool matches(const T &Node, ASTMatchFinder *Finder,
916                        BoundNodesTreeBuilder *Builder) const {
917     BoundNodesTreeBuilder Builder1;
918     bool Matched1 = InnerMatcher1.matches(Node, Finder, &Builder1);
919     if (Matched1)
920       Builder->addMatch(Builder1.build());
921
922     BoundNodesTreeBuilder Builder2;
923     bool Matched2 = InnerMatcher2.matches(Node, Finder, &Builder2);
924     if (Matched2)
925       Builder->addMatch(Builder2.build());
926
927     return Matched1 || Matched2;
928   }
929
930 private:
931   const Matcher<T> InnerMatcher1;
932   const Matcher<T> InnerMatcher2;
933 };
934
935 /// \brief Matches nodes of type T for which at least one of the two provided
936 /// matchers matches.
937 ///
938 /// Type arguments MatcherT1 and MatcherT2 are
939 /// required by PolymorphicMatcherWithParam2 but not actually
940 /// used. They will always be instantiated with types convertible to
941 /// Matcher<T>.
942 template <typename T, typename MatcherT1, typename MatcherT2>
943 class AnyOfMatcher : public MatcherInterface<T> {
944 public:
945   AnyOfMatcher(const Matcher<T> &InnerMatcher1, const Matcher<T> &InnerMatcher2)
946       : InnerMatcher1(InnerMatcher1), InnerMatcher2(InnerMatcher2) {}
947
948   virtual bool matches(const T &Node,
949                        ASTMatchFinder *Finder,
950                        BoundNodesTreeBuilder *Builder) const {
951     return InnerMatcher1.matches(Node, Finder, Builder) ||
952            InnerMatcher2.matches(Node, Finder, Builder);
953   }
954
955 private:
956   const Matcher<T> InnerMatcher1;
957   const Matcher<T> InnerMatcher2;
958 };
959
960 /// \brief Creates a Matcher<T> that matches if all inner matchers match.
961 template<typename T>
962 BindableMatcher<T> makeAllOfComposite(
963     ArrayRef<const Matcher<T> *> InnerMatchers) {
964   if (InnerMatchers.empty())
965     return BindableMatcher<T>(new TrueMatcher<T>);
966   MatcherInterface<T> *InnerMatcher = new TrueMatcher<T>;
967   for (int i = InnerMatchers.size() - 1; i >= 0; --i) {
968     InnerMatcher = new AllOfMatcher<T, Matcher<T>, Matcher<T> >(
969       *InnerMatchers[i], makeMatcher(InnerMatcher));
970   }
971   return BindableMatcher<T>(InnerMatcher);
972 }
973
974 /// \brief Creates a Matcher<T> that matches if
975 /// T is dyn_cast'able into InnerT and all inner matchers match.
976 ///
977 /// Returns BindableMatcher, as matchers that use dyn_cast have
978 /// the same object both to match on and to run submatchers on,
979 /// so there is no ambiguity with what gets bound.
980 template<typename T, typename InnerT>
981 BindableMatcher<T> makeDynCastAllOfComposite(
982     ArrayRef<const Matcher<InnerT> *> InnerMatchers) {
983   return BindableMatcher<T>(new DynCastMatcher<T, InnerT>(
984     makeAllOfComposite(InnerMatchers)));
985 }
986
987 /// \brief Matches nodes of type T that have at least one descendant node of
988 /// type DescendantT for which the given inner matcher matches.
989 ///
990 /// DescendantT must be an AST base type.
991 template <typename T, typename DescendantT>
992 class HasDescendantMatcher : public MatcherInterface<T> {
993   TOOLING_COMPILE_ASSERT(IsBaseType<DescendantT>::value,
994                          has_descendant_only_accepts_base_type_matcher);
995 public:
996   explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher)
997       : DescendantMatcher(DescendantMatcher) {}
998
999   virtual bool matches(const T &Node,
1000                        ASTMatchFinder *Finder,
1001                        BoundNodesTreeBuilder *Builder) const {
1002     return Finder->matchesDescendantOf(
1003         Node, DescendantMatcher, Builder, ASTMatchFinder::BK_First);
1004   }
1005
1006  private:
1007   const Matcher<DescendantT> DescendantMatcher;
1008 };
1009
1010 /// \brief Matches nodes of type \c T that have a parent node of type \c ParentT
1011 /// for which the given inner matcher matches.
1012 ///
1013 /// \c ParentT must be an AST base type.
1014 template <typename T, typename ParentT>
1015 class HasParentMatcher : public MatcherInterface<T> {
1016   TOOLING_COMPILE_ASSERT(IsBaseType<ParentT>::value,
1017                          has_parent_only_accepts_base_type_matcher);
1018 public:
1019   explicit HasParentMatcher(const Matcher<ParentT> &ParentMatcher)
1020       : ParentMatcher(ParentMatcher) {}
1021
1022   virtual bool matches(const T &Node,
1023                        ASTMatchFinder *Finder,
1024                        BoundNodesTreeBuilder *Builder) const {
1025     return Finder->matchesAncestorOf(
1026         Node, ParentMatcher, Builder, ASTMatchFinder::AMM_ParentOnly);
1027   }
1028
1029  private:
1030   const Matcher<ParentT> ParentMatcher;
1031 };
1032
1033 /// \brief Matches nodes of type \c T that have at least one ancestor node of
1034 /// type \c AncestorT for which the given inner matcher matches.
1035 ///
1036 /// \c AncestorT must be an AST base type.
1037 template <typename T, typename AncestorT>
1038 class HasAncestorMatcher : public MatcherInterface<T> {
1039   TOOLING_COMPILE_ASSERT(IsBaseType<AncestorT>::value,
1040                          has_ancestor_only_accepts_base_type_matcher);
1041 public:
1042   explicit HasAncestorMatcher(const Matcher<AncestorT> &AncestorMatcher)
1043       : AncestorMatcher(AncestorMatcher) {}
1044
1045   virtual bool matches(const T &Node,
1046                        ASTMatchFinder *Finder,
1047                        BoundNodesTreeBuilder *Builder) const {
1048     return Finder->matchesAncestorOf(
1049         Node, AncestorMatcher, Builder, ASTMatchFinder::AMM_All);
1050   }
1051
1052  private:
1053   const Matcher<AncestorT> AncestorMatcher;
1054 };
1055
1056 /// \brief Matches nodes of type T that have at least one descendant node of
1057 /// type DescendantT for which the given inner matcher matches.
1058 ///
1059 /// DescendantT must be an AST base type.
1060 /// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match
1061 /// for each descendant node that matches instead of only for the first.
1062 template <typename T, typename DescendantT>
1063 class ForEachDescendantMatcher : public MatcherInterface<T> {
1064   TOOLING_COMPILE_ASSERT(IsBaseType<DescendantT>::value,
1065                          for_each_descendant_only_accepts_base_type_matcher);
1066  public:
1067   explicit ForEachDescendantMatcher(
1068       const Matcher<DescendantT>& DescendantMatcher)
1069       : DescendantMatcher(DescendantMatcher) {}
1070
1071   virtual bool matches(const T& Node,
1072                        ASTMatchFinder* Finder,
1073                        BoundNodesTreeBuilder* Builder) const {
1074     return Finder->matchesDescendantOf(Node, DescendantMatcher, Builder,
1075                                        ASTMatchFinder::BK_All);
1076   }
1077
1078 private:
1079   const Matcher<DescendantT> DescendantMatcher;
1080 };
1081
1082 /// \brief Matches on nodes that have a getValue() method if getValue() equals
1083 /// the value the ValueEqualsMatcher was constructed with.
1084 template <typename T, typename ValueT>
1085 class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> {
1086   TOOLING_COMPILE_ASSERT((llvm::is_base_of<CharacterLiteral, T>::value ||
1087                          llvm::is_base_of<CXXBoolLiteralExpr,
1088                                           T>::value ||
1089                          llvm::is_base_of<FloatingLiteral, T>::value ||
1090                          llvm::is_base_of<IntegerLiteral, T>::value),
1091                          the_node_must_have_a_getValue_method);
1092 public:
1093   explicit ValueEqualsMatcher(const ValueT &ExpectedValue)
1094       : ExpectedValue(ExpectedValue) {}
1095
1096   virtual bool matchesNode(const T &Node) const {
1097     return Node.getValue() == ExpectedValue;
1098   }
1099
1100 private:
1101   const ValueT ExpectedValue;
1102 };
1103
1104 /// \brief A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a
1105 /// variadic functor that takes a number of Matcher<TargetT> and returns a
1106 /// Matcher<SourceT> that matches TargetT nodes that are matched by all of the
1107 /// given matchers, if SourceT can be dynamically casted into TargetT.
1108 ///
1109 /// For example:
1110 ///   const VariadicDynCastAllOfMatcher<
1111 ///       Decl, CXXRecordDecl> record;
1112 /// Creates a functor record(...) that creates a Matcher<Decl> given
1113 /// a variable number of arguments of type Matcher<CXXRecordDecl>.
1114 /// The returned matcher matches if the given Decl can by dynamically
1115 /// casted to CXXRecordDecl and all given matchers match.
1116 template <typename SourceT, typename TargetT>
1117 class VariadicDynCastAllOfMatcher
1118     : public llvm::VariadicFunction<
1119         BindableMatcher<SourceT>, Matcher<TargetT>,
1120         makeDynCastAllOfComposite<SourceT, TargetT> > {
1121 public:
1122   VariadicDynCastAllOfMatcher() {}
1123 };
1124
1125 /// \brief A \c VariadicAllOfMatcher<T> object is a variadic functor that takes
1126 /// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T
1127 /// nodes that are matched by all of the given matchers.
1128 ///
1129 /// For example:
1130 ///   const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
1131 /// Creates a functor nestedNameSpecifier(...) that creates a
1132 /// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type
1133 /// \c Matcher<NestedNameSpecifier>.
1134 /// The returned matcher matches if all given matchers match.
1135 template <typename T>
1136 class VariadicAllOfMatcher : public llvm::VariadicFunction<
1137                                BindableMatcher<T>, Matcher<T>,
1138                                makeAllOfComposite<T> > {
1139 public:
1140   VariadicAllOfMatcher() {}
1141 };
1142
1143 /// \brief Matches nodes of type \c TLoc for which the inner
1144 /// \c Matcher<T> matches.
1145 template <typename TLoc, typename T>
1146 class LocMatcher : public MatcherInterface<TLoc> {
1147 public:
1148   explicit LocMatcher(const Matcher<T> &InnerMatcher)
1149     : InnerMatcher(InnerMatcher) {}
1150
1151   virtual bool matches(const TLoc &Node,
1152                        ASTMatchFinder *Finder,
1153                        BoundNodesTreeBuilder *Builder) const {
1154     if (!Node)
1155       return false;
1156     return InnerMatcher.matches(*extract(Node), Finder, Builder);
1157   }
1158
1159 private:
1160   const NestedNameSpecifier *extract(const NestedNameSpecifierLoc &Loc) const {
1161     return Loc.getNestedNameSpecifier();
1162   }
1163
1164   const Matcher<T> InnerMatcher;
1165 };
1166
1167 /// \brief Matches \c TypeLocs based on an inner matcher matching a certain
1168 /// \c QualType.
1169 ///
1170 /// Used to implement the \c loc() matcher.
1171 class TypeLocTypeMatcher : public MatcherInterface<TypeLoc> {
1172 public:
1173   explicit TypeLocTypeMatcher(const Matcher<QualType> &InnerMatcher)
1174       : InnerMatcher(InnerMatcher) {}
1175
1176   virtual bool matches(const TypeLoc &Node,
1177                        ASTMatchFinder *Finder,
1178                        BoundNodesTreeBuilder *Builder) const {
1179     if (!Node)
1180       return false;
1181     return InnerMatcher.matches(Node.getType(), Finder, Builder);
1182   }
1183
1184 private:
1185   const Matcher<QualType> InnerMatcher;
1186 };
1187
1188 /// \brief Matches nodes of type \c T for which the inner matcher matches on a
1189 /// another node of type \c T that can be reached using a given traverse
1190 /// function.
1191 template <typename T>
1192 class TypeTraverseMatcher : public MatcherInterface<T> {
1193 public:
1194   explicit TypeTraverseMatcher(const Matcher<QualType> &InnerMatcher,
1195                                QualType (T::*TraverseFunction)() const)
1196       : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {}
1197
1198   virtual bool matches(const T &Node,
1199                        ASTMatchFinder *Finder,
1200                        BoundNodesTreeBuilder *Builder) const {
1201     QualType NextNode = (Node.*TraverseFunction)();
1202     if (NextNode.isNull())
1203       return false;
1204     return InnerMatcher.matches(NextNode, Finder, Builder);
1205   }
1206
1207 private:
1208   const Matcher<QualType> InnerMatcher;
1209   QualType (T::*TraverseFunction)() const;
1210 };
1211
1212 /// \brief Matches nodes of type \c T in a ..Loc hierarchy, for which the inner
1213 /// matcher matches on a another node of type \c T that can be reached using a
1214 /// given traverse function.
1215 template <typename T>
1216 class TypeLocTraverseMatcher : public MatcherInterface<T> {
1217 public:
1218   explicit TypeLocTraverseMatcher(const Matcher<TypeLoc> &InnerMatcher,
1219                                   TypeLoc (T::*TraverseFunction)() const)
1220       : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {}
1221
1222   virtual bool matches(const T &Node,
1223                        ASTMatchFinder *Finder,
1224                        BoundNodesTreeBuilder *Builder) const {
1225     TypeLoc NextNode = (Node.*TraverseFunction)();
1226     if (!NextNode)
1227       return false;
1228     return InnerMatcher.matches(NextNode, Finder, Builder);
1229   }
1230
1231 private:
1232   const Matcher<TypeLoc> InnerMatcher;
1233   TypeLoc (T::*TraverseFunction)() const;
1234 };
1235
1236 template <typename T, typename InnerT>
1237 T makeTypeAllOfComposite(ArrayRef<const Matcher<InnerT> *> InnerMatchers) {
1238   return T(makeAllOfComposite<InnerT>(InnerMatchers));
1239 }
1240
1241 } // end namespace internal
1242 } // end namespace ast_matchers
1243 } // end namespace clang
1244
1245 #endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H