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