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/ExprCXX.h"
44 #include "clang/AST/ExprObjC.h"
45 #include "clang/AST/NestedNameSpecifier.h"
46 #include "clang/AST/Stmt.h"
47 #include "clang/AST/TemplateName.h"
48 #include "clang/AST/Type.h"
49 #include "clang/AST/TypeLoc.h"
50 #include "clang/Basic/LLVM.h"
51 #include "clang/Basic/OperatorKinds.h"
52 #include "llvm/ADT/APFloat.h"
53 #include "llvm/ADT/ArrayRef.h"
54 #include "llvm/ADT/IntrusiveRefCntPtr.h"
55 #include "llvm/ADT/None.h"
56 #include "llvm/ADT/Optional.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include "llvm/ADT/SmallVector.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/iterator.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/ManagedStatic.h"
63 #include "llvm/Support/Regex.h"
64 #include <algorithm>
65 #include <cassert>
66 #include <cstddef>
67 #include <cstdint>
68 #include <map>
69 #include <memory>
70 #include <string>
71 #include <tuple>
72 #include <type_traits>
73 #include <utility>
74 #include <vector>
75 
76 namespace clang {
77 
78 class ASTContext;
79 
80 namespace ast_matchers {
81 
82 class BoundNodes;
83 
84 namespace internal {
85 
86 /// A type-list implementation.
87 ///
88 /// A "linked list" of types, accessible by using the ::head and ::tail
89 /// typedefs.
90 template <typename... Ts> struct TypeList {}; // Empty sentinel type list.
91 
92 template <typename T1, typename... Ts> struct TypeList<T1, Ts...> {
93   /// The first type on the list.
94   using head = T1;
95 
96   /// A sublist with the tail. ie everything but the head.
97   ///
98   /// This type is used to do recursion. TypeList<>/EmptyTypeList indicates the
99   /// end of the list.
100   using tail = TypeList<Ts...>;
101 };
102 
103 /// The empty type list.
104 using EmptyTypeList = TypeList<>;
105 
106 /// Helper meta-function to determine if some type \c T is present or
107 ///   a parent type in the list.
108 template <typename AnyTypeList, typename T> struct TypeListContainsSuperOf {
109   static const bool value =
110       std::is_base_of<typename AnyTypeList::head, T>::value ||
111       TypeListContainsSuperOf<typename AnyTypeList::tail, T>::value;
112 };
113 template <typename T> struct TypeListContainsSuperOf<EmptyTypeList, T> {
114   static const bool value = false;
115 };
116 
117 /// Variadic function object.
118 ///
119 /// Most of the functions below that use VariadicFunction could be implemented
120 /// using plain C++11 variadic functions, but the function object allows us to
121 /// capture it on the dynamic matcher registry.
122 template <typename ResultT, typename ArgT,
123           ResultT (*Func)(ArrayRef<const ArgT *>)>
124 struct VariadicFunction {
125   ResultT operator()() const { return Func(None); }
126 
127   template <typename... ArgsT>
128   ResultT operator()(const ArgT &Arg1, const ArgsT &... Args) const {
129     return Execute(Arg1, static_cast<const ArgT &>(Args)...);
130   }
131 
132   // We also allow calls with an already created array, in case the caller
133   // already had it.
134   ResultT operator()(ArrayRef<ArgT> Args) const {
135     return Func(llvm::to_vector<8>(llvm::make_pointer_range(Args)));
136   }
137 
138 private:
139   // Trampoline function to allow for implicit conversions to take place
140   // before we make the array.
141   template <typename... ArgsT> ResultT Execute(const ArgsT &... Args) const {
142     const ArgT *const ArgsArray[] = {&Args...};
143     return Func(ArrayRef<const ArgT *>(ArgsArray, sizeof...(ArgsT)));
144   }
145 };
146 
147 /// Unifies obtaining the underlying type of a regular node through
148 /// `getType` and a TypedefNameDecl node through `getUnderlyingType`.
149 inline QualType getUnderlyingType(const Expr &Node) { return Node.getType(); }
150 
151 inline QualType getUnderlyingType(const ValueDecl &Node) {
152   return Node.getType();
153 }
154 inline QualType getUnderlyingType(const TypedefNameDecl &Node) {
155   return Node.getUnderlyingType();
156 }
157 inline QualType getUnderlyingType(const FriendDecl &Node) {
158   if (const TypeSourceInfo *TSI = Node.getFriendType())
159     return TSI->getType();
160   return QualType();
161 }
162 inline QualType getUnderlyingType(const CXXBaseSpecifier &Node) {
163   return Node.getType();
164 }
165 
166 /// Unifies obtaining a `TypeSourceInfo` from different node types.
167 template <typename T,
168           std::enable_if_t<TypeListContainsSuperOf<
169               TypeList<CXXBaseSpecifier, CXXCtorInitializer,
170                        CXXTemporaryObjectExpr, CXXUnresolvedConstructExpr,
171                        CompoundLiteralExpr, DeclaratorDecl, ObjCPropertyDecl,
172                        TemplateArgumentLoc, TypedefNameDecl>,
173               T>::value> * = nullptr>
174 inline TypeSourceInfo *GetTypeSourceInfo(const T &Node) {
175   return Node.getTypeSourceInfo();
176 }
177 template <typename T,
178           std::enable_if_t<TypeListContainsSuperOf<
179               TypeList<CXXFunctionalCastExpr, ExplicitCastExpr>, T>::value> * =
180               nullptr>
181 inline TypeSourceInfo *GetTypeSourceInfo(const T &Node) {
182   return Node.getTypeInfoAsWritten();
183 }
184 inline TypeSourceInfo *GetTypeSourceInfo(const BlockDecl &Node) {
185   return Node.getSignatureAsWritten();
186 }
187 inline TypeSourceInfo *GetTypeSourceInfo(const CXXNewExpr &Node) {
188   return Node.getAllocatedTypeSourceInfo();
189 }
190 inline TypeSourceInfo *
191 GetTypeSourceInfo(const ClassTemplateSpecializationDecl &Node) {
192   return Node.getTypeAsWritten();
193 }
194 
195 /// Unifies obtaining the FunctionProtoType pointer from both
196 /// FunctionProtoType and FunctionDecl nodes..
197 inline const FunctionProtoType *
198 getFunctionProtoType(const FunctionProtoType &Node) {
199   return &Node;
200 }
201 
202 inline const FunctionProtoType *getFunctionProtoType(const FunctionDecl &Node) {
203   return Node.getType()->getAs<FunctionProtoType>();
204 }
205 
206 /// Unifies obtaining the access specifier from Decl and CXXBaseSpecifier nodes.
207 inline clang::AccessSpecifier getAccessSpecifier(const Decl &Node) {
208   return Node.getAccess();
209 }
210 
211 inline clang::AccessSpecifier getAccessSpecifier(const CXXBaseSpecifier &Node) {
212   return Node.getAccessSpecifier();
213 }
214 
215 /// Internal version of BoundNodes. Holds all the bound nodes.
216 class BoundNodesMap {
217 public:
218   /// Adds \c Node to the map with key \c ID.
219   ///
220   /// The node's base type should be in NodeBaseType or it will be unaccessible.
221   void addNode(StringRef ID, const DynTypedNode &DynNode) {
222     NodeMap[std::string(ID)] = DynNode;
223   }
224 
225   /// Returns the AST node bound to \c ID.
226   ///
227   /// Returns NULL if there was no node bound to \c ID or if there is a node but
228   /// it cannot be converted to the specified type.
229   template <typename T>
230   const T *getNodeAs(StringRef ID) const {
231     IDToNodeMap::const_iterator It = NodeMap.find(ID);
232     if (It == NodeMap.end()) {
233       return nullptr;
234     }
235     return It->second.get<T>();
236   }
237 
238   DynTypedNode getNode(StringRef ID) const {
239     IDToNodeMap::const_iterator It = NodeMap.find(ID);
240     if (It == NodeMap.end()) {
241       return DynTypedNode();
242     }
243     return It->second;
244   }
245 
246   /// Imposes an order on BoundNodesMaps.
247   bool operator<(const BoundNodesMap &Other) const {
248     return NodeMap < Other.NodeMap;
249   }
250 
251   /// A map from IDs to the bound nodes.
252   ///
253   /// Note that we're using std::map here, as for memoization:
254   /// - we need a comparison operator
255   /// - we need an assignment operator
256   using IDToNodeMap = std::map<std::string, DynTypedNode, std::less<>>;
257 
258   const IDToNodeMap &getMap() const {
259     return NodeMap;
260   }
261 
262   /// Returns \c true if this \c BoundNodesMap can be compared, i.e. all
263   /// stored nodes have memoization data.
264   bool isComparable() const {
265     for (const auto &IDAndNode : NodeMap) {
266       if (!IDAndNode.second.getMemoizationData())
267         return false;
268     }
269     return true;
270   }
271 
272 private:
273   IDToNodeMap NodeMap;
274 };
275 
276 /// Creates BoundNodesTree objects.
277 ///
278 /// The tree builder is used during the matching process to insert the bound
279 /// nodes from the Id matcher.
280 class BoundNodesTreeBuilder {
281 public:
282   /// A visitor interface to visit all BoundNodes results for a
283   /// BoundNodesTree.
284   class Visitor {
285   public:
286     virtual ~Visitor() = default;
287 
288     /// Called multiple times during a single call to VisitMatches(...).
289     ///
290     /// 'BoundNodesView' contains the bound nodes for a single match.
291     virtual void visitMatch(const BoundNodes& BoundNodesView) = 0;
292   };
293 
294   /// Add a binding from an id to a node.
295   void setBinding(StringRef Id, const DynTypedNode &DynNode) {
296     if (Bindings.empty())
297       Bindings.emplace_back();
298     for (BoundNodesMap &Binding : Bindings)
299       Binding.addNode(Id, DynNode);
300   }
301 
302   /// Adds a branch in the tree.
303   void addMatch(const BoundNodesTreeBuilder &Bindings);
304 
305   /// Visits all matches that this BoundNodesTree represents.
306   ///
307   /// The ownership of 'ResultVisitor' remains at the caller.
308   void visitMatches(Visitor* ResultVisitor);
309 
310   template <typename ExcludePredicate>
311   bool removeBindings(const ExcludePredicate &Predicate) {
312     llvm::erase_if(Bindings, Predicate);
313     return !Bindings.empty();
314   }
315 
316   /// Imposes an order on BoundNodesTreeBuilders.
317   bool operator<(const BoundNodesTreeBuilder &Other) const {
318     return Bindings < Other.Bindings;
319   }
320 
321   /// Returns \c true if this \c BoundNodesTreeBuilder can be compared,
322   /// i.e. all stored node maps have memoization data.
323   bool isComparable() const {
324     for (const BoundNodesMap &NodesMap : Bindings) {
325       if (!NodesMap.isComparable())
326         return false;
327     }
328     return true;
329   }
330 
331 private:
332   SmallVector<BoundNodesMap, 1> Bindings;
333 };
334 
335 class ASTMatchFinder;
336 
337 /// Generic interface for all matchers.
338 ///
339 /// Used by the implementation of Matcher<T> and DynTypedMatcher.
340 /// In general, implement MatcherInterface<T> or SingleNodeMatcherInterface<T>
341 /// instead.
342 class DynMatcherInterface
343     : public llvm::ThreadSafeRefCountedBase<DynMatcherInterface> {
344 public:
345   virtual ~DynMatcherInterface() = default;
346 
347   /// Returns true if \p DynNode can be matched.
348   ///
349   /// May bind \p DynNode to an ID via \p Builder, or recurse into
350   /// the AST via \p Finder.
351   virtual bool dynMatches(const DynTypedNode &DynNode, ASTMatchFinder *Finder,
352                           BoundNodesTreeBuilder *Builder) const = 0;
353 
354   virtual llvm::Optional<clang::TraversalKind> TraversalKind() const {
355     return llvm::None;
356   }
357 };
358 
359 /// Generic interface for matchers on an AST node of type T.
360 ///
361 /// Implement this if your matcher may need to inspect the children or
362 /// descendants of the node or bind matched nodes to names. If you are
363 /// writing a simple matcher that only inspects properties of the
364 /// current node and doesn't care about its children or descendants,
365 /// implement SingleNodeMatcherInterface instead.
366 template <typename T>
367 class MatcherInterface : public DynMatcherInterface {
368 public:
369   /// Returns true if 'Node' can be matched.
370   ///
371   /// May bind 'Node' to an ID via 'Builder', or recurse into
372   /// the AST via 'Finder'.
373   virtual bool matches(const T &Node,
374                        ASTMatchFinder *Finder,
375                        BoundNodesTreeBuilder *Builder) const = 0;
376 
377   bool dynMatches(const DynTypedNode &DynNode, ASTMatchFinder *Finder,
378                   BoundNodesTreeBuilder *Builder) const override {
379     return matches(DynNode.getUnchecked<T>(), Finder, Builder);
380   }
381 };
382 
383 /// Interface for matchers that only evaluate properties on a single
384 /// node.
385 template <typename T>
386 class SingleNodeMatcherInterface : public MatcherInterface<T> {
387 public:
388   /// Returns true if the matcher matches the provided node.
389   ///
390   /// A subclass must implement this instead of Matches().
391   virtual bool matchesNode(const T &Node) const = 0;
392 
393 private:
394   /// Implements MatcherInterface::Matches.
395   bool matches(const T &Node,
396                ASTMatchFinder * /* Finder */,
397                BoundNodesTreeBuilder * /*  Builder */) const override {
398     return matchesNode(Node);
399   }
400 };
401 
402 template <typename> class Matcher;
403 
404 /// Matcher that works on a \c DynTypedNode.
405 ///
406 /// It is constructed from a \c Matcher<T> object and redirects most calls to
407 /// underlying matcher.
408 /// It checks whether the \c DynTypedNode is convertible into the type of the
409 /// underlying matcher and then do the actual match on the actual node, or
410 /// return false if it is not convertible.
411 class DynTypedMatcher {
412 public:
413   /// Takes ownership of the provided implementation pointer.
414   template <typename T>
415   DynTypedMatcher(MatcherInterface<T> *Implementation)
416       : SupportedKind(ASTNodeKind::getFromNodeKind<T>()),
417         RestrictKind(SupportedKind), Implementation(Implementation) {}
418 
419   /// Construct from a variadic function.
420   enum VariadicOperator {
421     /// Matches nodes for which all provided matchers match.
422     VO_AllOf,
423 
424     /// Matches nodes for which at least one of the provided matchers
425     /// matches.
426     VO_AnyOf,
427 
428     /// Matches nodes for which at least one of the provided matchers
429     /// matches, but doesn't stop at the first match.
430     VO_EachOf,
431 
432     /// Matches any node but executes all inner matchers to find result
433     /// bindings.
434     VO_Optionally,
435 
436     /// Matches nodes that do not match the provided matcher.
437     ///
438     /// Uses the variadic matcher interface, but fails if
439     /// InnerMatchers.size() != 1.
440     VO_UnaryNot
441   };
442 
443   static DynTypedMatcher
444   constructVariadic(VariadicOperator Op, ASTNodeKind SupportedKind,
445                     std::vector<DynTypedMatcher> InnerMatchers);
446 
447   static DynTypedMatcher
448   constructRestrictedWrapper(const DynTypedMatcher &InnerMatcher,
449                              ASTNodeKind RestrictKind);
450 
451   /// Get a "true" matcher for \p NodeKind.
452   ///
453   /// It only checks that the node is of the right kind.
454   static DynTypedMatcher trueMatcher(ASTNodeKind NodeKind);
455 
456   void setAllowBind(bool AB) { AllowBind = AB; }
457 
458   /// Check whether this matcher could ever match a node of kind \p Kind.
459   /// \return \c false if this matcher will never match such a node. Otherwise,
460   /// return \c true.
461   bool canMatchNodesOfKind(ASTNodeKind Kind) const;
462 
463   /// Return a matcher that points to the same implementation, but
464   ///   restricts the node types for \p Kind.
465   DynTypedMatcher dynCastTo(const ASTNodeKind Kind) const;
466 
467   /// Return a matcher that that points to the same implementation, but sets the
468   ///   traversal kind.
469   ///
470   /// If the traversal kind is already set, then \c TK overrides it.
471   DynTypedMatcher withTraversalKind(TraversalKind TK);
472 
473   /// Returns true if the matcher matches the given \c DynNode.
474   bool matches(const DynTypedNode &DynNode, ASTMatchFinder *Finder,
475                BoundNodesTreeBuilder *Builder) const;
476 
477   /// Same as matches(), but skips the kind check.
478   ///
479   /// It is faster, but the caller must ensure the node is valid for the
480   /// kind of this matcher.
481   bool matchesNoKindCheck(const DynTypedNode &DynNode, ASTMatchFinder *Finder,
482                           BoundNodesTreeBuilder *Builder) const;
483 
484   /// Bind the specified \p ID to the matcher.
485   /// \return A new matcher with the \p ID bound to it if this matcher supports
486   ///   binding. Otherwise, returns an empty \c Optional<>.
487   llvm::Optional<DynTypedMatcher> tryBind(StringRef ID) const;
488 
489   /// Returns a unique \p ID for the matcher.
490   ///
491   /// Casting a Matcher<T> to Matcher<U> creates a matcher that has the
492   /// same \c Implementation pointer, but different \c RestrictKind. We need to
493   /// include both in the ID to make it unique.
494   ///
495   /// \c MatcherIDType supports operator< and provides strict weak ordering.
496   using MatcherIDType = std::pair<ASTNodeKind, uint64_t>;
497   MatcherIDType getID() const {
498     /// FIXME: Document the requirements this imposes on matcher
499     /// implementations (no new() implementation_ during a Matches()).
500     return std::make_pair(RestrictKind,
501                           reinterpret_cast<uint64_t>(Implementation.get()));
502   }
503 
504   /// Returns the type this matcher works on.
505   ///
506   /// \c matches() will always return false unless the node passed is of this
507   /// or a derived type.
508   ASTNodeKind getSupportedKind() const { return SupportedKind; }
509 
510   /// Returns \c true if the passed \c DynTypedMatcher can be converted
511   ///   to a \c Matcher<T>.
512   ///
513   /// This method verifies that the underlying matcher in \c Other can process
514   /// nodes of types T.
515   template <typename T> bool canConvertTo() const {
516     return canConvertTo(ASTNodeKind::getFromNodeKind<T>());
517   }
518   bool canConvertTo(ASTNodeKind To) const;
519 
520   /// Construct a \c Matcher<T> interface around the dynamic matcher.
521   ///
522   /// This method asserts that \c canConvertTo() is \c true. Callers
523   /// should call \c canConvertTo() first to make sure that \c this is
524   /// compatible with T.
525   template <typename T> Matcher<T> convertTo() const {
526     assert(canConvertTo<T>());
527     return unconditionalConvertTo<T>();
528   }
529 
530   /// Same as \c convertTo(), but does not check that the underlying
531   ///   matcher can handle a value of T.
532   ///
533   /// If it is not compatible, then this matcher will never match anything.
534   template <typename T> Matcher<T> unconditionalConvertTo() const;
535 
536   /// Returns the \c TraversalKind respected by calls to `match()`, if any.
537   ///
538   /// Most matchers will not have a traversal kind set, instead relying on the
539   /// surrounding context. For those, \c llvm::None is returned.
540   llvm::Optional<clang::TraversalKind> getTraversalKind() const {
541     return Implementation->TraversalKind();
542   }
543 
544 private:
545   DynTypedMatcher(ASTNodeKind SupportedKind, ASTNodeKind RestrictKind,
546                   IntrusiveRefCntPtr<DynMatcherInterface> Implementation)
547       : SupportedKind(SupportedKind), RestrictKind(RestrictKind),
548         Implementation(std::move(Implementation)) {}
549 
550   bool AllowBind = false;
551   ASTNodeKind SupportedKind;
552 
553   /// A potentially stricter node kind.
554   ///
555   /// It allows to perform implicit and dynamic cast of matchers without
556   /// needing to change \c Implementation.
557   ASTNodeKind RestrictKind;
558   IntrusiveRefCntPtr<DynMatcherInterface> Implementation;
559 };
560 
561 /// Wrapper of a MatcherInterface<T> *that allows copying.
562 ///
563 /// A Matcher<Base> can be used anywhere a Matcher<Derived> is
564 /// required. This establishes an is-a relationship which is reverse
565 /// to the AST hierarchy. In other words, Matcher<T> is contravariant
566 /// with respect to T. The relationship is built via a type conversion
567 /// operator rather than a type hierarchy to be able to templatize the
568 /// type hierarchy instead of spelling it out.
569 template <typename T>
570 class Matcher {
571 public:
572   /// Takes ownership of the provided implementation pointer.
573   explicit Matcher(MatcherInterface<T> *Implementation)
574       : Implementation(Implementation) {}
575 
576   /// Implicitly converts \c Other to a Matcher<T>.
577   ///
578   /// Requires \c T to be derived from \c From.
579   template <typename From>
580   Matcher(const Matcher<From> &Other,
581           std::enable_if_t<std::is_base_of<From, T>::value &&
582                            !std::is_same<From, T>::value> * = nullptr)
583       : Implementation(restrictMatcher(Other.Implementation)) {
584     assert(Implementation.getSupportedKind().isSame(
585         ASTNodeKind::getFromNodeKind<T>()));
586   }
587 
588   /// Implicitly converts \c Matcher<Type> to \c Matcher<QualType>.
589   ///
590   /// The resulting matcher is not strict, i.e. ignores qualifiers.
591   template <typename TypeT>
592   Matcher(const Matcher<TypeT> &Other,
593           std::enable_if_t<std::is_same<T, QualType>::value &&
594                            std::is_same<TypeT, Type>::value> * = nullptr)
595       : Implementation(new TypeToQualType<TypeT>(Other)) {}
596 
597   /// Convert \c this into a \c Matcher<T> by applying dyn_cast<> to the
598   /// argument.
599   /// \c To must be a base class of \c T.
600   template <typename To> Matcher<To> dynCastTo() const & {
601     static_assert(std::is_base_of<To, T>::value, "Invalid dynCast call.");
602     return Matcher<To>(Implementation);
603   }
604 
605   template <typename To> Matcher<To> dynCastTo() && {
606     static_assert(std::is_base_of<To, T>::value, "Invalid dynCast call.");
607     return Matcher<To>(std::move(Implementation));
608   }
609 
610   /// Forwards the call to the underlying MatcherInterface<T> pointer.
611   bool matches(const T &Node,
612                ASTMatchFinder *Finder,
613                BoundNodesTreeBuilder *Builder) const {
614     return Implementation.matches(DynTypedNode::create(Node), Finder, Builder);
615   }
616 
617   /// Returns an ID that uniquely identifies the matcher.
618   DynTypedMatcher::MatcherIDType getID() const {
619     return Implementation.getID();
620   }
621 
622   /// Extract the dynamic matcher.
623   ///
624   /// The returned matcher keeps the same restrictions as \c this and remembers
625   /// that it is meant to support nodes of type \c T.
626   operator DynTypedMatcher() const & { return Implementation; }
627 
628   operator DynTypedMatcher() && { return std::move(Implementation); }
629 
630   /// Allows the conversion of a \c Matcher<Type> to a \c
631   /// Matcher<QualType>.
632   ///
633   /// Depending on the constructor argument, the matcher is either strict, i.e.
634   /// does only matches in the absence of qualifiers, or not, i.e. simply
635   /// ignores any qualifiers.
636   template <typename TypeT>
637   class TypeToQualType : public MatcherInterface<QualType> {
638     const DynTypedMatcher InnerMatcher;
639 
640   public:
641     TypeToQualType(const Matcher<TypeT> &InnerMatcher)
642         : InnerMatcher(InnerMatcher) {}
643 
644     bool matches(const QualType &Node, ASTMatchFinder *Finder,
645                  BoundNodesTreeBuilder *Builder) const override {
646       if (Node.isNull())
647         return false;
648       return this->InnerMatcher.matches(DynTypedNode::create(*Node), Finder,
649                                         Builder);
650     }
651 
652     llvm::Optional<clang::TraversalKind> TraversalKind() const override {
653       return this->InnerMatcher.getTraversalKind();
654     }
655   };
656 
657 private:
658   // For Matcher<T> <=> Matcher<U> conversions.
659   template <typename U> friend class Matcher;
660 
661   // For DynTypedMatcher::unconditionalConvertTo<T>.
662   friend class DynTypedMatcher;
663 
664   static DynTypedMatcher restrictMatcher(const DynTypedMatcher &Other) {
665     return Other.dynCastTo(ASTNodeKind::getFromNodeKind<T>());
666   }
667 
668   explicit Matcher(const DynTypedMatcher &Implementation)
669       : Implementation(restrictMatcher(Implementation)) {
670     assert(this->Implementation.getSupportedKind().isSame(
671         ASTNodeKind::getFromNodeKind<T>()));
672   }
673 
674   DynTypedMatcher Implementation;
675 };  // class Matcher
676 
677 /// A convenient helper for creating a Matcher<T> without specifying
678 /// the template type argument.
679 template <typename T>
680 inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) {
681   return Matcher<T>(Implementation);
682 }
683 
684 /// Interface that allows matchers to traverse the AST.
685 /// FIXME: Find a better name.
686 ///
687 /// This provides three entry methods for each base node type in the AST:
688 /// - \c matchesChildOf:
689 ///   Matches a matcher on every child node of the given node. Returns true
690 ///   if at least one child node could be matched.
691 /// - \c matchesDescendantOf:
692 ///   Matches a matcher on all descendant nodes of the given node. Returns true
693 ///   if at least one descendant matched.
694 /// - \c matchesAncestorOf:
695 ///   Matches a matcher on all ancestors of the given node. Returns true if
696 ///   at least one ancestor matched.
697 ///
698 /// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal.
699 /// In the future, we want to implement this for all nodes for which it makes
700 /// sense. In the case of matchesAncestorOf, we'll want to implement it for
701 /// all nodes, as all nodes have ancestors.
702 class ASTMatchFinder {
703 public:
704   /// Defines how bindings are processed on recursive matches.
705   enum BindKind {
706     /// Stop at the first match and only bind the first match.
707     BK_First,
708 
709     /// Create results for all combinations of bindings that match.
710     BK_All
711   };
712 
713   /// Defines which ancestors are considered for a match.
714   enum AncestorMatchMode {
715     /// All ancestors.
716     AMM_All,
717 
718     /// Direct parent only.
719     AMM_ParentOnly
720   };
721 
722   virtual ~ASTMatchFinder() = default;
723 
724   /// Returns true if the given C++ class is directly or indirectly derived
725   /// from a base type matching \c base.
726   ///
727   /// A class is not considered to be derived from itself.
728   virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
729                                   const Matcher<NamedDecl> &Base,
730                                   BoundNodesTreeBuilder *Builder,
731                                   bool Directly) = 0;
732 
733   /// Returns true if the given Objective-C class is directly or indirectly
734   /// derived from a base class matching \c base.
735   ///
736   /// A class is not considered to be derived from itself.
737   virtual bool objcClassIsDerivedFrom(const ObjCInterfaceDecl *Declaration,
738                                       const Matcher<NamedDecl> &Base,
739                                       BoundNodesTreeBuilder *Builder,
740                                       bool Directly) = 0;
741 
742   template <typename T>
743   bool matchesChildOf(const T &Node, const DynTypedMatcher &Matcher,
744                       BoundNodesTreeBuilder *Builder, BindKind Bind) {
745     static_assert(std::is_base_of<Decl, T>::value ||
746                       std::is_base_of<Stmt, T>::value ||
747                       std::is_base_of<NestedNameSpecifier, T>::value ||
748                       std::is_base_of<NestedNameSpecifierLoc, T>::value ||
749                       std::is_base_of<TypeLoc, T>::value ||
750                       std::is_base_of<QualType, T>::value ||
751                       std::is_base_of<Attr, T>::value,
752                   "unsupported type for recursive matching");
753     return matchesChildOf(DynTypedNode::create(Node), getASTContext(), Matcher,
754                           Builder, Bind);
755   }
756 
757   template <typename T>
758   bool matchesDescendantOf(const T &Node, const DynTypedMatcher &Matcher,
759                            BoundNodesTreeBuilder *Builder, BindKind Bind) {
760     static_assert(std::is_base_of<Decl, T>::value ||
761                       std::is_base_of<Stmt, T>::value ||
762                       std::is_base_of<NestedNameSpecifier, T>::value ||
763                       std::is_base_of<NestedNameSpecifierLoc, T>::value ||
764                       std::is_base_of<TypeLoc, T>::value ||
765                       std::is_base_of<QualType, T>::value ||
766                       std::is_base_of<Attr, T>::value,
767                   "unsupported type for recursive matching");
768     return matchesDescendantOf(DynTypedNode::create(Node), getASTContext(),
769                                Matcher, Builder, Bind);
770   }
771 
772   // FIXME: Implement support for BindKind.
773   template <typename T>
774   bool matchesAncestorOf(const T &Node, const DynTypedMatcher &Matcher,
775                          BoundNodesTreeBuilder *Builder,
776                          AncestorMatchMode MatchMode) {
777     static_assert(std::is_base_of<Decl, T>::value ||
778                       std::is_base_of<NestedNameSpecifierLoc, T>::value ||
779                       std::is_base_of<Stmt, T>::value ||
780                       std::is_base_of<TypeLoc, T>::value ||
781                       std::is_base_of<Attr, T>::value,
782                   "type not allowed for recursive matching");
783     return matchesAncestorOf(DynTypedNode::create(Node), getASTContext(),
784                              Matcher, Builder, MatchMode);
785   }
786 
787   virtual ASTContext &getASTContext() const = 0;
788 
789   virtual bool IsMatchingInASTNodeNotSpelledInSource() const = 0;
790 
791   virtual bool IsMatchingInASTNodeNotAsIs() const = 0;
792 
793   bool isTraversalIgnoringImplicitNodes() const;
794 
795 protected:
796   virtual bool matchesChildOf(const DynTypedNode &Node, ASTContext &Ctx,
797                               const DynTypedMatcher &Matcher,
798                               BoundNodesTreeBuilder *Builder,
799                               BindKind Bind) = 0;
800 
801   virtual bool matchesDescendantOf(const DynTypedNode &Node, ASTContext &Ctx,
802                                    const DynTypedMatcher &Matcher,
803                                    BoundNodesTreeBuilder *Builder,
804                                    BindKind Bind) = 0;
805 
806   virtual bool matchesAncestorOf(const DynTypedNode &Node, ASTContext &Ctx,
807                                  const DynTypedMatcher &Matcher,
808                                  BoundNodesTreeBuilder *Builder,
809                                  AncestorMatchMode MatchMode) = 0;
810 private:
811   friend struct ASTChildrenNotSpelledInSourceScope;
812   virtual bool isMatchingChildrenNotSpelledInSource() const = 0;
813   virtual void setMatchingChildrenNotSpelledInSource(bool Set) = 0;
814 };
815 
816 struct ASTChildrenNotSpelledInSourceScope {
817   ASTChildrenNotSpelledInSourceScope(ASTMatchFinder *V, bool B)
818       : MV(V), MB(V->isMatchingChildrenNotSpelledInSource()) {
819     V->setMatchingChildrenNotSpelledInSource(B);
820   }
821   ~ASTChildrenNotSpelledInSourceScope() {
822     MV->setMatchingChildrenNotSpelledInSource(MB);
823   }
824 
825 private:
826   ASTMatchFinder *MV;
827   bool MB;
828 };
829 
830 /// Specialization of the conversion functions for QualType.
831 ///
832 /// This specialization provides the Matcher<Type>->Matcher<QualType>
833 /// conversion that the static API does.
834 template <>
835 inline Matcher<QualType> DynTypedMatcher::convertTo<QualType>() const {
836   assert(canConvertTo<QualType>());
837   const ASTNodeKind SourceKind = getSupportedKind();
838   if (SourceKind.isSame(ASTNodeKind::getFromNodeKind<Type>())) {
839     // We support implicit conversion from Matcher<Type> to Matcher<QualType>
840     return unconditionalConvertTo<Type>();
841   }
842   return unconditionalConvertTo<QualType>();
843 }
844 
845 /// Finds the first node in a range that matches the given matcher.
846 template <typename MatcherT, typename IteratorT>
847 IteratorT matchesFirstInRange(const MatcherT &Matcher, IteratorT Start,
848                               IteratorT End, ASTMatchFinder *Finder,
849                               BoundNodesTreeBuilder *Builder) {
850   for (IteratorT I = Start; I != End; ++I) {
851     BoundNodesTreeBuilder Result(*Builder);
852     if (Matcher.matches(*I, Finder, &Result)) {
853       *Builder = std::move(Result);
854       return I;
855     }
856   }
857   return End;
858 }
859 
860 /// Finds the first node in a pointer range that matches the given
861 /// matcher.
862 template <typename MatcherT, typename IteratorT>
863 IteratorT matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start,
864                                      IteratorT End, ASTMatchFinder *Finder,
865                                      BoundNodesTreeBuilder *Builder) {
866   for (IteratorT I = Start; I != End; ++I) {
867     BoundNodesTreeBuilder Result(*Builder);
868     if (Matcher.matches(**I, Finder, &Result)) {
869       *Builder = std::move(Result);
870       return I;
871     }
872   }
873   return End;
874 }
875 
876 template <typename T, std::enable_if_t<!std::is_base_of<FunctionDecl, T>::value>
877                           * = nullptr>
878 inline bool isDefaultedHelper(const T *) {
879   return false;
880 }
881 inline bool isDefaultedHelper(const FunctionDecl *FD) {
882   return FD->isDefaulted();
883 }
884 
885 // Metafunction to determine if type T has a member called getDecl.
886 template <typename Ty>
887 class has_getDecl {
888   using yes = char[1];
889   using no = char[2];
890 
891   template <typename Inner>
892   static yes& test(Inner *I, decltype(I->getDecl()) * = nullptr);
893 
894   template <typename>
895   static no& test(...);
896 
897 public:
898   static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
899 };
900 
901 /// Matches overloaded operators with a specific name.
902 ///
903 /// The type argument ArgT is not used by this matcher but is used by
904 /// PolymorphicMatcher and should be StringRef.
905 template <typename T, typename ArgT>
906 class HasOverloadedOperatorNameMatcher : public SingleNodeMatcherInterface<T> {
907   static_assert(std::is_same<T, CXXOperatorCallExpr>::value ||
908                 std::is_base_of<FunctionDecl, T>::value,
909                 "unsupported class for matcher");
910   static_assert(std::is_same<ArgT, std::vector<std::string>>::value,
911                 "argument type must be std::vector<std::string>");
912 
913 public:
914   explicit HasOverloadedOperatorNameMatcher(std::vector<std::string> Names)
915       : SingleNodeMatcherInterface<T>(), Names(std::move(Names)) {}
916 
917   bool matchesNode(const T &Node) const override {
918     return matchesSpecialized(Node);
919   }
920 
921 private:
922 
923   /// CXXOperatorCallExpr exist only for calls to overloaded operators
924   /// so this function returns true if the call is to an operator of the given
925   /// name.
926   bool matchesSpecialized(const CXXOperatorCallExpr &Node) const {
927     return llvm::is_contained(Names, getOperatorSpelling(Node.getOperator()));
928   }
929 
930   /// Returns true only if CXXMethodDecl represents an overloaded
931   /// operator and has the given operator name.
932   bool matchesSpecialized(const FunctionDecl &Node) const {
933     return Node.isOverloadedOperator() &&
934            llvm::is_contained(
935                Names, getOperatorSpelling(Node.getOverloadedOperator()));
936   }
937 
938   std::vector<std::string> Names;
939 };
940 
941 /// Matches named declarations with a specific name.
942 ///
943 /// See \c hasName() and \c hasAnyName() in ASTMatchers.h for details.
944 class HasNameMatcher : public SingleNodeMatcherInterface<NamedDecl> {
945  public:
946   explicit HasNameMatcher(std::vector<std::string> Names);
947 
948   bool matchesNode(const NamedDecl &Node) const override;
949 
950 private:
951   /// Unqualified match routine.
952   ///
953   /// It is much faster than the full match, but it only works for unqualified
954   /// matches.
955   bool matchesNodeUnqualified(const NamedDecl &Node) const;
956 
957   /// Full match routine
958   ///
959   /// Fast implementation for the simple case of a named declaration at
960   /// namespace or RecordDecl scope.
961   /// It is slower than matchesNodeUnqualified, but faster than
962   /// matchesNodeFullSlow.
963   bool matchesNodeFullFast(const NamedDecl &Node) const;
964 
965   /// Full match routine
966   ///
967   /// It generates the fully qualified name of the declaration (which is
968   /// expensive) before trying to match.
969   /// It is slower but simple and works on all cases.
970   bool matchesNodeFullSlow(const NamedDecl &Node) const;
971 
972   bool UseUnqualifiedMatch;
973   std::vector<std::string> Names;
974 };
975 
976 /// Trampoline function to use VariadicFunction<> to construct a
977 ///        HasNameMatcher.
978 Matcher<NamedDecl> hasAnyNameFunc(ArrayRef<const StringRef *> NameRefs);
979 
980 /// Trampoline function to use VariadicFunction<> to construct a
981 ///        hasAnySelector matcher.
982 Matcher<ObjCMessageExpr> hasAnySelectorFunc(
983     ArrayRef<const StringRef *> NameRefs);
984 
985 /// Matches declarations for QualType and CallExpr.
986 ///
987 /// Type argument DeclMatcherT is required by PolymorphicMatcher but
988 /// not actually used.
989 template <typename T, typename DeclMatcherT>
990 class HasDeclarationMatcher : public MatcherInterface<T> {
991   static_assert(std::is_same<DeclMatcherT, Matcher<Decl>>::value,
992                 "instantiated with wrong types");
993 
994   DynTypedMatcher InnerMatcher;
995 
996 public:
997   explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher)
998       : InnerMatcher(InnerMatcher) {}
999 
1000   bool matches(const T &Node, ASTMatchFinder *Finder,
1001                BoundNodesTreeBuilder *Builder) const override {
1002     return matchesSpecialized(Node, Finder, Builder);
1003   }
1004 
1005 private:
1006   /// Forwards to matching on the underlying type of the QualType.
1007   bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder,
1008                           BoundNodesTreeBuilder *Builder) const {
1009     if (Node.isNull())
1010       return false;
1011 
1012     return matchesSpecialized(*Node, Finder, Builder);
1013   }
1014 
1015   /// Finds the best declaration for a type and returns whether the inner
1016   /// matcher matches on it.
1017   bool matchesSpecialized(const Type &Node, ASTMatchFinder *Finder,
1018                           BoundNodesTreeBuilder *Builder) const {
1019     // DeducedType does not have declarations of its own, so
1020     // match the deduced type instead.
1021     if (const auto *S = dyn_cast<DeducedType>(&Node)) {
1022       QualType DT = S->getDeducedType();
1023       return !DT.isNull() ? matchesSpecialized(*DT, Finder, Builder) : false;
1024     }
1025 
1026     // First, for any types that have a declaration, extract the declaration and
1027     // match on it.
1028     if (const auto *S = dyn_cast<TagType>(&Node)) {
1029       return matchesDecl(S->getDecl(), Finder, Builder);
1030     }
1031     if (const auto *S = dyn_cast<InjectedClassNameType>(&Node)) {
1032       return matchesDecl(S->getDecl(), Finder, Builder);
1033     }
1034     if (const auto *S = dyn_cast<TemplateTypeParmType>(&Node)) {
1035       return matchesDecl(S->getDecl(), Finder, Builder);
1036     }
1037     if (const auto *S = dyn_cast<TypedefType>(&Node)) {
1038       return matchesDecl(S->getDecl(), Finder, Builder);
1039     }
1040     if (const auto *S = dyn_cast<UnresolvedUsingType>(&Node)) {
1041       return matchesDecl(S->getDecl(), Finder, Builder);
1042     }
1043     if (const auto *S = dyn_cast<ObjCObjectType>(&Node)) {
1044       return matchesDecl(S->getInterface(), Finder, Builder);
1045     }
1046 
1047     // A SubstTemplateTypeParmType exists solely to mark a type substitution
1048     // on the instantiated template. As users usually want to match the
1049     // template parameter on the uninitialized template, we can always desugar
1050     // one level without loss of expressivness.
1051     // For example, given:
1052     //   template<typename T> struct X { T t; } class A {}; X<A> a;
1053     // The following matcher will match, which otherwise would not:
1054     //   fieldDecl(hasType(pointerType())).
1055     if (const auto *S = dyn_cast<SubstTemplateTypeParmType>(&Node)) {
1056       return matchesSpecialized(S->getReplacementType(), Finder, Builder);
1057     }
1058 
1059     // For template specialization types, we want to match the template
1060     // declaration, as long as the type is still dependent, and otherwise the
1061     // declaration of the instantiated tag type.
1062     if (const auto *S = dyn_cast<TemplateSpecializationType>(&Node)) {
1063       if (!S->isTypeAlias() && S->isSugared()) {
1064         // If the template is non-dependent, we want to match the instantiated
1065         // tag type.
1066         // For example, given:
1067         //   template<typename T> struct X {}; X<int> a;
1068         // The following matcher will match, which otherwise would not:
1069         //   templateSpecializationType(hasDeclaration(cxxRecordDecl())).
1070         return matchesSpecialized(*S->desugar(), Finder, Builder);
1071       }
1072       // If the template is dependent or an alias, match the template
1073       // declaration.
1074       return matchesDecl(S->getTemplateName().getAsTemplateDecl(), Finder,
1075                          Builder);
1076     }
1077 
1078     // FIXME: We desugar elaborated types. This makes the assumption that users
1079     // do never want to match on whether a type is elaborated - there are
1080     // arguments for both sides; for now, continue desugaring.
1081     if (const auto *S = dyn_cast<ElaboratedType>(&Node)) {
1082       return matchesSpecialized(S->desugar(), Finder, Builder);
1083     }
1084     // Similarly types found via using declarations.
1085     // These are *usually* meaningless sugar, and this matches the historical
1086     // behavior prior to the introduction of UsingType.
1087     if (const auto *S = dyn_cast<UsingType>(&Node)) {
1088       return matchesSpecialized(S->desugar(), Finder, Builder);
1089     }
1090     return false;
1091   }
1092 
1093   /// Extracts the Decl the DeclRefExpr references and returns whether
1094   /// the inner matcher matches on it.
1095   bool matchesSpecialized(const DeclRefExpr &Node, ASTMatchFinder *Finder,
1096                           BoundNodesTreeBuilder *Builder) const {
1097     return matchesDecl(Node.getDecl(), Finder, Builder);
1098   }
1099 
1100   /// Extracts the Decl of the callee of a CallExpr and returns whether
1101   /// the inner matcher matches on it.
1102   bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder,
1103                           BoundNodesTreeBuilder *Builder) const {
1104     return matchesDecl(Node.getCalleeDecl(), Finder, Builder);
1105   }
1106 
1107   /// Extracts the Decl of the constructor call and returns whether the
1108   /// inner matcher matches on it.
1109   bool matchesSpecialized(const CXXConstructExpr &Node,
1110                           ASTMatchFinder *Finder,
1111                           BoundNodesTreeBuilder *Builder) const {
1112     return matchesDecl(Node.getConstructor(), Finder, Builder);
1113   }
1114 
1115   bool matchesSpecialized(const ObjCIvarRefExpr &Node,
1116                           ASTMatchFinder *Finder,
1117                           BoundNodesTreeBuilder *Builder) const {
1118     return matchesDecl(Node.getDecl(), Finder, Builder);
1119   }
1120 
1121   /// Extracts the operator new of the new call and returns whether the
1122   /// inner matcher matches on it.
1123   bool matchesSpecialized(const CXXNewExpr &Node,
1124                           ASTMatchFinder *Finder,
1125                           BoundNodesTreeBuilder *Builder) const {
1126     return matchesDecl(Node.getOperatorNew(), Finder, Builder);
1127   }
1128 
1129   /// Extracts the \c ValueDecl a \c MemberExpr refers to and returns
1130   /// whether the inner matcher matches on it.
1131   bool matchesSpecialized(const MemberExpr &Node,
1132                           ASTMatchFinder *Finder,
1133                           BoundNodesTreeBuilder *Builder) const {
1134     return matchesDecl(Node.getMemberDecl(), Finder, Builder);
1135   }
1136 
1137   /// Extracts the \c LabelDecl a \c AddrLabelExpr refers to and returns
1138   /// whether the inner matcher matches on it.
1139   bool matchesSpecialized(const AddrLabelExpr &Node,
1140                           ASTMatchFinder *Finder,
1141                           BoundNodesTreeBuilder *Builder) const {
1142     return matchesDecl(Node.getLabel(), Finder, Builder);
1143   }
1144 
1145   /// Extracts the declaration of a LabelStmt and returns whether the
1146   /// inner matcher matches on it.
1147   bool matchesSpecialized(const LabelStmt &Node, ASTMatchFinder *Finder,
1148                           BoundNodesTreeBuilder *Builder) const {
1149     return matchesDecl(Node.getDecl(), Finder, Builder);
1150   }
1151 
1152   /// Returns whether the inner matcher \c Node. Returns false if \c Node
1153   /// is \c NULL.
1154   bool matchesDecl(const Decl *Node, ASTMatchFinder *Finder,
1155                    BoundNodesTreeBuilder *Builder) const {
1156     return Node != nullptr &&
1157            !(Finder->isTraversalIgnoringImplicitNodes() &&
1158              Node->isImplicit()) &&
1159            this->InnerMatcher.matches(DynTypedNode::create(*Node), Finder,
1160                                       Builder);
1161   }
1162 };
1163 
1164 /// IsBaseType<T>::value is true if T is a "base" type in the AST
1165 /// node class hierarchies.
1166 template <typename T>
1167 struct IsBaseType {
1168   static const bool value =
1169       std::is_same<T, Decl>::value || std::is_same<T, Stmt>::value ||
1170       std::is_same<T, QualType>::value || std::is_same<T, Type>::value ||
1171       std::is_same<T, TypeLoc>::value ||
1172       std::is_same<T, NestedNameSpecifier>::value ||
1173       std::is_same<T, NestedNameSpecifierLoc>::value ||
1174       std::is_same<T, CXXCtorInitializer>::value ||
1175       std::is_same<T, TemplateArgumentLoc>::value ||
1176       std::is_same<T, Attr>::value;
1177 };
1178 template <typename T>
1179 const bool IsBaseType<T>::value;
1180 
1181 /// A "type list" that contains all types.
1182 ///
1183 /// Useful for matchers like \c anything and \c unless.
1184 using AllNodeBaseTypes =
1185     TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc, QualType,
1186              Type, TypeLoc, CXXCtorInitializer, Attr>;
1187 
1188 /// Helper meta-function to extract the argument out of a function of
1189 ///   type void(Arg).
1190 ///
1191 /// See AST_POLYMORPHIC_SUPPORTED_TYPES for details.
1192 template <class T> struct ExtractFunctionArgMeta;
1193 template <class T> struct ExtractFunctionArgMeta<void(T)> {
1194   using type = T;
1195 };
1196 
1197 template <class T, class Tuple, std::size_t... I>
1198 constexpr T *new_from_tuple_impl(Tuple &&t, std::index_sequence<I...>) {
1199   return new T(std::get<I>(std::forward<Tuple>(t))...);
1200 }
1201 
1202 template <class T, class Tuple> constexpr T *new_from_tuple(Tuple &&t) {
1203   return new_from_tuple_impl<T>(
1204       std::forward<Tuple>(t),
1205       std::make_index_sequence<
1206           std::tuple_size<std::remove_reference_t<Tuple>>::value>{});
1207 }
1208 
1209 /// Default type lists for ArgumentAdaptingMatcher matchers.
1210 using AdaptativeDefaultFromTypes = AllNodeBaseTypes;
1211 using AdaptativeDefaultToTypes =
1212     TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc, TypeLoc,
1213              QualType, Attr>;
1214 
1215 /// All types that are supported by HasDeclarationMatcher above.
1216 using HasDeclarationSupportedTypes =
1217     TypeList<CallExpr, CXXConstructExpr, CXXNewExpr, DeclRefExpr, EnumType,
1218              ElaboratedType, InjectedClassNameType, LabelStmt, AddrLabelExpr,
1219              MemberExpr, QualType, RecordType, TagType,
1220              TemplateSpecializationType, TemplateTypeParmType, TypedefType,
1221              UnresolvedUsingType, ObjCIvarRefExpr>;
1222 
1223 /// A Matcher that allows binding the node it matches to an id.
1224 ///
1225 /// BindableMatcher provides a \a bind() method that allows binding the
1226 /// matched node to an id if the match was successful.
1227 template <typename T> class BindableMatcher : public Matcher<T> {
1228 public:
1229   explicit BindableMatcher(const Matcher<T> &M) : Matcher<T>(M) {}
1230   explicit BindableMatcher(MatcherInterface<T> *Implementation)
1231       : Matcher<T>(Implementation) {}
1232 
1233   /// Returns a matcher that will bind the matched node on a match.
1234   ///
1235   /// The returned matcher is equivalent to this matcher, but will
1236   /// bind the matched node on a match.
1237   Matcher<T> bind(StringRef ID) const {
1238     return DynTypedMatcher(*this)
1239         .tryBind(ID)
1240         ->template unconditionalConvertTo<T>();
1241   }
1242 
1243   /// Same as Matcher<T>'s conversion operator, but enables binding on
1244   /// the returned matcher.
1245   operator DynTypedMatcher() const {
1246     DynTypedMatcher Result = static_cast<const Matcher<T> &>(*this);
1247     Result.setAllowBind(true);
1248     return Result;
1249   }
1250 };
1251 
1252 /// Matches any instance of the given NodeType.
1253 ///
1254 /// This is useful when a matcher syntactically requires a child matcher,
1255 /// but the context doesn't care. See for example: anything().
1256 class TrueMatcher {
1257 public:
1258   using ReturnTypes = AllNodeBaseTypes;
1259 
1260   template <typename T> operator Matcher<T>() const {
1261     return DynTypedMatcher::trueMatcher(ASTNodeKind::getFromNodeKind<T>())
1262         .template unconditionalConvertTo<T>();
1263   }
1264 };
1265 
1266 /// Creates a Matcher<T> that matches if all inner matchers match.
1267 template <typename T>
1268 BindableMatcher<T>
1269 makeAllOfComposite(ArrayRef<const Matcher<T> *> InnerMatchers) {
1270   // For the size() == 0 case, we return a "true" matcher.
1271   if (InnerMatchers.empty()) {
1272     return BindableMatcher<T>(TrueMatcher());
1273   }
1274   // For the size() == 1 case, we simply return that one matcher.
1275   // No need to wrap it in a variadic operation.
1276   if (InnerMatchers.size() == 1) {
1277     return BindableMatcher<T>(*InnerMatchers[0]);
1278   }
1279 
1280   using PI = llvm::pointee_iterator<const Matcher<T> *const *>;
1281 
1282   std::vector<DynTypedMatcher> DynMatchers(PI(InnerMatchers.begin()),
1283                                            PI(InnerMatchers.end()));
1284   return BindableMatcher<T>(
1285       DynTypedMatcher::constructVariadic(DynTypedMatcher::VO_AllOf,
1286                                          ASTNodeKind::getFromNodeKind<T>(),
1287                                          std::move(DynMatchers))
1288           .template unconditionalConvertTo<T>());
1289 }
1290 
1291 /// Creates a Matcher<T> that matches if
1292 /// T is dyn_cast'able into InnerT and all inner matchers match.
1293 ///
1294 /// Returns BindableMatcher, as matchers that use dyn_cast have
1295 /// the same object both to match on and to run submatchers on,
1296 /// so there is no ambiguity with what gets bound.
1297 template <typename T, typename InnerT>
1298 BindableMatcher<T>
1299 makeDynCastAllOfComposite(ArrayRef<const Matcher<InnerT> *> InnerMatchers) {
1300   return BindableMatcher<T>(
1301       makeAllOfComposite(InnerMatchers).template dynCastTo<T>());
1302 }
1303 
1304 /// A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a
1305 /// variadic functor that takes a number of Matcher<TargetT> and returns a
1306 /// Matcher<SourceT> that matches TargetT nodes that are matched by all of the
1307 /// given matchers, if SourceT can be dynamically casted into TargetT.
1308 ///
1309 /// For example:
1310 ///   const VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl> record;
1311 /// Creates a functor record(...) that creates a Matcher<Decl> given
1312 /// a variable number of arguments of type Matcher<CXXRecordDecl>.
1313 /// The returned matcher matches if the given Decl can by dynamically
1314 /// casted to CXXRecordDecl and all given matchers match.
1315 template <typename SourceT, typename TargetT>
1316 class VariadicDynCastAllOfMatcher
1317     : public VariadicFunction<BindableMatcher<SourceT>, Matcher<TargetT>,
1318                               makeDynCastAllOfComposite<SourceT, TargetT>> {
1319 public:
1320   VariadicDynCastAllOfMatcher() {}
1321 };
1322 
1323 /// A \c VariadicAllOfMatcher<T> object is a variadic functor that takes
1324 /// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T
1325 /// nodes that are matched by all of the given matchers.
1326 ///
1327 /// For example:
1328 ///   const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
1329 /// Creates a functor nestedNameSpecifier(...) that creates a
1330 /// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type
1331 /// \c Matcher<NestedNameSpecifier>.
1332 /// The returned matcher matches if all given matchers match.
1333 template <typename T>
1334 class VariadicAllOfMatcher
1335     : public VariadicFunction<BindableMatcher<T>, Matcher<T>,
1336                               makeAllOfComposite<T>> {
1337 public:
1338   VariadicAllOfMatcher() {}
1339 };
1340 
1341 /// VariadicOperatorMatcher related types.
1342 /// @{
1343 
1344 /// Polymorphic matcher object that uses a \c
1345 /// DynTypedMatcher::VariadicOperator operator.
1346 ///
1347 /// Input matchers can have any type (including other polymorphic matcher
1348 /// types), and the actual Matcher<T> is generated on demand with an implicit
1349 /// conversion operator.
1350 template <typename... Ps> class VariadicOperatorMatcher {
1351 public:
1352   VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op, Ps &&... Params)
1353       : Op(Op), Params(std::forward<Ps>(Params)...) {}
1354 
1355   template <typename T> operator Matcher<T>() const & {
1356     return DynTypedMatcher::constructVariadic(
1357                Op, ASTNodeKind::getFromNodeKind<T>(),
1358                getMatchers<T>(std::index_sequence_for<Ps...>()))
1359         .template unconditionalConvertTo<T>();
1360   }
1361 
1362   template <typename T> operator Matcher<T>() && {
1363     return DynTypedMatcher::constructVariadic(
1364                Op, ASTNodeKind::getFromNodeKind<T>(),
1365                getMatchers<T>(std::index_sequence_for<Ps...>()))
1366         .template unconditionalConvertTo<T>();
1367   }
1368 
1369 private:
1370   // Helper method to unpack the tuple into a vector.
1371   template <typename T, std::size_t... Is>
1372   std::vector<DynTypedMatcher> getMatchers(std::index_sequence<Is...>) const & {
1373     return {Matcher<T>(std::get<Is>(Params))...};
1374   }
1375 
1376   template <typename T, std::size_t... Is>
1377   std::vector<DynTypedMatcher> getMatchers(std::index_sequence<Is...>) && {
1378     return {Matcher<T>(std::get<Is>(std::move(Params)))...};
1379   }
1380 
1381   const DynTypedMatcher::VariadicOperator Op;
1382   std::tuple<Ps...> Params;
1383 };
1384 
1385 /// Overloaded function object to generate VariadicOperatorMatcher
1386 ///   objects from arbitrary matchers.
1387 template <unsigned MinCount, unsigned MaxCount>
1388 struct VariadicOperatorMatcherFunc {
1389   DynTypedMatcher::VariadicOperator Op;
1390 
1391   template <typename... Ms>
1392   VariadicOperatorMatcher<Ms...> operator()(Ms &&... Ps) const {
1393     static_assert(MinCount <= sizeof...(Ms) && sizeof...(Ms) <= MaxCount,
1394                   "invalid number of parameters for variadic matcher");
1395     return VariadicOperatorMatcher<Ms...>(Op, std::forward<Ms>(Ps)...);
1396   }
1397 };
1398 
1399 template <typename F, typename Tuple, std::size_t... I>
1400 constexpr auto applyMatcherImpl(F &&f, Tuple &&args,
1401                                 std::index_sequence<I...>) {
1402   return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(args))...);
1403 }
1404 
1405 template <typename F, typename Tuple>
1406 constexpr auto applyMatcher(F &&f, Tuple &&args) {
1407   return applyMatcherImpl(
1408       std::forward<F>(f), std::forward<Tuple>(args),
1409       std::make_index_sequence<
1410           std::tuple_size<typename std::decay<Tuple>::type>::value>());
1411 }
1412 
1413 template <typename T, bool IsBaseOf, typename Head, typename Tail>
1414 struct GetCladeImpl {
1415   using Type = Head;
1416 };
1417 template <typename T, typename Head, typename Tail>
1418 struct GetCladeImpl<T, false, Head, Tail>
1419     : GetCladeImpl<T, std::is_base_of<typename Tail::head, T>::value,
1420                    typename Tail::head, typename Tail::tail> {};
1421 
1422 template <typename T, typename... U>
1423 struct GetClade : GetCladeImpl<T, false, T, AllNodeBaseTypes> {};
1424 
1425 template <typename CladeType, typename... MatcherTypes>
1426 struct MapAnyOfMatcherImpl {
1427 
1428   template <typename... InnerMatchers>
1429   BindableMatcher<CladeType>
1430   operator()(InnerMatchers &&... InnerMatcher) const {
1431     // TODO: Use std::apply from c++17
1432     return VariadicAllOfMatcher<CladeType>()(applyMatcher(
1433         internal::VariadicOperatorMatcherFunc<
1434             0, std::numeric_limits<unsigned>::max()>{
1435             internal::DynTypedMatcher::VO_AnyOf},
1436         applyMatcher(
1437             [&](auto... Matcher) {
1438               return std::make_tuple(Matcher(InnerMatcher...)...);
1439             },
1440             std::tuple<
1441                 VariadicDynCastAllOfMatcher<CladeType, MatcherTypes>...>())));
1442   }
1443 };
1444 
1445 template <typename... MatcherTypes>
1446 using MapAnyOfMatcher =
1447     MapAnyOfMatcherImpl<typename GetClade<MatcherTypes...>::Type,
1448                         MatcherTypes...>;
1449 
1450 template <typename... MatcherTypes> struct MapAnyOfHelper {
1451   using CladeType = typename GetClade<MatcherTypes...>::Type;
1452 
1453   MapAnyOfMatcher<MatcherTypes...> with;
1454 
1455   operator BindableMatcher<CladeType>() const { return with(); }
1456 
1457   Matcher<CladeType> bind(StringRef ID) const { return with().bind(ID); }
1458 };
1459 
1460 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
1461           typename T, typename ToTypes>
1462 class ArgumentAdaptingMatcherFuncAdaptor {
1463 public:
1464   explicit ArgumentAdaptingMatcherFuncAdaptor(const Matcher<T> &InnerMatcher)
1465       : InnerMatcher(InnerMatcher) {}
1466 
1467   using ReturnTypes = ToTypes;
1468 
1469   template <typename To> operator Matcher<To>() const & {
1470     return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher));
1471   }
1472 
1473   template <typename To> operator Matcher<To>() && {
1474     return Matcher<To>(new ArgumentAdapterT<To, T>(std::move(InnerMatcher)));
1475   }
1476 
1477 private:
1478   Matcher<T> InnerMatcher;
1479 };
1480 
1481 /// Converts a \c Matcher<T> to a matcher of desired type \c To by
1482 /// "adapting" a \c To into a \c T.
1483 ///
1484 /// The \c ArgumentAdapterT argument specifies how the adaptation is done.
1485 ///
1486 /// For example:
1487 ///   \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher);
1488 /// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher
1489 /// that is convertible into any matcher of type \c To by constructing
1490 /// \c HasMatcher<To, T>(InnerMatcher).
1491 ///
1492 /// If a matcher does not need knowledge about the inner type, prefer to use
1493 /// PolymorphicMatcher.
1494 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
1495           typename FromTypes = AdaptativeDefaultFromTypes,
1496           typename ToTypes = AdaptativeDefaultToTypes>
1497 struct ArgumentAdaptingMatcherFunc {
1498   template <typename T>
1499   static ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>
1500   create(const Matcher<T> &InnerMatcher) {
1501     return ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>(
1502         InnerMatcher);
1503   }
1504 
1505   template <typename T>
1506   ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>
1507   operator()(const Matcher<T> &InnerMatcher) const {
1508     return create(InnerMatcher);
1509   }
1510 
1511   template <typename... T>
1512   ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT,
1513                                      typename GetClade<T...>::Type, ToTypes>
1514   operator()(const MapAnyOfHelper<T...> &InnerMatcher) const {
1515     return create(InnerMatcher.with());
1516   }
1517 };
1518 
1519 template <typename T> class TraversalMatcher : public MatcherInterface<T> {
1520   DynTypedMatcher InnerMatcher;
1521   clang::TraversalKind Traversal;
1522 
1523 public:
1524   explicit TraversalMatcher(clang::TraversalKind TK,
1525                             const Matcher<T> &InnerMatcher)
1526       : InnerMatcher(InnerMatcher), Traversal(TK) {}
1527 
1528   bool matches(const T &Node, ASTMatchFinder *Finder,
1529                BoundNodesTreeBuilder *Builder) const override {
1530     return this->InnerMatcher.matches(DynTypedNode::create(Node), Finder,
1531                                       Builder);
1532   }
1533 
1534   llvm::Optional<clang::TraversalKind> TraversalKind() const override {
1535     if (auto NestedKind = this->InnerMatcher.getTraversalKind())
1536       return NestedKind;
1537     return Traversal;
1538   }
1539 };
1540 
1541 template <typename MatcherType> class TraversalWrapper {
1542 public:
1543   TraversalWrapper(TraversalKind TK, const MatcherType &InnerMatcher)
1544       : TK(TK), InnerMatcher(InnerMatcher) {}
1545 
1546   template <typename T> operator Matcher<T>() const & {
1547     return internal::DynTypedMatcher::constructRestrictedWrapper(
1548                new internal::TraversalMatcher<T>(TK, InnerMatcher),
1549                ASTNodeKind::getFromNodeKind<T>())
1550         .template unconditionalConvertTo<T>();
1551   }
1552 
1553   template <typename T> operator Matcher<T>() && {
1554     return internal::DynTypedMatcher::constructRestrictedWrapper(
1555                new internal::TraversalMatcher<T>(TK, std::move(InnerMatcher)),
1556                ASTNodeKind::getFromNodeKind<T>())
1557         .template unconditionalConvertTo<T>();
1558   }
1559 
1560 private:
1561   TraversalKind TK;
1562   MatcherType InnerMatcher;
1563 };
1564 
1565 /// A PolymorphicMatcher<MatcherT, P1, ..., PN> object can be
1566 /// created from N parameters p1, ..., pN (of type P1, ..., PN) and
1567 /// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN)
1568 /// can be constructed.
1569 ///
1570 /// For example:
1571 /// - PolymorphicMatcher<IsDefinitionMatcher>()
1572 ///   creates an object that can be used as a Matcher<T> for any type T
1573 ///   where an IsDefinitionMatcher<T>() can be constructed.
1574 /// - PolymorphicMatcher<ValueEqualsMatcher, int>(42)
1575 ///   creates an object that can be used as a Matcher<T> for any type T
1576 ///   where a ValueEqualsMatcher<T, int>(42) can be constructed.
1577 template <template <typename T, typename... Params> class MatcherT,
1578           typename ReturnTypesF, typename... ParamTypes>
1579 class PolymorphicMatcher {
1580 public:
1581   PolymorphicMatcher(const ParamTypes &... Params) : Params(Params...) {}
1582 
1583   using ReturnTypes = typename ExtractFunctionArgMeta<ReturnTypesF>::type;
1584 
1585   template <typename T> operator Matcher<T>() const & {
1586     static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
1587                   "right polymorphic conversion");
1588     return Matcher<T>(new_from_tuple<MatcherT<T, ParamTypes...>>(Params));
1589   }
1590 
1591   template <typename T> operator Matcher<T>() && {
1592     static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
1593                   "right polymorphic conversion");
1594     return Matcher<T>(
1595         new_from_tuple<MatcherT<T, ParamTypes...>>(std::move(Params)));
1596   }
1597 
1598 private:
1599   std::tuple<ParamTypes...> Params;
1600 };
1601 
1602 /// Matches nodes of type T that have child nodes of type ChildT for
1603 /// which a specified child matcher matches.
1604 ///
1605 /// ChildT must be an AST base type.
1606 template <typename T, typename ChildT>
1607 class HasMatcher : public MatcherInterface<T> {
1608   DynTypedMatcher InnerMatcher;
1609 
1610 public:
1611   explicit HasMatcher(const Matcher<ChildT> &InnerMatcher)
1612       : InnerMatcher(InnerMatcher) {}
1613 
1614   bool matches(const T &Node, ASTMatchFinder *Finder,
1615                BoundNodesTreeBuilder *Builder) const override {
1616     return Finder->matchesChildOf(Node, this->InnerMatcher, Builder,
1617                                   ASTMatchFinder::BK_First);
1618   }
1619 };
1620 
1621 /// Matches nodes of type T that have child nodes of type ChildT for
1622 /// which a specified child matcher matches. ChildT must be an AST base
1623 /// type.
1624 /// As opposed to the HasMatcher, the ForEachMatcher will produce a match
1625 /// for each child that matches.
1626 template <typename T, typename ChildT>
1627 class ForEachMatcher : public MatcherInterface<T> {
1628   static_assert(IsBaseType<ChildT>::value,
1629                 "for each only accepts base type matcher");
1630 
1631   DynTypedMatcher InnerMatcher;
1632 
1633 public:
1634   explicit ForEachMatcher(const Matcher<ChildT> &InnerMatcher)
1635       : InnerMatcher(InnerMatcher) {}
1636 
1637   bool matches(const T &Node, ASTMatchFinder *Finder,
1638                BoundNodesTreeBuilder *Builder) const override {
1639     return Finder->matchesChildOf(
1640         Node, this->InnerMatcher, Builder,
1641         ASTMatchFinder::BK_All);
1642   }
1643 };
1644 
1645 /// @}
1646 
1647 template <typename T>
1648 inline Matcher<T> DynTypedMatcher::unconditionalConvertTo() const {
1649   return Matcher<T>(*this);
1650 }
1651 
1652 /// Matches nodes of type T that have at least one descendant node of
1653 /// type DescendantT for which the given inner matcher matches.
1654 ///
1655 /// DescendantT must be an AST base type.
1656 template <typename T, typename DescendantT>
1657 class HasDescendantMatcher : public MatcherInterface<T> {
1658   static_assert(IsBaseType<DescendantT>::value,
1659                 "has descendant only accepts base type matcher");
1660 
1661   DynTypedMatcher DescendantMatcher;
1662 
1663 public:
1664   explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher)
1665       : DescendantMatcher(DescendantMatcher) {}
1666 
1667   bool matches(const T &Node, ASTMatchFinder *Finder,
1668                BoundNodesTreeBuilder *Builder) const override {
1669     return Finder->matchesDescendantOf(Node, this->DescendantMatcher, Builder,
1670                                        ASTMatchFinder::BK_First);
1671   }
1672 };
1673 
1674 /// Matches nodes of type \c T that have a parent node of type \c ParentT
1675 /// for which the given inner matcher matches.
1676 ///
1677 /// \c ParentT must be an AST base type.
1678 template <typename T, typename ParentT>
1679 class HasParentMatcher : public MatcherInterface<T> {
1680   static_assert(IsBaseType<ParentT>::value,
1681                 "has parent only accepts base type matcher");
1682 
1683   DynTypedMatcher ParentMatcher;
1684 
1685 public:
1686   explicit HasParentMatcher(const Matcher<ParentT> &ParentMatcher)
1687       : ParentMatcher(ParentMatcher) {}
1688 
1689   bool matches(const T &Node, ASTMatchFinder *Finder,
1690                BoundNodesTreeBuilder *Builder) const override {
1691     return Finder->matchesAncestorOf(Node, this->ParentMatcher, Builder,
1692                                      ASTMatchFinder::AMM_ParentOnly);
1693   }
1694 };
1695 
1696 /// Matches nodes of type \c T that have at least one ancestor node of
1697 /// type \c AncestorT for which the given inner matcher matches.
1698 ///
1699 /// \c AncestorT must be an AST base type.
1700 template <typename T, typename AncestorT>
1701 class HasAncestorMatcher : public MatcherInterface<T> {
1702   static_assert(IsBaseType<AncestorT>::value,
1703                 "has ancestor only accepts base type matcher");
1704 
1705   DynTypedMatcher AncestorMatcher;
1706 
1707 public:
1708   explicit HasAncestorMatcher(const Matcher<AncestorT> &AncestorMatcher)
1709       : AncestorMatcher(AncestorMatcher) {}
1710 
1711   bool matches(const T &Node, ASTMatchFinder *Finder,
1712                BoundNodesTreeBuilder *Builder) const override {
1713     return Finder->matchesAncestorOf(Node, this->AncestorMatcher, Builder,
1714                                      ASTMatchFinder::AMM_All);
1715   }
1716 };
1717 
1718 /// Matches nodes of type T that have at least one descendant node of
1719 /// type DescendantT for which the given inner matcher matches.
1720 ///
1721 /// DescendantT must be an AST base type.
1722 /// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match
1723 /// for each descendant node that matches instead of only for the first.
1724 template <typename T, typename DescendantT>
1725 class ForEachDescendantMatcher : public MatcherInterface<T> {
1726   static_assert(IsBaseType<DescendantT>::value,
1727                 "for each descendant only accepts base type matcher");
1728 
1729   DynTypedMatcher DescendantMatcher;
1730 
1731 public:
1732   explicit ForEachDescendantMatcher(
1733       const Matcher<DescendantT> &DescendantMatcher)
1734       : DescendantMatcher(DescendantMatcher) {}
1735 
1736   bool matches(const T &Node, ASTMatchFinder *Finder,
1737                BoundNodesTreeBuilder *Builder) const override {
1738     return Finder->matchesDescendantOf(Node, this->DescendantMatcher, Builder,
1739                                        ASTMatchFinder::BK_All);
1740   }
1741 };
1742 
1743 /// Matches on nodes that have a getValue() method if getValue() equals
1744 /// the value the ValueEqualsMatcher was constructed with.
1745 template <typename T, typename ValueT>
1746 class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> {
1747   static_assert(std::is_base_of<CharacterLiteral, T>::value ||
1748                 std::is_base_of<CXXBoolLiteralExpr, T>::value ||
1749                 std::is_base_of<FloatingLiteral, T>::value ||
1750                 std::is_base_of<IntegerLiteral, T>::value,
1751                 "the node must have a getValue method");
1752 
1753 public:
1754   explicit ValueEqualsMatcher(const ValueT &ExpectedValue)
1755       : ExpectedValue(ExpectedValue) {}
1756 
1757   bool matchesNode(const T &Node) const override {
1758     return Node.getValue() == ExpectedValue;
1759   }
1760 
1761 private:
1762   ValueT ExpectedValue;
1763 };
1764 
1765 /// Template specializations to easily write matchers for floating point
1766 /// literals.
1767 template <>
1768 inline bool ValueEqualsMatcher<FloatingLiteral, double>::matchesNode(
1769     const FloatingLiteral &Node) const {
1770   if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle())
1771     return Node.getValue().convertToFloat() == ExpectedValue;
1772   if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble())
1773     return Node.getValue().convertToDouble() == ExpectedValue;
1774   return false;
1775 }
1776 template <>
1777 inline bool ValueEqualsMatcher<FloatingLiteral, float>::matchesNode(
1778     const FloatingLiteral &Node) const {
1779   if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle())
1780     return Node.getValue().convertToFloat() == ExpectedValue;
1781   if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble())
1782     return Node.getValue().convertToDouble() == ExpectedValue;
1783   return false;
1784 }
1785 template <>
1786 inline bool ValueEqualsMatcher<FloatingLiteral, llvm::APFloat>::matchesNode(
1787     const FloatingLiteral &Node) const {
1788   return ExpectedValue.compare(Node.getValue()) == llvm::APFloat::cmpEqual;
1789 }
1790 
1791 /// Matches nodes of type \c TLoc for which the inner
1792 /// \c Matcher<T> matches.
1793 template <typename TLoc, typename T>
1794 class LocMatcher : public MatcherInterface<TLoc> {
1795   DynTypedMatcher InnerMatcher;
1796 
1797 public:
1798   explicit LocMatcher(const Matcher<T> &InnerMatcher)
1799       : InnerMatcher(InnerMatcher) {}
1800 
1801   bool matches(const TLoc &Node, ASTMatchFinder *Finder,
1802                BoundNodesTreeBuilder *Builder) const override {
1803     if (!Node)
1804       return false;
1805     return this->InnerMatcher.matches(extract(Node), Finder, Builder);
1806   }
1807 
1808 private:
1809   static DynTypedNode extract(const NestedNameSpecifierLoc &Loc) {
1810     return DynTypedNode::create(*Loc.getNestedNameSpecifier());
1811   }
1812 };
1813 
1814 /// Matches \c TypeLocs based on an inner matcher matching a certain
1815 /// \c QualType.
1816 ///
1817 /// Used to implement the \c loc() matcher.
1818 class TypeLocTypeMatcher : public MatcherInterface<TypeLoc> {
1819   DynTypedMatcher InnerMatcher;
1820 
1821 public:
1822   explicit TypeLocTypeMatcher(const Matcher<QualType> &InnerMatcher)
1823       : InnerMatcher(InnerMatcher) {}
1824 
1825   bool matches(const TypeLoc &Node, ASTMatchFinder *Finder,
1826                BoundNodesTreeBuilder *Builder) const override {
1827     if (!Node)
1828       return false;
1829     return this->InnerMatcher.matches(DynTypedNode::create(Node.getType()),
1830                                       Finder, Builder);
1831   }
1832 };
1833 
1834 /// Matches nodes of type \c T for which the inner matcher matches on a
1835 /// another node of type \c T that can be reached using a given traverse
1836 /// function.
1837 template <typename T> class TypeTraverseMatcher : public MatcherInterface<T> {
1838   DynTypedMatcher InnerMatcher;
1839 
1840 public:
1841   explicit TypeTraverseMatcher(const Matcher<QualType> &InnerMatcher,
1842                                QualType (T::*TraverseFunction)() const)
1843       : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {}
1844 
1845   bool matches(const T &Node, ASTMatchFinder *Finder,
1846                BoundNodesTreeBuilder *Builder) const override {
1847     QualType NextNode = (Node.*TraverseFunction)();
1848     if (NextNode.isNull())
1849       return false;
1850     return this->InnerMatcher.matches(DynTypedNode::create(NextNode), Finder,
1851                                       Builder);
1852   }
1853 
1854 private:
1855   QualType (T::*TraverseFunction)() const;
1856 };
1857 
1858 /// Matches nodes of type \c T in a ..Loc hierarchy, for which the inner
1859 /// matcher matches on a another node of type \c T that can be reached using a
1860 /// given traverse function.
1861 template <typename T>
1862 class TypeLocTraverseMatcher : public MatcherInterface<T> {
1863   DynTypedMatcher InnerMatcher;
1864 
1865 public:
1866   explicit TypeLocTraverseMatcher(const Matcher<TypeLoc> &InnerMatcher,
1867                                   TypeLoc (T::*TraverseFunction)() const)
1868       : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {}
1869 
1870   bool matches(const T &Node, ASTMatchFinder *Finder,
1871                BoundNodesTreeBuilder *Builder) const override {
1872     TypeLoc NextNode = (Node.*TraverseFunction)();
1873     if (!NextNode)
1874       return false;
1875     return this->InnerMatcher.matches(DynTypedNode::create(NextNode), Finder,
1876                                       Builder);
1877   }
1878 
1879 private:
1880   TypeLoc (T::*TraverseFunction)() const;
1881 };
1882 
1883 /// Converts a \c Matcher<InnerT> to a \c Matcher<OuterT>, where
1884 /// \c OuterT is any type that is supported by \c Getter.
1885 ///
1886 /// \code Getter<OuterT>::value() \endcode returns a
1887 /// \code InnerTBase (OuterT::*)() \endcode, which is used to adapt a \c OuterT
1888 /// object into a \c InnerT
1889 template <typename InnerTBase,
1890           template <typename OuterT> class Getter,
1891           template <typename OuterT> class MatcherImpl,
1892           typename ReturnTypesF>
1893 class TypeTraversePolymorphicMatcher {
1894 private:
1895   using Self = TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl,
1896                                               ReturnTypesF>;
1897 
1898   static Self create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers);
1899 
1900 public:
1901   using ReturnTypes = typename ExtractFunctionArgMeta<ReturnTypesF>::type;
1902 
1903   explicit TypeTraversePolymorphicMatcher(
1904       ArrayRef<const Matcher<InnerTBase> *> InnerMatchers)
1905       : InnerMatcher(makeAllOfComposite(InnerMatchers)) {}
1906 
1907   template <typename OuterT> operator Matcher<OuterT>() const {
1908     return Matcher<OuterT>(
1909         new MatcherImpl<OuterT>(InnerMatcher, Getter<OuterT>::value()));
1910   }
1911 
1912   struct Func
1913       : public VariadicFunction<Self, Matcher<InnerTBase>, &Self::create> {
1914     Func() {}
1915   };
1916 
1917 private:
1918   Matcher<InnerTBase> InnerMatcher;
1919 };
1920 
1921 /// A simple memoizer of T(*)() functions.
1922 ///
1923 /// It will call the passed 'Func' template parameter at most once.
1924 /// Used to support AST_MATCHER_FUNCTION() macro.
1925 template <typename Matcher, Matcher (*Func)()> class MemoizedMatcher {
1926   struct Wrapper {
1927     Wrapper() : M(Func()) {}
1928 
1929     Matcher M;
1930   };
1931 
1932 public:
1933   static const Matcher &getInstance() {
1934     static llvm::ManagedStatic<Wrapper> Instance;
1935     return Instance->M;
1936   }
1937 };
1938 
1939 // Define the create() method out of line to silence a GCC warning about
1940 // the struct "Func" having greater visibility than its base, which comes from
1941 // using the flag -fvisibility-inlines-hidden.
1942 template <typename InnerTBase, template <typename OuterT> class Getter,
1943           template <typename OuterT> class MatcherImpl, typename ReturnTypesF>
1944 TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl, ReturnTypesF>
1945 TypeTraversePolymorphicMatcher<
1946     InnerTBase, Getter, MatcherImpl,
1947     ReturnTypesF>::create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers) {
1948   return Self(InnerMatchers);
1949 }
1950 
1951 // FIXME: unify ClassTemplateSpecializationDecl and TemplateSpecializationType's
1952 // APIs for accessing the template argument list.
1953 inline ArrayRef<TemplateArgument>
1954 getTemplateSpecializationArgs(const ClassTemplateSpecializationDecl &D) {
1955   return D.getTemplateArgs().asArray();
1956 }
1957 
1958 inline ArrayRef<TemplateArgument>
1959 getTemplateSpecializationArgs(const TemplateSpecializationType &T) {
1960   return llvm::makeArrayRef(T.getArgs(), T.getNumArgs());
1961 }
1962 
1963 inline ArrayRef<TemplateArgument>
1964 getTemplateSpecializationArgs(const FunctionDecl &FD) {
1965   if (const auto* TemplateArgs = FD.getTemplateSpecializationArgs())
1966     return TemplateArgs->asArray();
1967   return ArrayRef<TemplateArgument>();
1968 }
1969 
1970 struct NotEqualsBoundNodePredicate {
1971   bool operator()(const internal::BoundNodesMap &Nodes) const {
1972     return Nodes.getNode(ID) != Node;
1973   }
1974 
1975   std::string ID;
1976   DynTypedNode Node;
1977 };
1978 
1979 template <typename Ty, typename Enable = void> struct GetBodyMatcher {
1980   static const Stmt *get(const Ty &Node) { return Node.getBody(); }
1981 };
1982 
1983 template <typename Ty>
1984 struct GetBodyMatcher<Ty, typename std::enable_if<
1985                               std::is_base_of<FunctionDecl, Ty>::value>::type> {
1986   static const Stmt *get(const Ty &Node) {
1987     return Node.doesThisDeclarationHaveABody() ? Node.getBody() : nullptr;
1988   }
1989 };
1990 
1991 template <typename NodeType>
1992 inline Optional<BinaryOperatorKind>
1993 equivalentBinaryOperator(const NodeType &Node) {
1994   return Node.getOpcode();
1995 }
1996 
1997 template <>
1998 inline Optional<BinaryOperatorKind>
1999 equivalentBinaryOperator<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) {
2000   if (Node.getNumArgs() != 2)
2001     return None;
2002   switch (Node.getOperator()) {
2003   default:
2004     return None;
2005   case OO_ArrowStar:
2006     return BO_PtrMemI;
2007   case OO_Star:
2008     return BO_Mul;
2009   case OO_Slash:
2010     return BO_Div;
2011   case OO_Percent:
2012     return BO_Rem;
2013   case OO_Plus:
2014     return BO_Add;
2015   case OO_Minus:
2016     return BO_Sub;
2017   case OO_LessLess:
2018     return BO_Shl;
2019   case OO_GreaterGreater:
2020     return BO_Shr;
2021   case OO_Spaceship:
2022     return BO_Cmp;
2023   case OO_Less:
2024     return BO_LT;
2025   case OO_Greater:
2026     return BO_GT;
2027   case OO_LessEqual:
2028     return BO_LE;
2029   case OO_GreaterEqual:
2030     return BO_GE;
2031   case OO_EqualEqual:
2032     return BO_EQ;
2033   case OO_ExclaimEqual:
2034     return BO_NE;
2035   case OO_Amp:
2036     return BO_And;
2037   case OO_Caret:
2038     return BO_Xor;
2039   case OO_Pipe:
2040     return BO_Or;
2041   case OO_AmpAmp:
2042     return BO_LAnd;
2043   case OO_PipePipe:
2044     return BO_LOr;
2045   case OO_Equal:
2046     return BO_Assign;
2047   case OO_StarEqual:
2048     return BO_MulAssign;
2049   case OO_SlashEqual:
2050     return BO_DivAssign;
2051   case OO_PercentEqual:
2052     return BO_RemAssign;
2053   case OO_PlusEqual:
2054     return BO_AddAssign;
2055   case OO_MinusEqual:
2056     return BO_SubAssign;
2057   case OO_LessLessEqual:
2058     return BO_ShlAssign;
2059   case OO_GreaterGreaterEqual:
2060     return BO_ShrAssign;
2061   case OO_AmpEqual:
2062     return BO_AndAssign;
2063   case OO_CaretEqual:
2064     return BO_XorAssign;
2065   case OO_PipeEqual:
2066     return BO_OrAssign;
2067   case OO_Comma:
2068     return BO_Comma;
2069   }
2070 }
2071 
2072 template <typename NodeType>
2073 inline Optional<UnaryOperatorKind>
2074 equivalentUnaryOperator(const NodeType &Node) {
2075   return Node.getOpcode();
2076 }
2077 
2078 template <>
2079 inline Optional<UnaryOperatorKind>
2080 equivalentUnaryOperator<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) {
2081   if (Node.getNumArgs() != 1 && Node.getOperator() != OO_PlusPlus &&
2082       Node.getOperator() != OO_MinusMinus)
2083     return None;
2084   switch (Node.getOperator()) {
2085   default:
2086     return None;
2087   case OO_Plus:
2088     return UO_Plus;
2089   case OO_Minus:
2090     return UO_Minus;
2091   case OO_Amp:
2092     return UO_AddrOf;
2093   case OO_Star:
2094     return UO_Deref;
2095   case OO_Tilde:
2096     return UO_Not;
2097   case OO_Exclaim:
2098     return UO_LNot;
2099   case OO_PlusPlus: {
2100     const auto *FD = Node.getDirectCallee();
2101     if (!FD)
2102       return None;
2103     return FD->getNumParams() > 0 ? UO_PostInc : UO_PreInc;
2104   }
2105   case OO_MinusMinus: {
2106     const auto *FD = Node.getDirectCallee();
2107     if (!FD)
2108       return None;
2109     return FD->getNumParams() > 0 ? UO_PostDec : UO_PreDec;
2110   }
2111   case OO_Coawait:
2112     return UO_Coawait;
2113   }
2114 }
2115 
2116 template <typename NodeType> inline const Expr *getLHS(const NodeType &Node) {
2117   return Node.getLHS();
2118 }
2119 template <>
2120 inline const Expr *
2121 getLHS<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) {
2122   if (!internal::equivalentBinaryOperator(Node))
2123     return nullptr;
2124   return Node.getArg(0);
2125 }
2126 template <typename NodeType> inline const Expr *getRHS(const NodeType &Node) {
2127   return Node.getRHS();
2128 }
2129 template <>
2130 inline const Expr *
2131 getRHS<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) {
2132   if (!internal::equivalentBinaryOperator(Node))
2133     return nullptr;
2134   return Node.getArg(1);
2135 }
2136 template <typename NodeType>
2137 inline const Expr *getSubExpr(const NodeType &Node) {
2138   return Node.getSubExpr();
2139 }
2140 template <>
2141 inline const Expr *
2142 getSubExpr<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) {
2143   if (!internal::equivalentUnaryOperator(Node))
2144     return nullptr;
2145   return Node.getArg(0);
2146 }
2147 
2148 template <typename Ty>
2149 struct HasSizeMatcher {
2150   static bool hasSize(const Ty &Node, unsigned int N) {
2151     return Node.getSize() == N;
2152   }
2153 };
2154 
2155 template <>
2156 inline bool HasSizeMatcher<StringLiteral>::hasSize(
2157     const StringLiteral &Node, unsigned int N) {
2158   return Node.getLength() == N;
2159 }
2160 
2161 template <typename Ty>
2162 struct GetSourceExpressionMatcher {
2163   static const Expr *get(const Ty &Node) {
2164     return Node.getSubExpr();
2165   }
2166 };
2167 
2168 template <>
2169 inline const Expr *GetSourceExpressionMatcher<OpaqueValueExpr>::get(
2170     const OpaqueValueExpr &Node) {
2171   return Node.getSourceExpr();
2172 }
2173 
2174 template <typename Ty>
2175 struct CompoundStmtMatcher {
2176   static const CompoundStmt *get(const Ty &Node) {
2177     return &Node;
2178   }
2179 };
2180 
2181 template <>
2182 inline const CompoundStmt *
2183 CompoundStmtMatcher<StmtExpr>::get(const StmtExpr &Node) {
2184   return Node.getSubStmt();
2185 }
2186 
2187 /// If \p Loc is (transitively) expanded from macro \p MacroName, returns the
2188 /// location (in the chain of expansions) at which \p MacroName was
2189 /// expanded. Since the macro may have been expanded inside a series of
2190 /// expansions, that location may itself be a MacroID.
2191 llvm::Optional<SourceLocation>
2192 getExpansionLocOfMacro(StringRef MacroName, SourceLocation Loc,
2193                        const ASTContext &Context);
2194 
2195 inline Optional<StringRef> getOpName(const UnaryOperator &Node) {
2196   return Node.getOpcodeStr(Node.getOpcode());
2197 }
2198 inline Optional<StringRef> getOpName(const BinaryOperator &Node) {
2199   return Node.getOpcodeStr();
2200 }
2201 inline StringRef getOpName(const CXXRewrittenBinaryOperator &Node) {
2202   return Node.getOpcodeStr();
2203 }
2204 inline Optional<StringRef> getOpName(const CXXOperatorCallExpr &Node) {
2205   auto optBinaryOpcode = equivalentBinaryOperator(Node);
2206   if (!optBinaryOpcode) {
2207     auto optUnaryOpcode = equivalentUnaryOperator(Node);
2208     if (!optUnaryOpcode)
2209       return None;
2210     return UnaryOperator::getOpcodeStr(*optUnaryOpcode);
2211   }
2212   return BinaryOperator::getOpcodeStr(*optBinaryOpcode);
2213 }
2214 
2215 /// Matches overloaded operators with a specific name.
2216 ///
2217 /// The type argument ArgT is not used by this matcher but is used by
2218 /// PolymorphicMatcher and should be std::vector<std::string>>.
2219 template <typename T, typename ArgT = std::vector<std::string>>
2220 class HasAnyOperatorNameMatcher : public SingleNodeMatcherInterface<T> {
2221   static_assert(std::is_same<T, BinaryOperator>::value ||
2222                     std::is_same<T, CXXOperatorCallExpr>::value ||
2223                     std::is_same<T, CXXRewrittenBinaryOperator>::value ||
2224                     std::is_same<T, UnaryOperator>::value,
2225                 "Matcher only supports `BinaryOperator`, `UnaryOperator`, "
2226                 "`CXXOperatorCallExpr` and `CXXRewrittenBinaryOperator`");
2227   static_assert(std::is_same<ArgT, std::vector<std::string>>::value,
2228                 "Matcher ArgT must be std::vector<std::string>");
2229 
2230 public:
2231   explicit HasAnyOperatorNameMatcher(std::vector<std::string> Names)
2232       : SingleNodeMatcherInterface<T>(), Names(std::move(Names)) {}
2233 
2234   bool matchesNode(const T &Node) const override {
2235     Optional<StringRef> OptOpName = getOpName(Node);
2236     return OptOpName && llvm::is_contained(Names, *OptOpName);
2237   }
2238 
2239 private:
2240   static Optional<StringRef> getOpName(const UnaryOperator &Node) {
2241     return Node.getOpcodeStr(Node.getOpcode());
2242   }
2243   static Optional<StringRef> getOpName(const BinaryOperator &Node) {
2244     return Node.getOpcodeStr();
2245   }
2246   static StringRef getOpName(const CXXRewrittenBinaryOperator &Node) {
2247     return Node.getOpcodeStr();
2248   }
2249   static Optional<StringRef> getOpName(const CXXOperatorCallExpr &Node) {
2250     auto optBinaryOpcode = equivalentBinaryOperator(Node);
2251     if (!optBinaryOpcode) {
2252       auto optUnaryOpcode = equivalentUnaryOperator(Node);
2253       if (!optUnaryOpcode)
2254         return None;
2255       return UnaryOperator::getOpcodeStr(*optUnaryOpcode);
2256     }
2257     return BinaryOperator::getOpcodeStr(*optBinaryOpcode);
2258   }
2259 
2260   std::vector<std::string> Names;
2261 };
2262 
2263 using HasOpNameMatcher =
2264     PolymorphicMatcher<HasAnyOperatorNameMatcher,
2265                        void(
2266                            TypeList<BinaryOperator, CXXOperatorCallExpr,
2267                                     CXXRewrittenBinaryOperator, UnaryOperator>),
2268                        std::vector<std::string>>;
2269 
2270 HasOpNameMatcher hasAnyOperatorNameFunc(ArrayRef<const StringRef *> NameRefs);
2271 
2272 using HasOverloadOpNameMatcher =
2273     PolymorphicMatcher<HasOverloadedOperatorNameMatcher,
2274                        void(TypeList<CXXOperatorCallExpr, FunctionDecl>),
2275                        std::vector<std::string>>;
2276 
2277 HasOverloadOpNameMatcher
2278 hasAnyOverloadedOperatorNameFunc(ArrayRef<const StringRef *> NameRefs);
2279 
2280 /// Returns true if \p Node has a base specifier matching \p BaseSpec.
2281 ///
2282 /// A class is not considered to be derived from itself.
2283 bool matchesAnyBase(const CXXRecordDecl &Node,
2284                     const Matcher<CXXBaseSpecifier> &BaseSpecMatcher,
2285                     ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder);
2286 
2287 std::shared_ptr<llvm::Regex> createAndVerifyRegex(StringRef Regex,
2288                                                   llvm::Regex::RegexFlags Flags,
2289                                                   StringRef MatcherID);
2290 
2291 inline bool
2292 MatchTemplateArgLocAt(const DeclRefExpr &Node, unsigned int Index,
2293                       internal::Matcher<TemplateArgumentLoc> InnerMatcher,
2294                       internal::ASTMatchFinder *Finder,
2295                       internal::BoundNodesTreeBuilder *Builder) {
2296   llvm::ArrayRef<TemplateArgumentLoc> ArgLocs = Node.template_arguments();
2297   return Index < ArgLocs.size() &&
2298          InnerMatcher.matches(ArgLocs[Index], Finder, Builder);
2299 }
2300 
2301 inline bool
2302 MatchTemplateArgLocAt(const TemplateSpecializationTypeLoc &Node,
2303                       unsigned int Index,
2304                       internal::Matcher<TemplateArgumentLoc> InnerMatcher,
2305                       internal::ASTMatchFinder *Finder,
2306                       internal::BoundNodesTreeBuilder *Builder) {
2307   return !Node.isNull() && Index < Node.getNumArgs() &&
2308          InnerMatcher.matches(Node.getArgLoc(Index), Finder, Builder);
2309 }
2310 
2311 } // namespace internal
2312 
2313 } // namespace ast_matchers
2314 
2315 } // namespace clang
2316 
2317 #endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERSINTERNAL_H
2318