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