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