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