Home | History | Annotate | Download | only in ASTMatchers
      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_ASTMATCHERS_ASTMATCHERSINTERNAL_H
     36 #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERSINTERNAL_H
     37 
     38 #include "clang/AST/ASTTypeTraits.h"
     39 #include "clang/AST/Decl.h"
     40 #include "clang/AST/DeclCXX.h"
     41 #include "clang/AST/DeclObjC.h"
     42 #include "clang/AST/DeclTemplate.h"
     43 #include "clang/AST/ExprCXX.h"
     44 #include "clang/AST/ExprObjC.h"
     45 #include "clang/AST/Stmt.h"
     46 #include "clang/AST/StmtCXX.h"
     47 #include "clang/AST/StmtObjC.h"
     48 #include "clang/AST/Type.h"
     49 #include "llvm/ADT/Optional.h"
     50 #include "llvm/ADT/VariadicFunction.h"
     51 #include "llvm/Support/ManagedStatic.h"
     52 #include <map>
     53 #include <string>
     54 #include <vector>
     55 
     56 namespace clang {
     57 namespace ast_matchers {
     58 
     59 class BoundNodes;
     60 
     61 namespace internal {
     62 
     63 /// \brief Internal version of BoundNodes. Holds all the bound nodes.
     64 class BoundNodesMap {
     65 public:
     66   /// \brief Adds \c Node to the map with key \c ID.
     67   ///
     68   /// The node's base type should be in NodeBaseType or it will be unaccessible.
     69   void addNode(StringRef ID, const ast_type_traits::DynTypedNode& DynNode) {
     70     NodeMap[ID] = DynNode;
     71   }
     72 
     73   /// \brief Returns the AST node bound to \c ID.
     74   ///
     75   /// Returns NULL if there was no node bound to \c ID or if there is a node but
     76   /// it cannot be converted to the specified type.
     77   template <typename T>
     78   const T *getNodeAs(StringRef ID) const {
     79     IDToNodeMap::const_iterator It = NodeMap.find(ID);
     80     if (It == NodeMap.end()) {
     81       return nullptr;
     82     }
     83     return It->second.get<T>();
     84   }
     85 
     86   ast_type_traits::DynTypedNode getNode(StringRef ID) const {
     87     IDToNodeMap::const_iterator It = NodeMap.find(ID);
     88     if (It == NodeMap.end()) {
     89       return ast_type_traits::DynTypedNode();
     90     }
     91     return It->second;
     92   }
     93 
     94   /// \brief Imposes an order on BoundNodesMaps.
     95   bool operator<(const BoundNodesMap &Other) const {
     96     return NodeMap < Other.NodeMap;
     97   }
     98 
     99   /// \brief A map from IDs to the bound nodes.
    100   ///
    101   /// Note that we're using std::map here, as for memoization:
    102   /// - we need a comparison operator
    103   /// - we need an assignment operator
    104   typedef std::map<std::string, ast_type_traits::DynTypedNode> IDToNodeMap;
    105 
    106   const IDToNodeMap &getMap() const {
    107     return NodeMap;
    108   }
    109 
    110   /// \brief Returns \c true if this \c BoundNodesMap can be compared, i.e. all
    111   /// stored nodes have memoization data.
    112   bool isComparable() const {
    113     for (const auto &IDAndNode : NodeMap) {
    114       if (!IDAndNode.second.getMemoizationData())
    115         return false;
    116     }
    117     return true;
    118   }
    119 
    120 private:
    121   IDToNodeMap NodeMap;
    122 };
    123 
    124 /// \brief Creates BoundNodesTree objects.
    125 ///
    126 /// The tree builder is used during the matching process to insert the bound
    127 /// nodes from the Id matcher.
    128 class BoundNodesTreeBuilder {
    129 public:
    130   /// \brief A visitor interface to visit all BoundNodes results for a
    131   /// BoundNodesTree.
    132   class Visitor {
    133   public:
    134     virtual ~Visitor() {}
    135 
    136     /// \brief Called multiple times during a single call to VisitMatches(...).
    137     ///
    138     /// 'BoundNodesView' contains the bound nodes for a single match.
    139     virtual void visitMatch(const BoundNodes& BoundNodesView) = 0;
    140   };
    141 
    142   /// \brief Add a binding from an id to a node.
    143   void setBinding(StringRef Id, const ast_type_traits::DynTypedNode &DynNode) {
    144     if (Bindings.empty())
    145       Bindings.emplace_back();
    146     for (BoundNodesMap &Binding : Bindings)
    147       Binding.addNode(Id, DynNode);
    148   }
    149 
    150   /// \brief Adds a branch in the tree.
    151   void addMatch(const BoundNodesTreeBuilder &Bindings);
    152 
    153   /// \brief Visits all matches that this BoundNodesTree represents.
    154   ///
    155   /// The ownership of 'ResultVisitor' remains at the caller.
    156   void visitMatches(Visitor* ResultVisitor);
    157 
    158   template <typename ExcludePredicate>
    159   bool removeBindings(const ExcludePredicate &Predicate) {
    160     Bindings.erase(std::remove_if(Bindings.begin(), Bindings.end(), Predicate),
    161                    Bindings.end());
    162     return !Bindings.empty();
    163   }
    164 
    165   /// \brief Imposes an order on BoundNodesTreeBuilders.
    166   bool operator<(const BoundNodesTreeBuilder &Other) const {
    167     return Bindings < Other.Bindings;
    168   }
    169 
    170   /// \brief Returns \c true if this \c BoundNodesTreeBuilder can be compared,
    171   /// i.e. all stored node maps have memoization data.
    172   bool isComparable() const {
    173     for (const BoundNodesMap &NodesMap : Bindings) {
    174       if (!NodesMap.isComparable())
    175         return false;
    176     }
    177     return true;
    178   }
    179 
    180 private:
    181   SmallVector<BoundNodesMap, 16> Bindings;
    182 };
    183 
    184 class ASTMatchFinder;
    185 
    186 /// \brief Generic interface for all matchers.
    187 ///
    188 /// Used by the implementation of Matcher<T> and DynTypedMatcher.
    189 /// In general, implement MatcherInterface<T> or SingleNodeMatcherInterface<T>
    190 /// instead.
    191 class DynMatcherInterface
    192     : public llvm::ThreadSafeRefCountedBase<DynMatcherInterface> {
    193 public:
    194   virtual ~DynMatcherInterface() {}
    195 
    196   /// \brief Returns true if \p DynNode can be matched.
    197   ///
    198   /// May bind \p DynNode to an ID via \p Builder, or recurse into
    199   /// the AST via \p Finder.
    200   virtual bool dynMatches(const ast_type_traits::DynTypedNode &DynNode,
    201                           ASTMatchFinder *Finder,
    202                           BoundNodesTreeBuilder *Builder) const = 0;
    203 };
    204 
    205 /// \brief Generic interface for matchers on an AST node of type T.
    206 ///
    207 /// Implement this if your matcher may need to inspect the children or
    208 /// descendants of the node or bind matched nodes to names. If you are
    209 /// writing a simple matcher that only inspects properties of the
    210 /// current node and doesn't care about its children or descendants,
    211 /// implement SingleNodeMatcherInterface instead.
    212 template <typename T>
    213 class MatcherInterface : public DynMatcherInterface {
    214 public:
    215   /// \brief Returns true if 'Node' can be matched.
    216   ///
    217   /// May bind 'Node' to an ID via 'Builder', or recurse into
    218   /// the AST via 'Finder'.
    219   virtual bool matches(const T &Node,
    220                        ASTMatchFinder *Finder,
    221                        BoundNodesTreeBuilder *Builder) const = 0;
    222 
    223   bool dynMatches(const ast_type_traits::DynTypedNode &DynNode,
    224                   ASTMatchFinder *Finder,
    225                   BoundNodesTreeBuilder *Builder) const override {
    226     return matches(DynNode.getUnchecked<T>(), Finder, Builder);
    227   }
    228 };
    229 
    230 /// \brief Interface for matchers that only evaluate properties on a single
    231 /// node.
    232 template <typename T>
    233 class SingleNodeMatcherInterface : public MatcherInterface<T> {
    234 public:
    235   /// \brief Returns true if the matcher matches the provided node.
    236   ///
    237   /// A subclass must implement this instead of Matches().
    238   virtual bool matchesNode(const T &Node) const = 0;
    239 
    240 private:
    241   /// Implements MatcherInterface::Matches.
    242   bool matches(const T &Node,
    243                ASTMatchFinder * /* Finder */,
    244                BoundNodesTreeBuilder * /*  Builder */) const override {
    245     return matchesNode(Node);
    246   }
    247 };
    248 
    249 template <typename> class Matcher;
    250 
    251 /// \brief Matcher that works on a \c DynTypedNode.
    252 ///
    253 /// It is constructed from a \c Matcher<T> object and redirects most calls to
    254 /// underlying matcher.
    255 /// It checks whether the \c DynTypedNode is convertible into the type of the
    256 /// underlying matcher and then do the actual match on the actual node, or
    257 /// return false if it is not convertible.
    258 class DynTypedMatcher {
    259 public:
    260   /// \brief Takes ownership of the provided implementation pointer.
    261   template <typename T>
    262   DynTypedMatcher(MatcherInterface<T> *Implementation)
    263       : AllowBind(false),
    264         SupportedKind(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()),
    265         RestrictKind(SupportedKind), Implementation(Implementation) {}
    266 
    267   /// \brief Construct from a variadic function.
    268   enum VariadicOperator {
    269     /// \brief Matches nodes for which all provided matchers match.
    270     VO_AllOf,
    271     /// \brief Matches nodes for which at least one of the provided matchers
    272     /// matches.
    273     VO_AnyOf,
    274     /// \brief Matches nodes for which at least one of the provided matchers
    275     /// matches, but doesn't stop at the first match.
    276     VO_EachOf,
    277     /// \brief Matches nodes that do not match the provided matcher.
    278     ///
    279     /// Uses the variadic matcher interface, but fails if
    280     /// InnerMatchers.size() != 1.
    281     VO_UnaryNot
    282   };
    283   static DynTypedMatcher
    284   constructVariadic(VariadicOperator Op,
    285                     ast_type_traits::ASTNodeKind SupportedKind,
    286                     std::vector<DynTypedMatcher> InnerMatchers);
    287 
    288   /// \brief Get a "true" matcher for \p NodeKind.
    289   ///
    290   /// It only checks that the node is of the right kind.
    291   static DynTypedMatcher trueMatcher(ast_type_traits::ASTNodeKind NodeKind);
    292 
    293   void setAllowBind(bool AB) { AllowBind = AB; }
    294 
    295   /// \brief Check whether this matcher could ever match a node of kind \p Kind.
    296   /// \return \c false if this matcher will never match such a node. Otherwise,
    297   /// return \c true.
    298   bool canMatchNodesOfKind(ast_type_traits::ASTNodeKind Kind) const;
    299 
    300   /// \brief Return a matcher that points to the same implementation, but
    301   ///   restricts the node types for \p Kind.
    302   DynTypedMatcher dynCastTo(const ast_type_traits::ASTNodeKind Kind) const;
    303 
    304   /// \brief Returns true if the matcher matches the given \c DynNode.
    305   bool matches(const ast_type_traits::DynTypedNode &DynNode,
    306                ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const;
    307 
    308   /// \brief Same as matches(), but skips the kind check.
    309   ///
    310   /// It is faster, but the caller must ensure the node is valid for the
    311   /// kind of this matcher.
    312   bool matchesNoKindCheck(const ast_type_traits::DynTypedNode &DynNode,
    313                           ASTMatchFinder *Finder,
    314                           BoundNodesTreeBuilder *Builder) const;
    315 
    316   /// \brief Bind the specified \p ID to the matcher.
    317   /// \return A new matcher with the \p ID bound to it if this matcher supports
    318   ///   binding. Otherwise, returns an empty \c Optional<>.
    319   llvm::Optional<DynTypedMatcher> tryBind(StringRef ID) const;
    320 
    321   /// \brief Returns a unique \p ID for the matcher.
    322   ///
    323   /// Casting a Matcher<T> to Matcher<U> creates a matcher that has the
    324   /// same \c Implementation pointer, but different \c RestrictKind. We need to
    325   /// include both in the ID to make it unique.
    326   ///
    327   /// \c MatcherIDType supports operator< and provides strict weak ordering.
    328   typedef std::pair<ast_type_traits::ASTNodeKind, uint64_t> MatcherIDType;
    329   MatcherIDType getID() const {
    330     /// FIXME: Document the requirements this imposes on matcher
    331     /// implementations (no new() implementation_ during a Matches()).
    332     return std::make_pair(RestrictKind,
    333                           reinterpret_cast<uint64_t>(Implementation.get()));
    334   }
    335 
    336   /// \brief Returns the type this matcher works on.
    337   ///
    338   /// \c matches() will always return false unless the node passed is of this
    339   /// or a derived type.
    340   ast_type_traits::ASTNodeKind getSupportedKind() const {
    341     return SupportedKind;
    342   }
    343 
    344   /// \brief Returns \c true if the passed \c DynTypedMatcher can be converted
    345   ///   to a \c Matcher<T>.
    346   ///
    347   /// This method verifies that the underlying matcher in \c Other can process
    348   /// nodes of types T.
    349   template <typename T> bool canConvertTo() const {
    350     return canConvertTo(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
    351   }
    352   bool canConvertTo(ast_type_traits::ASTNodeKind To) const;
    353 
    354   /// \brief Construct a \c Matcher<T> interface around the dynamic matcher.
    355   ///
    356   /// This method asserts that \c canConvertTo() is \c true. Callers
    357   /// should call \c canConvertTo() first to make sure that \c this is
    358   /// compatible with T.
    359   template <typename T> Matcher<T> convertTo() const {
    360     assert(canConvertTo<T>());
    361     return unconditionalConvertTo<T>();
    362   }
    363 
    364   /// \brief Same as \c convertTo(), but does not check that the underlying
    365   ///   matcher can handle a value of T.
    366   ///
    367   /// If it is not compatible, then this matcher will never match anything.
    368   template <typename T> Matcher<T> unconditionalConvertTo() const;
    369 
    370 private:
    371  DynTypedMatcher(ast_type_traits::ASTNodeKind SupportedKind,
    372                  ast_type_traits::ASTNodeKind RestrictKind,
    373                  IntrusiveRefCntPtr<DynMatcherInterface> Implementation)
    374      : AllowBind(false),
    375        SupportedKind(SupportedKind),
    376        RestrictKind(RestrictKind),
    377        Implementation(std::move(Implementation)) {}
    378 
    379   bool AllowBind;
    380   ast_type_traits::ASTNodeKind SupportedKind;
    381   /// \brief A potentially stricter node kind.
    382   ///
    383   /// It allows to perform implicit and dynamic cast of matchers without
    384   /// needing to change \c Implementation.
    385   ast_type_traits::ASTNodeKind RestrictKind;
    386   IntrusiveRefCntPtr<DynMatcherInterface> Implementation;
    387 };
    388 
    389 /// \brief Wrapper base class for a wrapping matcher.
    390 ///
    391 /// This is just a container for a DynTypedMatcher that can be used as a base
    392 /// class for another matcher.
    393 template <typename T>
    394 class WrapperMatcherInterface : public MatcherInterface<T> {
    395 protected:
    396   explicit WrapperMatcherInterface(DynTypedMatcher &&InnerMatcher)
    397       : InnerMatcher(std::move(InnerMatcher)) {}
    398 
    399   const DynTypedMatcher InnerMatcher;
    400 };
    401 
    402 /// \brief Wrapper of a MatcherInterface<T> *that allows copying.
    403 ///
    404 /// A Matcher<Base> can be used anywhere a Matcher<Derived> is
    405 /// required. This establishes an is-a relationship which is reverse
    406 /// to the AST hierarchy. In other words, Matcher<T> is contravariant
    407 /// with respect to T. The relationship is built via a type conversion
    408 /// operator rather than a type hierarchy to be able to templatize the
    409 /// type hierarchy instead of spelling it out.
    410 template <typename T>
    411 class Matcher {
    412 public:
    413   /// \brief Takes ownership of the provided implementation pointer.
    414   explicit Matcher(MatcherInterface<T> *Implementation)
    415       : Implementation(Implementation) {}
    416 
    417   /// \brief Implicitly converts \c Other to a Matcher<T>.
    418   ///
    419   /// Requires \c T to be derived from \c From.
    420   template <typename From>
    421   Matcher(const Matcher<From> &Other,
    422           typename std::enable_if<std::is_base_of<From, T>::value &&
    423                                   !std::is_same<From, T>::value>::type * = 0)
    424       : Implementation(restrictMatcher(Other.Implementation)) {
    425     assert(Implementation.getSupportedKind().isSame(
    426         ast_type_traits::ASTNodeKind::getFromNodeKind<T>()));
    427   }
    428 
    429   /// \brief Implicitly converts \c Matcher<Type> to \c Matcher<QualType>.
    430   ///
    431   /// The resulting matcher is not strict, i.e. ignores qualifiers.
    432   template <typename TypeT>
    433   Matcher(const Matcher<TypeT> &Other,
    434           typename std::enable_if<
    435             std::is_same<T, QualType>::value &&
    436             std::is_same<TypeT, Type>::value>::type* = 0)
    437       : Implementation(new TypeToQualType<TypeT>(Other)) {}
    438 
    439   /// \brief Convert \c this into a \c Matcher<T> by applying dyn_cast<> to the
    440   /// argument.
    441   /// \c To must be a base class of \c T.
    442   template <typename To>
    443   Matcher<To> dynCastTo() const {
    444     static_assert(std::is_base_of<To, T>::value, "Invalid dynCast call.");
    445     return Matcher<To>(Implementation);
    446   }
    447 
    448   /// \brief Forwards the call to the underlying MatcherInterface<T> pointer.
    449   bool matches(const T &Node,
    450                ASTMatchFinder *Finder,
    451                BoundNodesTreeBuilder *Builder) const {
    452     return Implementation.matches(ast_type_traits::DynTypedNode::create(Node),
    453                                   Finder, Builder);
    454   }
    455 
    456   /// \brief Returns an ID that uniquely identifies the matcher.
    457   DynTypedMatcher::MatcherIDType getID() const {
    458     return Implementation.getID();
    459   }
    460 
    461   /// \brief Extract the dynamic matcher.
    462   ///
    463   /// The returned matcher keeps the same restrictions as \c this and remembers
    464   /// that it is meant to support nodes of type \c T.
    465   operator DynTypedMatcher() const { return Implementation; }
    466 
    467   /// \brief Allows the conversion of a \c Matcher<Type> to a \c
    468   /// Matcher<QualType>.
    469   ///
    470   /// Depending on the constructor argument, the matcher is either strict, i.e.
    471   /// does only matches in the absence of qualifiers, or not, i.e. simply
    472   /// ignores any qualifiers.
    473   template <typename TypeT>
    474   class TypeToQualType : public WrapperMatcherInterface<QualType> {
    475   public:
    476     TypeToQualType(const Matcher<TypeT> &InnerMatcher)
    477         : TypeToQualType::WrapperMatcherInterface(InnerMatcher) {}
    478 
    479     bool matches(const QualType &Node, ASTMatchFinder *Finder,
    480                  BoundNodesTreeBuilder *Builder) const override {
    481       if (Node.isNull())
    482         return false;
    483       return this->InnerMatcher.matches(
    484           ast_type_traits::DynTypedNode::create(*Node), Finder, Builder);
    485     }
    486   };
    487 
    488 private:
    489   // For Matcher<T> <=> Matcher<U> conversions.
    490   template <typename U> friend class Matcher;
    491   // For DynTypedMatcher::unconditionalConvertTo<T>.
    492   friend class DynTypedMatcher;
    493 
    494   static DynTypedMatcher restrictMatcher(const DynTypedMatcher &Other) {
    495     return Other.dynCastTo(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
    496   }
    497 
    498   explicit Matcher(const DynTypedMatcher &Implementation)
    499       : Implementation(restrictMatcher(Implementation)) {
    500     assert(this->Implementation.getSupportedKind()
    501                .isSame(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()));
    502   }
    503 
    504   DynTypedMatcher Implementation;
    505 };  // class Matcher
    506 
    507 /// \brief A convenient helper for creating a Matcher<T> without specifying
    508 /// the template type argument.
    509 template <typename T>
    510 inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) {
    511   return Matcher<T>(Implementation);
    512 }
    513 
    514 /// \brief Specialization of the conversion functions for QualType.
    515 ///
    516 /// This specialization provides the Matcher<Type>->Matcher<QualType>
    517 /// conversion that the static API does.
    518 template <>
    519 inline Matcher<QualType> DynTypedMatcher::convertTo<QualType>() const {
    520   assert(canConvertTo<QualType>());
    521   const ast_type_traits::ASTNodeKind SourceKind = getSupportedKind();
    522   if (SourceKind.isSame(
    523           ast_type_traits::ASTNodeKind::getFromNodeKind<Type>())) {
    524     // We support implicit conversion from Matcher<Type> to Matcher<QualType>
    525     return unconditionalConvertTo<Type>();
    526   }
    527   return unconditionalConvertTo<QualType>();
    528 }
    529 
    530 /// \brief Finds the first node in a range that matches the given matcher.
    531 template <typename MatcherT, typename IteratorT>
    532 bool matchesFirstInRange(const MatcherT &Matcher, IteratorT Start,
    533                          IteratorT End, ASTMatchFinder *Finder,
    534                          BoundNodesTreeBuilder *Builder) {
    535   for (IteratorT I = Start; I != End; ++I) {
    536     BoundNodesTreeBuilder Result(*Builder);
    537     if (Matcher.matches(*I, Finder, &Result)) {
    538       *Builder = std::move(Result);
    539       return true;
    540     }
    541   }
    542   return false;
    543 }
    544 
    545 /// \brief Finds the first node in a pointer range that matches the given
    546 /// matcher.
    547 template <typename MatcherT, typename IteratorT>
    548 bool matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start,
    549                                 IteratorT End, ASTMatchFinder *Finder,
    550                                 BoundNodesTreeBuilder *Builder) {
    551   for (IteratorT I = Start; I != End; ++I) {
    552     BoundNodesTreeBuilder Result(*Builder);
    553     if (Matcher.matches(**I, Finder, &Result)) {
    554       *Builder = std::move(Result);
    555       return true;
    556     }
    557   }
    558   return false;
    559 }
    560 
    561 /// \brief Metafunction to determine if type T has a member called getDecl.
    562 template <typename T> struct has_getDecl {
    563   struct Default { int getDecl; };
    564   struct Derived : T, Default { };
    565 
    566   template<typename C, C> struct CheckT;
    567 
    568   // If T::getDecl exists, an ambiguity arises and CheckT will
    569   // not be instantiable. This makes f(...) the only available
    570   // overload.
    571   template<typename C>
    572   static char (&f(CheckT<int Default::*, &C::getDecl>*))[1];
    573   template<typename C> static char (&f(...))[2];
    574 
    575   static bool const value = sizeof(f<Derived>(nullptr)) == 2;
    576 };
    577 
    578 /// \brief Matches overloaded operators with a specific name.
    579 ///
    580 /// The type argument ArgT is not used by this matcher but is used by
    581 /// PolymorphicMatcherWithParam1 and should be StringRef.
    582 template <typename T, typename ArgT>
    583 class HasOverloadedOperatorNameMatcher : public SingleNodeMatcherInterface<T> {
    584   static_assert(std::is_same<T, CXXOperatorCallExpr>::value ||
    585                 std::is_base_of<FunctionDecl, T>::value,
    586                 "unsupported class for matcher");
    587   static_assert(std::is_same<ArgT, StringRef>::value,
    588                 "argument type must be StringRef");
    589 
    590 public:
    591   explicit HasOverloadedOperatorNameMatcher(const StringRef Name)
    592       : SingleNodeMatcherInterface<T>(), Name(Name) {}
    593 
    594   bool matchesNode(const T &Node) const override {
    595     return matchesSpecialized(Node);
    596   }
    597 
    598 private:
    599 
    600   /// \brief CXXOperatorCallExpr exist only for calls to overloaded operators
    601   /// so this function returns true if the call is to an operator of the given
    602   /// name.
    603   bool matchesSpecialized(const CXXOperatorCallExpr &Node) const {
    604     return getOperatorSpelling(Node.getOperator()) == Name;
    605   }
    606 
    607   /// \brief Returns true only if CXXMethodDecl represents an overloaded
    608   /// operator and has the given operator name.
    609   bool matchesSpecialized(const FunctionDecl &Node) const {
    610     return Node.isOverloadedOperator() &&
    611            getOperatorSpelling(Node.getOverloadedOperator()) == Name;
    612   }
    613 
    614   std::string Name;
    615 };
    616 
    617 /// \brief Matches named declarations with a specific name.
    618 ///
    619 /// See \c hasName() in ASTMatchers.h for details.
    620 class HasNameMatcher : public SingleNodeMatcherInterface<NamedDecl> {
    621  public:
    622   explicit HasNameMatcher(StringRef Name);
    623 
    624   bool matchesNode(const NamedDecl &Node) const override;
    625 
    626  private:
    627   /// \brief Unqualified match routine.
    628   ///
    629   /// It is much faster than the full match, but it only works for unqualified
    630   /// matches.
    631   bool matchesNodeUnqualified(const NamedDecl &Node) const;
    632 
    633   /// \brief Full match routine
    634   ///
    635   /// It generates the fully qualified name of the declaration (which is
    636   /// expensive) before trying to match.
    637   /// It is slower but simple and works on all cases.
    638   bool matchesNodeFull(const NamedDecl &Node) const;
    639 
    640   const bool UseUnqualifiedMatch;
    641   const std::string Name;
    642 };
    643 
    644 /// \brief Matches declarations for QualType and CallExpr.
    645 ///
    646 /// Type argument DeclMatcherT is required by PolymorphicMatcherWithParam1 but
    647 /// not actually used.
    648 template <typename T, typename DeclMatcherT>
    649 class HasDeclarationMatcher : public WrapperMatcherInterface<T> {
    650   static_assert(std::is_same<DeclMatcherT, Matcher<Decl>>::value,
    651                 "instantiated with wrong types");
    652 
    653 public:
    654   explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher)
    655       : HasDeclarationMatcher::WrapperMatcherInterface(InnerMatcher) {}
    656 
    657   bool matches(const T &Node, ASTMatchFinder *Finder,
    658                BoundNodesTreeBuilder *Builder) const override {
    659     return matchesSpecialized(Node, Finder, Builder);
    660   }
    661 
    662 private:
    663   /// \brief If getDecl exists as a member of U, returns whether the inner
    664   /// matcher matches Node.getDecl().
    665   template <typename U>
    666   bool matchesSpecialized(
    667       const U &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder,
    668       typename std::enable_if<has_getDecl<U>::value, int>::type = 0) const {
    669     return matchesDecl(Node.getDecl(), Finder, Builder);
    670   }
    671 
    672   /// \brief Extracts the TagDecl of a QualType and returns whether the inner
    673   /// matcher matches on it.
    674   bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder,
    675                           BoundNodesTreeBuilder *Builder) const {
    676     if (Node.isNull())
    677       return false;
    678 
    679     if (auto *TD = Node->getAsTagDecl())
    680       return matchesDecl(TD, Finder, Builder);
    681     else if (auto *TT = Node->getAs<TypedefType>())
    682       return matchesDecl(TT->getDecl(), Finder, Builder);
    683     // Do not use getAs<TemplateTypeParmType> instead of the direct dyn_cast.
    684     // Calling getAs will return the canonical type, but that type does not
    685     // store a TemplateTypeParmDecl. We *need* the uncanonical type, if it is
    686     // available, and using dyn_cast ensures that.
    687     else if (auto *TTP = dyn_cast<TemplateTypeParmType>(Node.getTypePtr()))
    688       return matchesDecl(TTP->getDecl(), Finder, Builder);
    689     else if (auto *OCIT = Node->getAs<ObjCInterfaceType>())
    690       return matchesDecl(OCIT->getDecl(), Finder, Builder);
    691     else if (auto *UUT = Node->getAs<UnresolvedUsingType>())
    692       return matchesDecl(UUT->getDecl(), Finder, Builder);
    693     else if (auto *ICNT = Node->getAs<InjectedClassNameType>())
    694       return matchesDecl(ICNT->getDecl(), Finder, Builder);
    695     return false;
    696   }
    697 
    698   /// \brief Gets the TemplateDecl from a TemplateSpecializationType
    699   /// and returns whether the inner matches on it.
    700   bool matchesSpecialized(const TemplateSpecializationType &Node,
    701                           ASTMatchFinder *Finder,
    702                           BoundNodesTreeBuilder *Builder) const {
    703     return matchesDecl(Node.getTemplateName().getAsTemplateDecl(),
    704                        Finder, Builder);
    705   }
    706 
    707   /// \brief Extracts the Decl of the callee of a CallExpr and returns whether
    708   /// the inner matcher matches on it.
    709   bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder,
    710                           BoundNodesTreeBuilder *Builder) const {
    711     return matchesDecl(Node.getCalleeDecl(), Finder, Builder);
    712   }
    713 
    714   /// \brief Extracts the Decl of the constructor call and returns whether the
    715   /// inner matcher matches on it.
    716   bool matchesSpecialized(const CXXConstructExpr &Node,
    717                           ASTMatchFinder *Finder,
    718                           BoundNodesTreeBuilder *Builder) const {
    719     return matchesDecl(Node.getConstructor(), Finder, Builder);
    720   }
    721 
    722   /// \brief Extracts the \c ValueDecl a \c MemberExpr refers to and returns
    723   /// whether the inner matcher matches on it.
    724   bool matchesSpecialized(const MemberExpr &Node,
    725                           ASTMatchFinder *Finder,
    726                           BoundNodesTreeBuilder *Builder) const {
    727     return matchesDecl(Node.getMemberDecl(), Finder, Builder);
    728   }
    729 
    730   /// \brief Returns whether the inner matcher \c Node. Returns false if \c Node
    731   /// is \c NULL.
    732   bool matchesDecl(const Decl *Node, ASTMatchFinder *Finder,
    733                    BoundNodesTreeBuilder *Builder) const {
    734     return Node != nullptr &&
    735            this->InnerMatcher.matches(
    736                ast_type_traits::DynTypedNode::create(*Node), Finder, Builder);
    737   }
    738 };
    739 
    740 /// \brief IsBaseType<T>::value is true if T is a "base" type in the AST
    741 /// node class hierarchies.
    742 template <typename T>
    743 struct IsBaseType {
    744   static const bool value =
    745       std::is_same<T, Decl>::value ||
    746       std::is_same<T, Stmt>::value ||
    747       std::is_same<T, QualType>::value ||
    748       std::is_same<T, Type>::value ||
    749       std::is_same<T, TypeLoc>::value ||
    750       std::is_same<T, NestedNameSpecifier>::value ||
    751       std::is_same<T, NestedNameSpecifierLoc>::value ||
    752       std::is_same<T, CXXCtorInitializer>::value;
    753 };
    754 template <typename T>
    755 const bool IsBaseType<T>::value;
    756 
    757 /// \brief Interface that allows matchers to traverse the AST.
    758 /// FIXME: Find a better name.
    759 ///
    760 /// This provides three entry methods for each base node type in the AST:
    761 /// - \c matchesChildOf:
    762 ///   Matches a matcher on every child node of the given node. Returns true
    763 ///   if at least one child node could be matched.
    764 /// - \c matchesDescendantOf:
    765 ///   Matches a matcher on all descendant nodes of the given node. Returns true
    766 ///   if at least one descendant matched.
    767 /// - \c matchesAncestorOf:
    768 ///   Matches a matcher on all ancestors of the given node. Returns true if
    769 ///   at least one ancestor matched.
    770 ///
    771 /// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal.
    772 /// In the future, we want to implement this for all nodes for which it makes
    773 /// sense. In the case of matchesAncestorOf, we'll want to implement it for
    774 /// all nodes, as all nodes have ancestors.
    775 class ASTMatchFinder {
    776 public:
    777   /// \brief Defines how we descend a level in the AST when we pass
    778   /// through expressions.
    779   enum TraversalKind {
    780     /// Will traverse any child nodes.
    781     TK_AsIs,
    782     /// Will not traverse implicit casts and parentheses.
    783     TK_IgnoreImplicitCastsAndParentheses
    784   };
    785 
    786   /// \brief Defines how bindings are processed on recursive matches.
    787   enum BindKind {
    788     /// Stop at the first match and only bind the first match.
    789     BK_First,
    790     /// Create results for all combinations of bindings that match.
    791     BK_All
    792   };
    793 
    794   /// \brief Defines which ancestors are considered for a match.
    795   enum AncestorMatchMode {
    796     /// All ancestors.
    797     AMM_All,
    798     /// Direct parent only.
    799     AMM_ParentOnly
    800   };
    801 
    802   virtual ~ASTMatchFinder() {}
    803 
    804   /// \brief Returns true if the given class is directly or indirectly derived
    805   /// from a base type matching \c base.
    806   ///
    807   /// A class is considered to be also derived from itself.
    808   virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
    809                                   const Matcher<NamedDecl> &Base,
    810                                   BoundNodesTreeBuilder *Builder) = 0;
    811 
    812   template <typename T>
    813   bool matchesChildOf(const T &Node,
    814                       const DynTypedMatcher &Matcher,
    815                       BoundNodesTreeBuilder *Builder,
    816                       TraversalKind Traverse,
    817                       BindKind Bind) {
    818     static_assert(std::is_base_of<Decl, T>::value ||
    819                   std::is_base_of<Stmt, T>::value ||
    820                   std::is_base_of<NestedNameSpecifier, T>::value ||
    821                   std::is_base_of<NestedNameSpecifierLoc, T>::value ||
    822                   std::is_base_of<TypeLoc, T>::value ||
    823                   std::is_base_of<QualType, T>::value,
    824                   "unsupported type for recursive matching");
    825    return matchesChildOf(ast_type_traits::DynTypedNode::create(Node),
    826                           Matcher, Builder, Traverse, Bind);
    827   }
    828 
    829   template <typename T>
    830   bool matchesDescendantOf(const T &Node,
    831                            const DynTypedMatcher &Matcher,
    832                            BoundNodesTreeBuilder *Builder,
    833                            BindKind Bind) {
    834     static_assert(std::is_base_of<Decl, T>::value ||
    835                   std::is_base_of<Stmt, T>::value ||
    836                   std::is_base_of<NestedNameSpecifier, T>::value ||
    837                   std::is_base_of<NestedNameSpecifierLoc, T>::value ||
    838                   std::is_base_of<TypeLoc, T>::value ||
    839                   std::is_base_of<QualType, T>::value,
    840                   "unsupported type for recursive matching");
    841     return matchesDescendantOf(ast_type_traits::DynTypedNode::create(Node),
    842                                Matcher, Builder, Bind);
    843   }
    844 
    845   // FIXME: Implement support for BindKind.
    846   template <typename T>
    847   bool matchesAncestorOf(const T &Node,
    848                          const DynTypedMatcher &Matcher,
    849                          BoundNodesTreeBuilder *Builder,
    850                          AncestorMatchMode MatchMode) {
    851     static_assert(std::is_base_of<Decl, T>::value ||
    852                       std::is_base_of<NestedNameSpecifierLoc, T>::value ||
    853                       std::is_base_of<Stmt, T>::value ||
    854                       std::is_base_of<TypeLoc, T>::value,
    855                   "type not allowed for recursive matching");
    856     return matchesAncestorOf(ast_type_traits::DynTypedNode::create(Node),
    857                              Matcher, Builder, MatchMode);
    858   }
    859 
    860   virtual ASTContext &getASTContext() const = 0;
    861 
    862 protected:
    863   virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node,
    864                               const DynTypedMatcher &Matcher,
    865                               BoundNodesTreeBuilder *Builder,
    866                               TraversalKind Traverse,
    867                               BindKind Bind) = 0;
    868 
    869   virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node,
    870                                    const DynTypedMatcher &Matcher,
    871                                    BoundNodesTreeBuilder *Builder,
    872                                    BindKind Bind) = 0;
    873 
    874   virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node,
    875                                  const DynTypedMatcher &Matcher,
    876                                  BoundNodesTreeBuilder *Builder,
    877                                  AncestorMatchMode MatchMode) = 0;
    878 };
    879 
    880 /// \brief A type-list implementation.
    881 ///
    882 /// A "linked list" of types, accessible by using the ::head and ::tail
    883 /// typedefs.
    884 template <typename... Ts> struct TypeList {}; // Empty sentinel type list.
    885 
    886 template <typename T1, typename... Ts> struct TypeList<T1, Ts...> {
    887   /// \brief The first type on the list.
    888   typedef T1 head;
    889 
    890   /// \brief A sublist with the tail. ie everything but the head.
    891   ///
    892   /// This type is used to do recursion. TypeList<>/EmptyTypeList indicates the
    893   /// end of the list.
    894   typedef TypeList<Ts...> tail;
    895 };
    896 
    897 /// \brief The empty type list.
    898 typedef TypeList<> EmptyTypeList;
    899 
    900 /// \brief Helper meta-function to determine if some type \c T is present or
    901 ///   a parent type in the list.
    902 template <typename AnyTypeList, typename T>
    903 struct TypeListContainsSuperOf {
    904   static const bool value =
    905       std::is_base_of<typename AnyTypeList::head, T>::value ||
    906       TypeListContainsSuperOf<typename AnyTypeList::tail, T>::value;
    907 };
    908 template <typename T>
    909 struct TypeListContainsSuperOf<EmptyTypeList, T> {
    910   static const bool value = false;
    911 };
    912 
    913 /// \brief A "type list" that contains all types.
    914 ///
    915 /// Useful for matchers like \c anything and \c unless.
    916 typedef TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc,
    917                  QualType, Type, TypeLoc, CXXCtorInitializer> AllNodeBaseTypes;
    918 
    919 /// \brief Helper meta-function to extract the argument out of a function of
    920 ///   type void(Arg).
    921 ///
    922 /// See AST_POLYMORPHIC_SUPPORTED_TYPES for details.
    923 template <class T> struct ExtractFunctionArgMeta;
    924 template <class T> struct ExtractFunctionArgMeta<void(T)> {
    925   typedef T type;
    926 };
    927 
    928 /// \brief Default type lists for ArgumentAdaptingMatcher matchers.
    929 typedef AllNodeBaseTypes AdaptativeDefaultFromTypes;
    930 typedef TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc,
    931                  TypeLoc, QualType> AdaptativeDefaultToTypes;
    932 
    933 /// \brief All types that are supported by HasDeclarationMatcher above.
    934 typedef TypeList<CallExpr, CXXConstructExpr, DeclRefExpr, EnumType,
    935                  InjectedClassNameType, LabelStmt, MemberExpr, QualType,
    936                  RecordType, TagType, TemplateSpecializationType,
    937                  TemplateTypeParmType, TypedefType,
    938                  UnresolvedUsingType> HasDeclarationSupportedTypes;
    939 
    940 /// \brief Converts a \c Matcher<T> to a matcher of desired type \c To by
    941 /// "adapting" a \c To into a \c T.
    942 ///
    943 /// The \c ArgumentAdapterT argument specifies how the adaptation is done.
    944 ///
    945 /// For example:
    946 ///   \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher);
    947 /// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher
    948 /// that is convertible into any matcher of type \c To by constructing
    949 /// \c HasMatcher<To, T>(InnerMatcher).
    950 ///
    951 /// If a matcher does not need knowledge about the inner type, prefer to use
    952 /// PolymorphicMatcherWithParam1.
    953 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
    954           typename FromTypes = AdaptativeDefaultFromTypes,
    955           typename ToTypes = AdaptativeDefaultToTypes>
    956 struct ArgumentAdaptingMatcherFunc {
    957   template <typename T> class Adaptor {
    958   public:
    959     explicit Adaptor(const Matcher<T> &InnerMatcher)
    960         : InnerMatcher(InnerMatcher) {}
    961 
    962     typedef ToTypes ReturnTypes;
    963 
    964     template <typename To> operator Matcher<To>() const {
    965       return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher));
    966     }
    967 
    968   private:
    969     const Matcher<T> InnerMatcher;
    970   };
    971 
    972   template <typename T>
    973   static Adaptor<T> create(const Matcher<T> &InnerMatcher) {
    974     return Adaptor<T>(InnerMatcher);
    975   }
    976 
    977   template <typename T>
    978   Adaptor<T> operator()(const Matcher<T> &InnerMatcher) const {
    979     return create(InnerMatcher);
    980   }
    981 };
    982 
    983 /// \brief A PolymorphicMatcherWithParamN<MatcherT, P1, ..., PN> object can be
    984 /// created from N parameters p1, ..., pN (of type P1, ..., PN) and
    985 /// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN)
    986 /// can be constructed.
    987 ///
    988 /// For example:
    989 /// - PolymorphicMatcherWithParam0<IsDefinitionMatcher>()
    990 ///   creates an object that can be used as a Matcher<T> for any type T
    991 ///   where an IsDefinitionMatcher<T>() can be constructed.
    992 /// - PolymorphicMatcherWithParam1<ValueEqualsMatcher, int>(42)
    993 ///   creates an object that can be used as a Matcher<T> for any type T
    994 ///   where a ValueEqualsMatcher<T, int>(42) can be constructed.
    995 template <template <typename T> class MatcherT,
    996           typename ReturnTypesF = void(AllNodeBaseTypes)>
    997 class PolymorphicMatcherWithParam0 {
    998 public:
    999   typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
   1000   template <typename T>
   1001   operator Matcher<T>() const {
   1002     static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
   1003                   "right polymorphic conversion");
   1004     return Matcher<T>(new MatcherT<T>());
   1005   }
   1006 };
   1007 
   1008 template <template <typename T, typename P1> class MatcherT,
   1009           typename P1,
   1010           typename ReturnTypesF = void(AllNodeBaseTypes)>
   1011 class PolymorphicMatcherWithParam1 {
   1012 public:
   1013   explicit PolymorphicMatcherWithParam1(const P1 &Param1)
   1014       : Param1(Param1) {}
   1015 
   1016   typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
   1017 
   1018   template <typename T>
   1019   operator Matcher<T>() const {
   1020     static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
   1021                   "right polymorphic conversion");
   1022     return Matcher<T>(new MatcherT<T, P1>(Param1));
   1023   }
   1024 
   1025 private:
   1026   const P1 Param1;
   1027 };
   1028 
   1029 template <template <typename T, typename P1, typename P2> class MatcherT,
   1030           typename P1, typename P2,
   1031           typename ReturnTypesF = void(AllNodeBaseTypes)>
   1032 class PolymorphicMatcherWithParam2 {
   1033 public:
   1034   PolymorphicMatcherWithParam2(const P1 &Param1, const P2 &Param2)
   1035       : Param1(Param1), Param2(Param2) {}
   1036 
   1037   typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
   1038 
   1039   template <typename T>
   1040   operator Matcher<T>() const {
   1041     static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
   1042                   "right polymorphic conversion");
   1043     return Matcher<T>(new MatcherT<T, P1, P2>(Param1, Param2));
   1044   }
   1045 
   1046 private:
   1047   const P1 Param1;
   1048   const P2 Param2;
   1049 };
   1050 
   1051 /// \brief Matches any instance of the given NodeType.
   1052 ///
   1053 /// This is useful when a matcher syntactically requires a child matcher,
   1054 /// but the context doesn't care. See for example: anything().
   1055 class TrueMatcher {
   1056  public:
   1057   typedef AllNodeBaseTypes ReturnTypes;
   1058 
   1059   template <typename T>
   1060   operator Matcher<T>() const {
   1061     return DynTypedMatcher::trueMatcher(
   1062                ast_type_traits::ASTNodeKind::getFromNodeKind<T>())
   1063         .template unconditionalConvertTo<T>();
   1064   }
   1065 };
   1066 
   1067 /// \brief A Matcher that allows binding the node it matches to an id.
   1068 ///
   1069 /// BindableMatcher provides a \a bind() method that allows binding the
   1070 /// matched node to an id if the match was successful.
   1071 template <typename T>
   1072 class BindableMatcher : public Matcher<T> {
   1073 public:
   1074   explicit BindableMatcher(const Matcher<T> &M) : Matcher<T>(M) {}
   1075   explicit BindableMatcher(MatcherInterface<T> *Implementation)
   1076     : Matcher<T>(Implementation) {}
   1077 
   1078   /// \brief Returns a matcher that will bind the matched node on a match.
   1079   ///
   1080   /// The returned matcher is equivalent to this matcher, but will
   1081   /// bind the matched node on a match.
   1082   Matcher<T> bind(StringRef ID) const {
   1083     return DynTypedMatcher(*this)
   1084         .tryBind(ID)
   1085         ->template unconditionalConvertTo<T>();
   1086   }
   1087 
   1088   /// \brief Same as Matcher<T>'s conversion operator, but enables binding on
   1089   /// the returned matcher.
   1090   operator DynTypedMatcher() const {
   1091     DynTypedMatcher Result = static_cast<const Matcher<T>&>(*this);
   1092     Result.setAllowBind(true);
   1093     return Result;
   1094   }
   1095 };
   1096 
   1097 /// \brief Matches nodes of type T that have child nodes of type ChildT for
   1098 /// which a specified child matcher matches.
   1099 ///
   1100 /// ChildT must be an AST base type.
   1101 template <typename T, typename ChildT>
   1102 class HasMatcher : public WrapperMatcherInterface<T> {
   1103   static_assert(IsBaseType<ChildT>::value,
   1104                 "has only accepts base type matcher");
   1105 
   1106 public:
   1107   explicit HasMatcher(const Matcher<ChildT> &ChildMatcher)
   1108       : HasMatcher::WrapperMatcherInterface(ChildMatcher) {}
   1109 
   1110   bool matches(const T &Node, ASTMatchFinder *Finder,
   1111                BoundNodesTreeBuilder *Builder) const override {
   1112     return Finder->matchesChildOf(
   1113         Node, this->InnerMatcher, Builder,
   1114         ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
   1115         ASTMatchFinder::BK_First);
   1116   }
   1117 };
   1118 
   1119 /// \brief Matches nodes of type T that have child nodes of type ChildT for
   1120 /// which a specified child matcher matches. ChildT must be an AST base
   1121 /// type.
   1122 /// As opposed to the HasMatcher, the ForEachMatcher will produce a match
   1123 /// for each child that matches.
   1124 template <typename T, typename ChildT>
   1125 class ForEachMatcher : public WrapperMatcherInterface<T> {
   1126   static_assert(IsBaseType<ChildT>::value,
   1127                 "for each only accepts base type matcher");
   1128 
   1129  public:
   1130    explicit ForEachMatcher(const Matcher<ChildT> &ChildMatcher)
   1131        : ForEachMatcher::WrapperMatcherInterface(ChildMatcher) {}
   1132 
   1133   bool matches(const T& Node, ASTMatchFinder* Finder,
   1134                BoundNodesTreeBuilder* Builder) const override {
   1135     return Finder->matchesChildOf(
   1136         Node, this->InnerMatcher, Builder,
   1137         ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
   1138         ASTMatchFinder::BK_All);
   1139   }
   1140 };
   1141 
   1142 /// \brief VariadicOperatorMatcher related types.
   1143 /// @{
   1144 
   1145 /// \brief Polymorphic matcher object that uses a \c
   1146 /// DynTypedMatcher::VariadicOperator operator.
   1147 ///
   1148 /// Input matchers can have any type (including other polymorphic matcher
   1149 /// types), and the actual Matcher<T> is generated on demand with an implicit
   1150 /// coversion operator.
   1151 template <typename... Ps> class VariadicOperatorMatcher {
   1152 public:
   1153   VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op, Ps &&... Params)
   1154       : Op(Op), Params(std::forward<Ps>(Params)...) {}
   1155 
   1156   template <typename T> operator Matcher<T>() const {
   1157     return DynTypedMatcher::constructVariadic(
   1158                Op, ast_type_traits::ASTNodeKind::getFromNodeKind<T>(),
   1159                getMatchers<T>(llvm::index_sequence_for<Ps...>()))
   1160         .template unconditionalConvertTo<T>();
   1161   }
   1162 
   1163 private:
   1164   // Helper method to unpack the tuple into a vector.
   1165   template <typename T, std::size_t... Is>
   1166   std::vector<DynTypedMatcher> getMatchers(llvm::index_sequence<Is...>) const {
   1167     return {Matcher<T>(std::get<Is>(Params))...};
   1168   }
   1169 
   1170   const DynTypedMatcher::VariadicOperator Op;
   1171   std::tuple<Ps...> Params;
   1172 };
   1173 
   1174 /// \brief Overloaded function object to generate VariadicOperatorMatcher
   1175 ///   objects from arbitrary matchers.
   1176 template <unsigned MinCount, unsigned MaxCount>
   1177 struct VariadicOperatorMatcherFunc {
   1178   DynTypedMatcher::VariadicOperator Op;
   1179 
   1180   template <typename... Ms>
   1181   VariadicOperatorMatcher<Ms...> operator()(Ms &&... Ps) const {
   1182     static_assert(MinCount <= sizeof...(Ms) && sizeof...(Ms) <= MaxCount,
   1183                   "invalid number of parameters for variadic matcher");
   1184     return VariadicOperatorMatcher<Ms...>(Op, std::forward<Ms>(Ps)...);
   1185   }
   1186 };
   1187 
   1188 /// @}
   1189 
   1190 template <typename T>
   1191 inline Matcher<T> DynTypedMatcher::unconditionalConvertTo() const {
   1192   return Matcher<T>(*this);
   1193 }
   1194 
   1195 /// \brief Creates a Matcher<T> that matches if all inner matchers match.
   1196 template<typename T>
   1197 BindableMatcher<T> makeAllOfComposite(
   1198     ArrayRef<const Matcher<T> *> InnerMatchers) {
   1199   // For the size() == 0 case, we return a "true" matcher.
   1200   if (InnerMatchers.size() == 0) {
   1201     return BindableMatcher<T>(TrueMatcher());
   1202   }
   1203   // For the size() == 1 case, we simply return that one matcher.
   1204   // No need to wrap it in a variadic operation.
   1205   if (InnerMatchers.size() == 1) {
   1206     return BindableMatcher<T>(*InnerMatchers[0]);
   1207   }
   1208 
   1209   typedef llvm::pointee_iterator<const Matcher<T> *const *> PI;
   1210   std::vector<DynTypedMatcher> DynMatchers(PI(InnerMatchers.begin()),
   1211                                            PI(InnerMatchers.end()));
   1212   return BindableMatcher<T>(
   1213       DynTypedMatcher::constructVariadic(
   1214           DynTypedMatcher::VO_AllOf,
   1215           ast_type_traits::ASTNodeKind::getFromNodeKind<T>(),
   1216           std::move(DynMatchers))
   1217           .template unconditionalConvertTo<T>());
   1218 }
   1219 
   1220 /// \brief Creates a Matcher<T> that matches if
   1221 /// T is dyn_cast'able into InnerT and all inner matchers match.
   1222 ///
   1223 /// Returns BindableMatcher, as matchers that use dyn_cast have
   1224 /// the same object both to match on and to run submatchers on,
   1225 /// so there is no ambiguity with what gets bound.
   1226 template<typename T, typename InnerT>
   1227 BindableMatcher<T> makeDynCastAllOfComposite(
   1228     ArrayRef<const Matcher<InnerT> *> InnerMatchers) {
   1229   return BindableMatcher<T>(
   1230       makeAllOfComposite(InnerMatchers).template dynCastTo<T>());
   1231 }
   1232 
   1233 /// \brief Matches nodes of type T that have at least one descendant node of
   1234 /// type DescendantT for which the given inner matcher matches.
   1235 ///
   1236 /// DescendantT must be an AST base type.
   1237 template <typename T, typename DescendantT>
   1238 class HasDescendantMatcher : public WrapperMatcherInterface<T> {
   1239   static_assert(IsBaseType<DescendantT>::value,
   1240                 "has descendant only accepts base type matcher");
   1241 
   1242 public:
   1243   explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher)
   1244       : HasDescendantMatcher::WrapperMatcherInterface(DescendantMatcher) {}
   1245 
   1246   bool matches(const T &Node, ASTMatchFinder *Finder,
   1247                BoundNodesTreeBuilder *Builder) const override {
   1248     return Finder->matchesDescendantOf(Node, this->InnerMatcher, Builder,
   1249                                        ASTMatchFinder::BK_First);
   1250   }
   1251 };
   1252 
   1253 /// \brief Matches nodes of type \c T that have a parent node of type \c ParentT
   1254 /// for which the given inner matcher matches.
   1255 ///
   1256 /// \c ParentT must be an AST base type.
   1257 template <typename T, typename ParentT>
   1258 class HasParentMatcher : public WrapperMatcherInterface<T> {
   1259   static_assert(IsBaseType<ParentT>::value,
   1260                 "has parent only accepts base type matcher");
   1261 
   1262 public:
   1263   explicit HasParentMatcher(const Matcher<ParentT> &ParentMatcher)
   1264       : HasParentMatcher::WrapperMatcherInterface(ParentMatcher) {}
   1265 
   1266   bool matches(const T &Node, ASTMatchFinder *Finder,
   1267                BoundNodesTreeBuilder *Builder) const override {
   1268     return Finder->matchesAncestorOf(Node, this->InnerMatcher, Builder,
   1269                                      ASTMatchFinder::AMM_ParentOnly);
   1270   }
   1271 };
   1272 
   1273 /// \brief Matches nodes of type \c T that have at least one ancestor node of
   1274 /// type \c AncestorT for which the given inner matcher matches.
   1275 ///
   1276 /// \c AncestorT must be an AST base type.
   1277 template <typename T, typename AncestorT>
   1278 class HasAncestorMatcher : public WrapperMatcherInterface<T> {
   1279   static_assert(IsBaseType<AncestorT>::value,
   1280                 "has ancestor only accepts base type matcher");
   1281 
   1282 public:
   1283   explicit HasAncestorMatcher(const Matcher<AncestorT> &AncestorMatcher)
   1284       : HasAncestorMatcher::WrapperMatcherInterface(AncestorMatcher) {}
   1285 
   1286   bool matches(const T &Node, ASTMatchFinder *Finder,
   1287                BoundNodesTreeBuilder *Builder) const override {
   1288     return Finder->matchesAncestorOf(Node, this->InnerMatcher, Builder,
   1289                                      ASTMatchFinder::AMM_All);
   1290   }
   1291 };
   1292 
   1293 /// \brief Matches nodes of type T that have at least one descendant node of
   1294 /// type DescendantT for which the given inner matcher matches.
   1295 ///
   1296 /// DescendantT must be an AST base type.
   1297 /// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match
   1298 /// for each descendant node that matches instead of only for the first.
   1299 template <typename T, typename DescendantT>
   1300 class ForEachDescendantMatcher : public WrapperMatcherInterface<T> {
   1301   static_assert(IsBaseType<DescendantT>::value,
   1302                 "for each descendant only accepts base type matcher");
   1303 
   1304 public:
   1305   explicit ForEachDescendantMatcher(
   1306       const Matcher<DescendantT> &DescendantMatcher)
   1307       : ForEachDescendantMatcher::WrapperMatcherInterface(DescendantMatcher) {}
   1308 
   1309   bool matches(const T &Node, ASTMatchFinder *Finder,
   1310                BoundNodesTreeBuilder *Builder) const override {
   1311     return Finder->matchesDescendantOf(Node, this->InnerMatcher, Builder,
   1312                                        ASTMatchFinder::BK_All);
   1313   }
   1314 };
   1315 
   1316 /// \brief Matches on nodes that have a getValue() method if getValue() equals
   1317 /// the value the ValueEqualsMatcher was constructed with.
   1318 template <typename T, typename ValueT>
   1319 class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> {
   1320   static_assert(std::is_base_of<CharacterLiteral, T>::value ||
   1321                 std::is_base_of<CXXBoolLiteralExpr, T>::value ||
   1322                 std::is_base_of<FloatingLiteral, T>::value ||
   1323                 std::is_base_of<IntegerLiteral, T>::value,
   1324                 "the node must have a getValue method");
   1325 
   1326 public:
   1327   explicit ValueEqualsMatcher(const ValueT &ExpectedValue)
   1328       : ExpectedValue(ExpectedValue) {}
   1329 
   1330   bool matchesNode(const T &Node) const override {
   1331     return Node.getValue() == ExpectedValue;
   1332   }
   1333 
   1334 private:
   1335   const ValueT ExpectedValue;
   1336 };
   1337 
   1338 /// \brief Template specializations to easily write matchers for floating point
   1339 /// literals.
   1340 template <>
   1341 inline bool ValueEqualsMatcher<FloatingLiteral, double>::matchesNode(
   1342     const FloatingLiteral &Node) const {
   1343   if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle)
   1344     return Node.getValue().convertToFloat() == ExpectedValue;
   1345   if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble)
   1346     return Node.getValue().convertToDouble() == ExpectedValue;
   1347   return false;
   1348 }
   1349 template <>
   1350 inline bool ValueEqualsMatcher<FloatingLiteral, float>::matchesNode(
   1351     const FloatingLiteral &Node) const {
   1352   if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle)
   1353     return Node.getValue().convertToFloat() == ExpectedValue;
   1354   if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble)
   1355     return Node.getValue().convertToDouble() == ExpectedValue;
   1356   return false;
   1357 }
   1358 template <>
   1359 inline bool ValueEqualsMatcher<FloatingLiteral, llvm::APFloat>::matchesNode(
   1360     const FloatingLiteral &Node) const {
   1361   return ExpectedValue.compare(Node.getValue()) == llvm::APFloat::cmpEqual;
   1362 }
   1363 
   1364 /// \brief A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a
   1365 /// variadic functor that takes a number of Matcher<TargetT> and returns a
   1366 /// Matcher<SourceT> that matches TargetT nodes that are matched by all of the
   1367 /// given matchers, if SourceT can be dynamically casted into TargetT.
   1368 ///
   1369 /// For example:
   1370 ///   const VariadicDynCastAllOfMatcher<
   1371 ///       Decl, CXXRecordDecl> record;
   1372 /// Creates a functor record(...) that creates a Matcher<Decl> given
   1373 /// a variable number of arguments of type Matcher<CXXRecordDecl>.
   1374 /// The returned matcher matches if the given Decl can by dynamically
   1375 /// casted to CXXRecordDecl and all given matchers match.
   1376 template <typename SourceT, typename TargetT>
   1377 class VariadicDynCastAllOfMatcher
   1378     : public llvm::VariadicFunction<
   1379         BindableMatcher<SourceT>, Matcher<TargetT>,
   1380         makeDynCastAllOfComposite<SourceT, TargetT> > {
   1381 public:
   1382   VariadicDynCastAllOfMatcher() {}
   1383 };
   1384 
   1385 /// \brief A \c VariadicAllOfMatcher<T> object is a variadic functor that takes
   1386 /// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T
   1387 /// nodes that are matched by all of the given matchers.
   1388 ///
   1389 /// For example:
   1390 ///   const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
   1391 /// Creates a functor nestedNameSpecifier(...) that creates a
   1392 /// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type
   1393 /// \c Matcher<NestedNameSpecifier>.
   1394 /// The returned matcher matches if all given matchers match.
   1395 template <typename T>
   1396 class VariadicAllOfMatcher : public llvm::VariadicFunction<
   1397                                BindableMatcher<T>, Matcher<T>,
   1398                                makeAllOfComposite<T> > {
   1399 public:
   1400   VariadicAllOfMatcher() {}
   1401 };
   1402 
   1403 /// \brief Matches nodes of type \c TLoc for which the inner
   1404 /// \c Matcher<T> matches.
   1405 template <typename TLoc, typename T>
   1406 class LocMatcher : public WrapperMatcherInterface<TLoc> {
   1407 public:
   1408   explicit LocMatcher(const Matcher<T> &InnerMatcher)
   1409       : LocMatcher::WrapperMatcherInterface(InnerMatcher) {}
   1410 
   1411   bool matches(const TLoc &Node, ASTMatchFinder *Finder,
   1412                BoundNodesTreeBuilder *Builder) const override {
   1413     if (!Node)
   1414       return false;
   1415     return this->InnerMatcher.matches(extract(Node), Finder, Builder);
   1416   }
   1417 
   1418 private:
   1419   static ast_type_traits::DynTypedNode
   1420   extract(const NestedNameSpecifierLoc &Loc) {
   1421     return ast_type_traits::DynTypedNode::create(*Loc.getNestedNameSpecifier());
   1422   }
   1423 };
   1424 
   1425 /// \brief Matches \c TypeLocs based on an inner matcher matching a certain
   1426 /// \c QualType.
   1427 ///
   1428 /// Used to implement the \c loc() matcher.
   1429 class TypeLocTypeMatcher : public WrapperMatcherInterface<TypeLoc> {
   1430 public:
   1431   explicit TypeLocTypeMatcher(const Matcher<QualType> &InnerMatcher)
   1432       : TypeLocTypeMatcher::WrapperMatcherInterface(InnerMatcher) {}
   1433 
   1434   bool matches(const TypeLoc &Node, ASTMatchFinder *Finder,
   1435                BoundNodesTreeBuilder *Builder) const override {
   1436     if (!Node)
   1437       return false;
   1438     return this->InnerMatcher.matches(
   1439         ast_type_traits::DynTypedNode::create(Node.getType()), Finder, Builder);
   1440   }
   1441 };
   1442 
   1443 /// \brief Matches nodes of type \c T for which the inner matcher matches on a
   1444 /// another node of type \c T that can be reached using a given traverse
   1445 /// function.
   1446 template <typename T>
   1447 class TypeTraverseMatcher : public WrapperMatcherInterface<T> {
   1448 public:
   1449   explicit TypeTraverseMatcher(const Matcher<QualType> &InnerMatcher,
   1450                                QualType (T::*TraverseFunction)() const)
   1451       : TypeTraverseMatcher::WrapperMatcherInterface(InnerMatcher),
   1452         TraverseFunction(TraverseFunction) {}
   1453 
   1454   bool matches(const T &Node, ASTMatchFinder *Finder,
   1455                BoundNodesTreeBuilder *Builder) const override {
   1456     QualType NextNode = (Node.*TraverseFunction)();
   1457     if (NextNode.isNull())
   1458       return false;
   1459     return this->InnerMatcher.matches(
   1460         ast_type_traits::DynTypedNode::create(NextNode), Finder, Builder);
   1461   }
   1462 
   1463 private:
   1464   QualType (T::*TraverseFunction)() const;
   1465 };
   1466 
   1467 /// \brief Matches nodes of type \c T in a ..Loc hierarchy, for which the inner
   1468 /// matcher matches on a another node of type \c T that can be reached using a
   1469 /// given traverse function.
   1470 template <typename T>
   1471 class TypeLocTraverseMatcher : public WrapperMatcherInterface<T> {
   1472 public:
   1473   explicit TypeLocTraverseMatcher(const Matcher<TypeLoc> &InnerMatcher,
   1474                                   TypeLoc (T::*TraverseFunction)() const)
   1475       : TypeLocTraverseMatcher::WrapperMatcherInterface(InnerMatcher),
   1476         TraverseFunction(TraverseFunction) {}
   1477 
   1478   bool matches(const T &Node, ASTMatchFinder *Finder,
   1479                BoundNodesTreeBuilder *Builder) const override {
   1480     TypeLoc NextNode = (Node.*TraverseFunction)();
   1481     if (!NextNode)
   1482       return false;
   1483     return this->InnerMatcher.matches(
   1484         ast_type_traits::DynTypedNode::create(NextNode), Finder, Builder);
   1485   }
   1486 
   1487 private:
   1488   TypeLoc (T::*TraverseFunction)() const;
   1489 };
   1490 
   1491 /// \brief Converts a \c Matcher<InnerT> to a \c Matcher<OuterT>, where
   1492 /// \c OuterT is any type that is supported by \c Getter.
   1493 ///
   1494 /// \code Getter<OuterT>::value() \endcode returns a
   1495 /// \code InnerTBase (OuterT::*)() \endcode, which is used to adapt a \c OuterT
   1496 /// object into a \c InnerT
   1497 template <typename InnerTBase,
   1498           template <typename OuterT> class Getter,
   1499           template <typename OuterT> class MatcherImpl,
   1500           typename ReturnTypesF>
   1501 class TypeTraversePolymorphicMatcher {
   1502 private:
   1503   typedef TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl,
   1504                                          ReturnTypesF> Self;
   1505   static Self create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers);
   1506 
   1507 public:
   1508   typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
   1509 
   1510   explicit TypeTraversePolymorphicMatcher(
   1511       ArrayRef<const Matcher<InnerTBase> *> InnerMatchers)
   1512       : InnerMatcher(makeAllOfComposite(InnerMatchers)) {}
   1513 
   1514   template <typename OuterT> operator Matcher<OuterT>() const {
   1515     return Matcher<OuterT>(
   1516         new MatcherImpl<OuterT>(InnerMatcher, Getter<OuterT>::value()));
   1517   }
   1518 
   1519   struct Func : public llvm::VariadicFunction<Self, Matcher<InnerTBase>,
   1520                                               &Self::create> {
   1521     Func() {}
   1522   };
   1523 
   1524 private:
   1525   const Matcher<InnerTBase> InnerMatcher;
   1526 };
   1527 
   1528 /// \brief A simple memoizer of T(*)() functions.
   1529 ///
   1530 /// It will call the passed 'Func' template parameter at most once.
   1531 /// Used to support AST_MATCHER_FUNCTION() macro.
   1532 template <typename Matcher, Matcher (*Func)()> class MemoizedMatcher {
   1533   struct Wrapper {
   1534     Wrapper() : M(Func()) {}
   1535     Matcher M;
   1536   };
   1537 
   1538 public:
   1539   static const Matcher &getInstance() {
   1540     static llvm::ManagedStatic<Wrapper> Instance;
   1541     return Instance->M;
   1542   }
   1543 };
   1544 
   1545 // Define the create() method out of line to silence a GCC warning about
   1546 // the struct "Func" having greater visibility than its base, which comes from
   1547 // using the flag -fvisibility-inlines-hidden.
   1548 template <typename InnerTBase, template <typename OuterT> class Getter,
   1549           template <typename OuterT> class MatcherImpl, typename ReturnTypesF>
   1550 TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl, ReturnTypesF>
   1551 TypeTraversePolymorphicMatcher<
   1552     InnerTBase, Getter, MatcherImpl,
   1553     ReturnTypesF>::create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers) {
   1554   return Self(InnerMatchers);
   1555 }
   1556 
   1557 // FIXME: unify ClassTemplateSpecializationDecl and TemplateSpecializationType's
   1558 // APIs for accessing the template argument list.
   1559 inline ArrayRef<TemplateArgument>
   1560 getTemplateSpecializationArgs(const ClassTemplateSpecializationDecl &D) {
   1561   return D.getTemplateArgs().asArray();
   1562 }
   1563 
   1564 inline ArrayRef<TemplateArgument>
   1565 getTemplateSpecializationArgs(const TemplateSpecializationType &T) {
   1566   return llvm::makeArrayRef(T.getArgs(), T.getNumArgs());
   1567 }
   1568 
   1569 struct NotEqualsBoundNodePredicate {
   1570   bool operator()(const internal::BoundNodesMap &Nodes) const {
   1571     return Nodes.getNode(ID) != Node;
   1572   }
   1573   std::string ID;
   1574   ast_type_traits::DynTypedNode Node;
   1575 };
   1576 
   1577 } // end namespace internal
   1578 } // end namespace ast_matchers
   1579 } // end namespace clang
   1580 
   1581 #endif
   1582