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