ASTMatchersInternal.h revision 8456ae602783b615019a42f7d5c6f0e71639b11b
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/Decl.h"
39#include "clang/AST/DeclCXX.h"
40#include "clang/AST/ExprCXX.h"
41#include "clang/AST/Stmt.h"
42#include "llvm/ADT/VariadicFunction.h"
43#include <map>
44#include <string>
45#include <vector>
46
47namespace clang {
48namespace ast_matchers {
49
50/// FIXME: Move into the llvm support library.
51template <bool> struct CompileAssert {};
52#define TOOLING_COMPILE_ASSERT(Expr, Msg) \
53  typedef CompileAssert<(bool(Expr))> Msg[bool(Expr) ? 1 : -1]
54
55class BoundNodes;
56
57namespace internal {
58
59class BoundNodesTreeBuilder;
60
61/// \brief A tree of bound nodes in match results.
62///
63/// If a match can contain multiple matches on the same node with different
64/// matching subexpressions, BoundNodesTree contains a branch for each of
65/// those matching subexpressions.
66///
67/// BoundNodesTree's are created during the matching process; when a match
68/// is found, we iterate over the tree and create a BoundNodes object containing
69/// the union of all bound nodes on the path from the root to a each leaf.
70class BoundNodesTree {
71public:
72  /// \brief A visitor interface to visit all BoundNodes results for a
73  /// BoundNodesTree.
74  class Visitor {
75  public:
76    virtual ~Visitor() {}
77
78    /// \brief Called multiple times during a single call to VisitMatches(...).
79    ///
80    /// 'BoundNodesView' contains the bound nodes for a single match.
81    virtual void visitMatch(const BoundNodes& BoundNodesView) = 0;
82  };
83
84  BoundNodesTree();
85
86  /// \brief Create a BoundNodesTree from pre-filled maps of bindings.
87  BoundNodesTree(const std::map<std::string, const Decl*>& DeclBindings,
88                 const std::map<std::string, const Stmt*>& StmtBindings,
89                 const std::vector<BoundNodesTree> RecursiveBindings);
90
91  /// \brief Adds all bound nodes to bound_nodes_builder.
92  void copyTo(BoundNodesTreeBuilder* Builder) const;
93
94  /// \brief Visits all matches that this BoundNodesTree represents.
95  ///
96  /// The ownership of 'ResultVisitor' remains at the caller.
97  void visitMatches(Visitor* ResultVisitor);
98
99private:
100  void visitMatchesRecursively(
101      Visitor* ResultVistior,
102      std::map<std::string, const Decl*> DeclBindings,
103      std::map<std::string, const Stmt*> StmtBindings);
104
105  template <typename T>
106  void copyBindingsTo(const T& bindings, BoundNodesTreeBuilder* Builder) const;
107
108  // FIXME: Find out whether we want to use different data structures here -
109  // first benchmarks indicate that it doesn't matter though.
110
111  std::map<std::string, const Decl*> DeclBindings;
112  std::map<std::string, const Stmt*> StmtBindings;
113
114  std::vector<BoundNodesTree> RecursiveBindings;
115};
116
117/// \brief Creates BoundNodesTree objects.
118///
119/// The tree builder is used during the matching process to insert the bound
120/// nodes from the Id matcher.
121class BoundNodesTreeBuilder {
122public:
123  BoundNodesTreeBuilder();
124
125  /// \brief Add a binding from an id to a node.
126  ///
127  /// FIXME: Add overloads for all AST base types.
128  /// @{
129  void setBinding(const std::string &Id, const Decl *Node);
130  void setBinding(const std::string &Id, const Stmt *Node);
131  /// @}
132
133  /// \brief Adds a branch in the tree.
134  void addMatch(const BoundNodesTree& Bindings);
135
136  /// \brief Returns a BoundNodes object containing all current bindings.
137  BoundNodesTree build() const;
138
139private:
140  BoundNodesTreeBuilder(const BoundNodesTreeBuilder&);  // DO NOT IMPLEMENT
141  void operator=(const BoundNodesTreeBuilder&);  // DO NOT IMPLEMENT
142
143  std::map<std::string, const Decl*> DeclBindings;
144  std::map<std::string, const Stmt*> StmtBindings;
145
146  std::vector<BoundNodesTree> RecursiveBindings;
147};
148
149class ASTMatchFinder;
150
151/// \brief Generic interface for matchers on an AST node of type T.
152///
153/// Implement this if your matcher may need to inspect the children or
154/// descendants of the node or bind matched nodes to names. If you are
155/// writing a simple matcher that only inspects properties of the
156/// current node and doesn't care about its children or descendants,
157/// implement SingleNodeMatcherInterface instead.
158template <typename T>
159class MatcherInterface : public llvm::RefCountedBaseVPTR {
160public:
161  virtual ~MatcherInterface() {}
162
163  /// \brief Returns true if 'Node' can be matched.
164  ///
165  /// May bind 'Node' to an ID via 'Builder', or recurse into
166  /// the AST via 'Finder'.
167  virtual bool matches(const T &Node,
168                       ASTMatchFinder *Finder,
169                       BoundNodesTreeBuilder *Builder) const = 0;
170};
171
172/// \brief Interface for matchers that only evaluate properties on a single node.
173template <typename T>
174class SingleNodeMatcherInterface : public MatcherInterface<T> {
175public:
176  /// \brief Returns true if the matcher matches the provided node.
177  ///
178  /// A subclass must implement this instead of Matches().
179  virtual bool matchesNode(const T &Node) const = 0;
180
181private:
182  /// Implements MatcherInterface::Matches.
183  virtual bool matches(const T &Node,
184                       ASTMatchFinder * /* Finder */,
185                       BoundNodesTreeBuilder * /*  Builder */) const {
186    return matchesNode(Node);
187  }
188};
189
190/// \brief Wrapper of a MatcherInterface<T> *that allows copying.
191///
192/// A Matcher<Base> can be used anywhere a Matcher<Derived> is
193/// required. This establishes an is-a relationship which is reverse
194/// to the AST hierarchy. In other words, Matcher<T> is contravariant
195/// with respect to T. The relationship is built via a type conversion
196/// operator rather than a type hierarchy to be able to templatize the
197/// type hierarchy instead of spelling it out.
198template <typename T>
199class Matcher {
200public:
201  /// \brief Takes ownership of the provided implementation pointer.
202  explicit Matcher(MatcherInterface<T> *Implementation)
203      : Implementation(Implementation) {}
204
205  /// \brief Forwards the call to the underlying MatcherInterface<T> pointer.
206  bool matches(const T &Node,
207               ASTMatchFinder *Finder,
208               BoundNodesTreeBuilder *Builder) const {
209    return Implementation->matches(Node, Finder, Builder);
210  }
211
212  /// \brief Implicitly converts this object to a Matcher<Derived>.
213  ///
214  /// Requires Derived to be derived from T.
215  template <typename Derived>
216  operator Matcher<Derived>() const {
217    return Matcher<Derived>(new ImplicitCastMatcher<Derived>(*this));
218  }
219
220  /// \brief Returns an ID that uniquely identifies the matcher.
221  uint64_t getID() const {
222    /// FIXME: Document the requirements this imposes on matcher
223    /// implementations (no new() implementation_ during a Matches()).
224    return reinterpret_cast<uint64_t>(Implementation.getPtr());
225  }
226
227private:
228  /// \brief Allows conversion from Matcher<T> to Matcher<Derived> if Derived
229  /// is derived from T.
230  template <typename Derived>
231  class ImplicitCastMatcher : public MatcherInterface<Derived> {
232  public:
233    explicit ImplicitCastMatcher(const Matcher<T> &From)
234        : From(From) {}
235
236    virtual bool matches(const Derived &Node,
237                         ASTMatchFinder *Finder,
238                         BoundNodesTreeBuilder *Builder) const {
239      return From.matches(Node, Finder, Builder);
240    }
241
242  private:
243    const Matcher<T> From;
244  };
245
246  llvm::IntrusiveRefCntPtr< MatcherInterface<T> > Implementation;
247};  // class Matcher
248
249/// \brief A convenient helper for creating a Matcher<T> without specifying
250/// the template type argument.
251template <typename T>
252inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) {
253  return Matcher<T>(Implementation);
254}
255
256/// \brief Matches declarations for QualType and CallExpr.
257///
258/// Type argument DeclMatcherT is required by PolymorphicMatcherWithParam1 but
259/// not actually used.
260template <typename T, typename DeclMatcherT>
261class HasDeclarationMatcher : public MatcherInterface<T> {
262  TOOLING_COMPILE_ASSERT((llvm::is_same< DeclMatcherT,
263                                         Matcher<Decl> >::value),
264                          instantiated_with_wrong_types);
265public:
266  explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher)
267      : InnerMatcher(InnerMatcher) {}
268
269  virtual bool matches(const T &Node,
270                       ASTMatchFinder *Finder,
271                       BoundNodesTreeBuilder *Builder) const {
272    return matchesSpecialized(Node, Finder, Builder);
273  }
274
275private:
276  /// \brief Extracts the CXXRecordDecl of a QualType and returns whether the
277  /// inner matcher matches on it.
278  bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder,
279                          BoundNodesTreeBuilder *Builder) const {
280    /// FIXME: Add other ways to convert...
281    if (Node.isNull())
282      return false;
283    CXXRecordDecl *NodeAsRecordDecl = Node->getAsCXXRecordDecl();
284    return NodeAsRecordDecl != NULL &&
285      InnerMatcher.matches(*NodeAsRecordDecl, Finder, Builder);
286  }
287
288  /// \brief Extracts the Decl of the callee of a CallExpr and returns whether
289  /// the inner matcher matches on it.
290  bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder,
291                          BoundNodesTreeBuilder *Builder) const {
292    const Decl *NodeAsDecl = Node.getCalleeDecl();
293    return NodeAsDecl != NULL &&
294      InnerMatcher.matches(*NodeAsDecl, Finder, Builder);
295  }
296
297  /// \brief Extracts the Decl of the constructor call and returns whether the
298  /// inner matcher matches on it.
299  bool matchesSpecialized(const CXXConstructExpr &Node,
300                          ASTMatchFinder *Finder,
301                          BoundNodesTreeBuilder *Builder) const {
302    const Decl *NodeAsDecl = Node.getConstructor();
303    return NodeAsDecl != NULL &&
304      InnerMatcher.matches(*NodeAsDecl, Finder, Builder);
305  }
306
307  const Matcher<Decl> InnerMatcher;
308};
309
310/// \brief IsBaseType<T>::value is true if T is a "base" type in the AST
311/// node class hierarchies (i.e. if T is Decl, Stmt, or QualType).
312template <typename T>
313struct IsBaseType {
314  static const bool value =
315      (llvm::is_same<T, Decl>::value ||
316       llvm::is_same<T, Stmt>::value ||
317       llvm::is_same<T, QualType>::value ||
318       llvm::is_same<T, CXXCtorInitializer>::value);
319};
320template <typename T>
321const bool IsBaseType<T>::value;
322
323/// \brief Interface that can match any AST base node type and contains default
324/// implementations returning false.
325class UntypedBaseMatcher : public llvm::RefCountedBaseVPTR {
326public:
327  virtual ~UntypedBaseMatcher() {}
328
329  virtual bool matches(const Decl &DeclNode, ASTMatchFinder *Finder,
330                       BoundNodesTreeBuilder *Builder) const {
331    return false;
332  }
333  virtual bool matches(const QualType &TypeNode, ASTMatchFinder *Finder,
334                       BoundNodesTreeBuilder *Builder) const {
335    return false;
336  }
337  virtual bool matches(const Stmt &StmtNode, ASTMatchFinder *Finder,
338                       BoundNodesTreeBuilder *Builder) const {
339    return false;
340  }
341  virtual bool matches(const CXXCtorInitializer &CtorInitNode,
342                       ASTMatchFinder *Finder,
343                       BoundNodesTreeBuilder *Builder) const {
344    return false;
345  }
346
347  /// \brief Returns a unique ID for the matcher.
348  virtual uint64_t getID() const = 0;
349};
350
351/// \brief An UntypedBaseMatcher that overwrites the Matches(...) method for
352/// node type T. T must be an AST base type.
353template <typename T>
354class TypedBaseMatcher : public UntypedBaseMatcher {
355  TOOLING_COMPILE_ASSERT(IsBaseType<T>::value,
356                         typed_base_matcher_can_only_be_used_with_base_type);
357public:
358  explicit TypedBaseMatcher(const Matcher<T> &InnerMatcher)
359      : InnerMatcher(InnerMatcher) {}
360
361  using UntypedBaseMatcher::matches;
362  /// \brief Implements UntypedBaseMatcher::Matches.
363  ///
364  /// Since T is guaranteed to be a "base" AST node type, this method is
365  /// guaranteed to override one of the matches() methods from
366  /// UntypedBaseMatcher.
367  virtual bool matches(const T &Node,
368                       ASTMatchFinder *Finder,
369                       BoundNodesTreeBuilder *Builder) const {
370    return InnerMatcher.matches(Node, Finder, Builder);
371  }
372
373  /// \brief Implements UntypedBaseMatcher::getID.
374  virtual uint64_t getID() const {
375    return InnerMatcher.getID();
376  }
377
378private:
379  Matcher<T> InnerMatcher;
380};
381
382/// \brief Interface that allows matchers to traverse the AST.
383/// FIXME: Find a better name.
384///
385/// This provides two entry methods for each base node type in the AST:
386/// - matchesChildOf:
387///   Matches a matcher on every child node of the given node. Returns true
388///   if at least one child node could be matched.
389/// - matchesDescendantOf:
390///   Matches a matcher on all descendant nodes of the given node. Returns true
391///   if at least one descendant matched.
392class ASTMatchFinder {
393public:
394  /// \brief Defines how we descend a level in the AST when we pass
395  /// through expressions.
396  enum TraversalKind {
397    /// Will traverse any child nodes.
398    TK_AsIs,
399    /// Will not traverse implicit casts and parentheses.
400    TK_IgnoreImplicitCastsAndParentheses
401  };
402
403  /// \brief Defines how bindings are processed on recursive matches.
404  enum BindKind {
405    /// Stop at the first match and only bind the first match.
406    BK_First,
407    /// Create results for all combinations of bindings that match.
408    BK_All
409  };
410
411  virtual ~ASTMatchFinder() {}
412
413  /// \brief Returns true if the given class is directly or indirectly derived
414  /// from a base type matching \c base.
415  ///
416  /// A class is considered to be also derived from itself.
417  virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
418                                  const Matcher<NamedDecl> &Base,
419                                  BoundNodesTreeBuilder *Builder) = 0;
420
421  // FIXME: Implement for other base nodes.
422  virtual bool matchesChildOf(const Decl &DeclNode,
423                              const UntypedBaseMatcher &BaseMatcher,
424                              BoundNodesTreeBuilder *Builder,
425                              TraversalKind Traverse,
426                              BindKind Bind) = 0;
427  virtual bool matchesChildOf(const Stmt &StmtNode,
428                              const UntypedBaseMatcher &BaseMatcher,
429                              BoundNodesTreeBuilder *Builder,
430                              TraversalKind Traverse,
431                              BindKind Bind) = 0;
432
433  virtual bool matchesDescendantOf(const Decl &DeclNode,
434                                   const UntypedBaseMatcher &BaseMatcher,
435                                   BoundNodesTreeBuilder *Builder,
436                                   BindKind Bind) = 0;
437  virtual bool matchesDescendantOf(const Stmt &StmtNode,
438                                   const UntypedBaseMatcher &BaseMatcher,
439                                   BoundNodesTreeBuilder *Builder,
440                                   BindKind Bind) = 0;
441};
442
443/// \brief Converts a \c Matcher<T> to a matcher of desired type \c To by
444/// "adapting" a \c To into a \c T.
445///
446/// The \c ArgumentAdapterT argument specifies how the adaptation is done.
447///
448/// For example:
449///   \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher);
450/// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher
451/// that is convertible into any matcher of type \c To by constructing
452/// \c HasMatcher<To, T>(InnerMatcher).
453///
454/// If a matcher does not need knowledge about the inner type, prefer to use
455/// PolymorphicMatcherWithParam1.
456template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
457          typename T>
458class ArgumentAdaptingMatcher {
459public:
460  explicit ArgumentAdaptingMatcher(const Matcher<T> &InnerMatcher)
461      : InnerMatcher(InnerMatcher) {}
462
463  template <typename To>
464  operator Matcher<To>() const {
465    return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher));
466  }
467
468private:
469  const Matcher<T> InnerMatcher;
470};
471
472/// \brief A PolymorphicMatcherWithParamN<MatcherT, P1, ..., PN> object can be
473/// created from N parameters p1, ..., pN (of type P1, ..., PN) and
474/// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN)
475/// can be constructed.
476///
477/// For example:
478/// - PolymorphicMatcherWithParam0<IsDefinitionMatcher>()
479///   creates an object that can be used as a Matcher<T> for any type T
480///   where an IsDefinitionMatcher<T>() can be constructed.
481/// - PolymorphicMatcherWithParam1<ValueEqualsMatcher, int>(42)
482///   creates an object that can be used as a Matcher<T> for any type T
483///   where a ValueEqualsMatcher<T, int>(42) can be constructed.
484template <template <typename T> class MatcherT>
485class PolymorphicMatcherWithParam0 {
486public:
487  template <typename T>
488  operator Matcher<T>() const {
489    return Matcher<T>(new MatcherT<T>());
490  }
491};
492
493template <template <typename T, typename P1> class MatcherT,
494          typename P1>
495class PolymorphicMatcherWithParam1 {
496public:
497  explicit PolymorphicMatcherWithParam1(const P1 &Param1)
498      : Param1(Param1) {}
499
500  template <typename T>
501  operator Matcher<T>() const {
502    return Matcher<T>(new MatcherT<T, P1>(Param1));
503  }
504
505private:
506  const P1 Param1;
507};
508
509template <template <typename T, typename P1, typename P2> class MatcherT,
510          typename P1, typename P2>
511class PolymorphicMatcherWithParam2 {
512public:
513  PolymorphicMatcherWithParam2(const P1 &Param1, const P2 &Param2)
514      : Param1(Param1), Param2(Param2) {}
515
516  template <typename T>
517  operator Matcher<T>() const {
518    return Matcher<T>(new MatcherT<T, P1, P2>(Param1, Param2));
519  }
520
521private:
522  const P1 Param1;
523  const P2 Param2;
524};
525
526/// \brief Matches any instance of the given NodeType.
527///
528/// This is useful when a matcher syntactically requires a child matcher,
529/// but the context doesn't care. See for example: anything().
530///
531/// FIXME: Alternatively we could also create a IsAMatcher or something
532/// that checks that a dyn_cast is possible. This is purely needed for the
533/// difference between calling for example:
534///   record()
535/// and
536///   record(SomeMatcher)
537/// In the second case we need the correct type we were dyn_cast'ed to in order
538/// to get the right type for the inner matcher. In the first case we don't need
539/// that, but we use the type conversion anyway and insert a TrueMatcher.
540template <typename T>
541class TrueMatcher : public SingleNodeMatcherInterface<T>  {
542public:
543  virtual bool matchesNode(const T &Node) const {
544    return true;
545  }
546};
547
548/// \brief Provides a MatcherInterface<T> for a Matcher<To> that matches if T is
549/// dyn_cast'able into To and the given Matcher<To> matches on the dyn_cast'ed
550/// node.
551template <typename T, typename To>
552class DynCastMatcher : public MatcherInterface<T> {
553public:
554  explicit DynCastMatcher(const Matcher<To> &InnerMatcher)
555      : InnerMatcher(InnerMatcher) {}
556
557  virtual bool matches(const T &Node,
558                       ASTMatchFinder *Finder,
559                       BoundNodesTreeBuilder *Builder) const {
560    const To *InnerMatchValue = llvm::dyn_cast<To>(&Node);
561    return InnerMatchValue != NULL &&
562      InnerMatcher.matches(*InnerMatchValue, Finder, Builder);
563  }
564
565private:
566  const Matcher<To> InnerMatcher;
567};
568
569/// \brief Matcher<T> that wraps an inner Matcher<T> and binds the matched node
570/// to an ID if the inner matcher matches on the node.
571template <typename T>
572class IdMatcher : public MatcherInterface<T> {
573public:
574  /// \brief Creates an IdMatcher that binds to 'ID' if 'InnerMatcher' matches
575  /// the node.
576  IdMatcher(StringRef ID, const Matcher<T> &InnerMatcher)
577      : ID(ID), InnerMatcher(InnerMatcher) {}
578
579  virtual bool matches(const T &Node,
580                       ASTMatchFinder *Finder,
581                       BoundNodesTreeBuilder *Builder) const {
582    bool Result = InnerMatcher.matches(Node, Finder, Builder);
583    if (Result) {
584      Builder->setBinding(ID, &Node);
585    }
586    return Result;
587  }
588
589private:
590  const std::string ID;
591  const Matcher<T> InnerMatcher;
592};
593
594/// \brief A Matcher that allows binding the node it matches to an id.
595///
596/// BindableMatcher provides a \a bind() method that allows binding the
597/// matched node to an id if the match was successful.
598template <typename T>
599class BindableMatcher : public Matcher<T> {
600public:
601  BindableMatcher(MatcherInterface<T> *Implementation)
602    : Matcher<T>(Implementation) {}
603
604  /// \brief Returns a matcher that will bind the matched node on a match.
605  ///
606  /// The returned matcher is equivalent to this matcher, but will
607  /// bind the matched node on a match.
608  Matcher<T> bind(StringRef ID) const {
609    TOOLING_COMPILE_ASSERT((llvm::is_base_of<Stmt, T>::value ||
610                            llvm::is_base_of<Decl, T>::value),
611      trying_to_bind_unsupported_node_type__only_decl_and_stmt_supported);
612    return Matcher<T>(new IdMatcher<T>(ID, *this));
613  }
614};
615
616/// \brief Matches nodes of type T that have child nodes of type ChildT for
617/// which a specified child matcher matches.
618///
619/// ChildT must be an AST base type.
620template <typename T, typename ChildT>
621class HasMatcher : public MatcherInterface<T> {
622  TOOLING_COMPILE_ASSERT(IsBaseType<ChildT>::value,
623                         has_only_accepts_base_type_matcher);
624public:
625  explicit HasMatcher(const Matcher<ChildT> &ChildMatcher)
626      : ChildMatcher(ChildMatcher) {}
627
628  virtual bool matches(const T &Node,
629                       ASTMatchFinder *Finder,
630                       BoundNodesTreeBuilder *Builder) const {
631    return Finder->matchesChildOf(
632        Node, ChildMatcher, Builder,
633        ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
634        ASTMatchFinder::BK_First);
635  }
636
637 private:
638  const TypedBaseMatcher<ChildT> ChildMatcher;
639};
640
641/// \brief Matches nodes of type T that have child nodes of type ChildT for
642/// which a specified child matcher matches. ChildT must be an AST base
643/// type.
644/// As opposed to the HasMatcher, the ForEachMatcher will produce a match
645/// for each child that matches.
646template <typename T, typename ChildT>
647class ForEachMatcher : public MatcherInterface<T> {
648  TOOLING_COMPILE_ASSERT(IsBaseType<ChildT>::value,
649                         for_each_only_accepts_base_type_matcher);
650 public:
651  explicit ForEachMatcher(const Matcher<ChildT> &ChildMatcher)
652      : ChildMatcher(ChildMatcher) {}
653
654  virtual bool matches(const T& Node,
655                       ASTMatchFinder* Finder,
656                       BoundNodesTreeBuilder* Builder) const {
657    return Finder->matchesChildOf(
658      Node, ChildMatcher, Builder,
659      ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
660      ASTMatchFinder::BK_All);
661  }
662
663private:
664  const TypedBaseMatcher<ChildT> ChildMatcher;
665};
666
667/// \brief Matches nodes of type T if the given Matcher<T> does not match.
668///
669/// Type argument MatcherT is required by PolymorphicMatcherWithParam1
670/// but not actually used. It will always be instantiated with a type
671/// convertible to Matcher<T>.
672template <typename T, typename MatcherT>
673class NotMatcher : public MatcherInterface<T> {
674public:
675  explicit NotMatcher(const Matcher<T> &InnerMatcher)
676      : InnerMatcher(InnerMatcher) {}
677
678  virtual bool matches(const T &Node,
679                       ASTMatchFinder *Finder,
680                       BoundNodesTreeBuilder *Builder) const {
681    return !InnerMatcher.matches(Node, Finder, Builder);
682  }
683
684private:
685  const Matcher<T> InnerMatcher;
686};
687
688/// \brief Matches nodes of type T for which both provided matchers match.
689///
690/// Type arguments MatcherT1 and MatcherT2 are required by
691/// PolymorphicMatcherWithParam2 but not actually used. They will
692/// always be instantiated with types convertible to Matcher<T>.
693template <typename T, typename MatcherT1, typename MatcherT2>
694class AllOfMatcher : public MatcherInterface<T> {
695public:
696  AllOfMatcher(const Matcher<T> &InnerMatcher1, const Matcher<T> &InnerMatcher2)
697      : InnerMatcher1(InnerMatcher1), InnerMatcher2(InnerMatcher2) {}
698
699  virtual bool matches(const T &Node,
700                       ASTMatchFinder *Finder,
701                       BoundNodesTreeBuilder *Builder) const {
702    return InnerMatcher1.matches(Node, Finder, Builder) &&
703           InnerMatcher2.matches(Node, Finder, Builder);
704  }
705
706private:
707  const Matcher<T> InnerMatcher1;
708  const Matcher<T> InnerMatcher2;
709};
710
711/// \brief Matches nodes of type T for which at least one of the two provided
712/// matchers matches.
713///
714/// Type arguments MatcherT1 and MatcherT2 are
715/// required by PolymorphicMatcherWithParam2 but not actually
716/// used. They will always be instantiated with types convertible to
717/// Matcher<T>.
718template <typename T, typename MatcherT1, typename MatcherT2>
719class AnyOfMatcher : public MatcherInterface<T> {
720public:
721  AnyOfMatcher(const Matcher<T> &InnerMatcher1, const Matcher<T> &InnerMatcher2)
722      : InnerMatcher1(InnerMatcher1), InnertMatcher2(InnerMatcher2) {}
723
724  virtual bool matches(const T &Node,
725                       ASTMatchFinder *Finder,
726                       BoundNodesTreeBuilder *Builder) const {
727    return InnerMatcher1.matches(Node, Finder, Builder) ||
728           InnertMatcher2.matches(Node, Finder, Builder);
729  }
730
731private:
732  const Matcher<T> InnerMatcher1;
733  const Matcher<T> InnertMatcher2;
734};
735
736/// \brief Creates a Matcher<T> that matches if
737/// T is dyn_cast'able into InnerT and all inner matchers match.
738///
739/// Returns BindableMatcher, as matchers that use dyn_cast have
740/// the same object both to match on and to run submatchers on,
741/// so there is no ambiguity with what gets bound.
742template<typename T, typename InnerT>
743BindableMatcher<T> makeDynCastAllOfComposite(
744    ArrayRef<const Matcher<InnerT> *> InnerMatchers) {
745  if (InnerMatchers.empty()) {
746    Matcher<InnerT> InnerMatcher = makeMatcher(new TrueMatcher<InnerT>);
747    return BindableMatcher<T>(new DynCastMatcher<T, InnerT>(InnerMatcher));
748  }
749  Matcher<InnerT> InnerMatcher = *InnerMatchers.back();
750  for (int i = InnerMatchers.size() - 2; i >= 0; --i) {
751    InnerMatcher = makeMatcher(
752        new AllOfMatcher<InnerT, Matcher<InnerT>, Matcher<InnerT> >(
753            *InnerMatchers[i], InnerMatcher));
754  }
755  return BindableMatcher<T>(new DynCastMatcher<T, InnerT>(InnerMatcher));
756}
757
758/// \brief Matches nodes of type T that have at least one descendant node of
759/// type DescendantT for which the given inner matcher matches.
760///
761/// DescendantT must be an AST base type.
762template <typename T, typename DescendantT>
763class HasDescendantMatcher : public MatcherInterface<T> {
764  TOOLING_COMPILE_ASSERT(IsBaseType<DescendantT>::value,
765                         has_descendant_only_accepts_base_type_matcher);
766public:
767  explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher)
768      : DescendantMatcher(DescendantMatcher) {}
769
770  virtual bool matches(const T &Node,
771                       ASTMatchFinder *Finder,
772                       BoundNodesTreeBuilder *Builder) const {
773    return Finder->matchesDescendantOf(
774        Node, DescendantMatcher, Builder, ASTMatchFinder::BK_First);
775  }
776
777 private:
778  const TypedBaseMatcher<DescendantT> DescendantMatcher;
779};
780
781/// \brief Matches nodes of type T that have at least one descendant node of
782/// type DescendantT for which the given inner matcher matches.
783///
784/// DescendantT must be an AST base type.
785/// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match
786/// for each descendant node that matches instead of only for the first.
787template <typename T, typename DescendantT>
788class ForEachDescendantMatcher : public MatcherInterface<T> {
789  TOOLING_COMPILE_ASSERT(IsBaseType<DescendantT>::value,
790                         for_each_descendant_only_accepts_base_type_matcher);
791 public:
792  explicit ForEachDescendantMatcher(
793      const Matcher<DescendantT>& DescendantMatcher)
794      : DescendantMatcher(DescendantMatcher) {}
795
796  virtual bool matches(const T& Node,
797                       ASTMatchFinder* Finder,
798                       BoundNodesTreeBuilder* Builder) const {
799    return Finder->matchesDescendantOf(Node, DescendantMatcher, Builder,
800                                       ASTMatchFinder::BK_All);
801  }
802
803private:
804  const TypedBaseMatcher<DescendantT> DescendantMatcher;
805};
806
807/// \brief Matches on nodes that have a getValue() method if getValue() equals
808/// the value the ValueEqualsMatcher was constructed with.
809template <typename T, typename ValueT>
810class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> {
811  TOOLING_COMPILE_ASSERT((llvm::is_base_of<CharacterLiteral, T>::value ||
812                         llvm::is_base_of<CXXBoolLiteralExpr,
813                                          T>::value ||
814                         llvm::is_base_of<FloatingLiteral, T>::value ||
815                         llvm::is_base_of<IntegerLiteral, T>::value),
816                         the_node_must_have_a_getValue_method);
817public:
818  explicit ValueEqualsMatcher(const ValueT &ExpectedValue)
819      : ExpectedValue(ExpectedValue) {}
820
821  virtual bool matchesNode(const T &Node) const {
822    return Node.getValue() == ExpectedValue;
823  }
824
825private:
826  const ValueT ExpectedValue;
827};
828
829template <typename T>
830class IsDefinitionMatcher : public SingleNodeMatcherInterface<T> {
831  TOOLING_COMPILE_ASSERT(
832    (llvm::is_base_of<TagDecl, T>::value) ||
833    (llvm::is_base_of<VarDecl, T>::value) ||
834    (llvm::is_base_of<FunctionDecl, T>::value),
835    is_definition_requires_isThisDeclarationADefinition_method);
836public:
837  virtual bool matchesNode(const T &Node) const {
838    return Node.isThisDeclarationADefinition();
839  }
840};
841
842/// \brief Matches on template instantiations for FunctionDecl, VarDecl or
843/// CXXRecordDecl nodes.
844template <typename T>
845class IsTemplateInstantiationMatcher : public MatcherInterface<T> {
846  TOOLING_COMPILE_ASSERT((llvm::is_base_of<FunctionDecl, T>::value) ||
847                         (llvm::is_base_of<VarDecl, T>::value) ||
848                         (llvm::is_base_of<CXXRecordDecl, T>::value),
849                         requires_getTemplateSpecializationKind_method);
850 public:
851  virtual bool matches(const T& Node,
852                       ASTMatchFinder* Finder,
853                       BoundNodesTreeBuilder* Builder) const {
854    return (Node.getTemplateSpecializationKind() ==
855                TSK_ImplicitInstantiation ||
856            Node.getTemplateSpecializationKind() ==
857                TSK_ExplicitInstantiationDefinition);
858  }
859};
860
861/// \brief Matches on explicit template specializations for FunctionDecl,
862/// VarDecl or CXXRecordDecl nodes.
863template <typename T>
864class IsExplicitTemplateSpecializationMatcher : public MatcherInterface<T> {
865  TOOLING_COMPILE_ASSERT((llvm::is_base_of<FunctionDecl, T>::value) ||
866                         (llvm::is_base_of<VarDecl, T>::value) ||
867                         (llvm::is_base_of<CXXRecordDecl, T>::value),
868                         requires_getTemplateSpecializationKind_method);
869 public:
870  virtual bool matches(const T& Node,
871                       ASTMatchFinder* Finder,
872                       BoundNodesTreeBuilder* Builder) const {
873    return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization);
874  }
875};
876
877
878class IsArrowMatcher : public SingleNodeMatcherInterface<MemberExpr> {
879public:
880  virtual bool matchesNode(const MemberExpr &Node) const {
881    return Node.isArrow();
882  }
883};
884
885class IsConstQualifiedMatcher
886    : public SingleNodeMatcherInterface<QualType> {
887 public:
888  virtual bool matchesNode(const QualType& Node) const {
889    return Node.isConstQualified();
890  }
891};
892
893/// \brief A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a
894/// variadic functor that takes a number of Matcher<TargetT> and returns a
895/// Matcher<SourceT> that matches TargetT nodes that are matched by all of the
896/// given matchers, if SourceT can be dynamically casted into TargetT.
897///
898/// For example:
899///   const VariadicDynCastAllOfMatcher<
900///       Decl, CXXRecordDecl> record;
901/// Creates a functor record(...) that creates a Matcher<Decl> given
902/// a variable number of arguments of type Matcher<CXXRecordDecl>.
903/// The returned matcher matches if the given Decl can by dynamically
904/// casted to CXXRecordDecl and all given matchers match.
905template <typename SourceT, typename TargetT>
906class VariadicDynCastAllOfMatcher
907    : public llvm::VariadicFunction<
908        BindableMatcher<SourceT>, Matcher<TargetT>,
909        makeDynCastAllOfComposite<SourceT, TargetT> > {
910public:
911  VariadicDynCastAllOfMatcher() {}
912};
913
914} // end namespace internal
915} // end namespace ast_matchers
916} // end namespace clang
917
918#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H
919