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