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