ASTMatchersInternal.h revision d36e46350b50907425bba0db1b3ddfb46cc1637f
1//===--- ASTMatchersInternal.h - Structural query framework -----*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  Implements the base layer of the matcher framework.
11//
12//  Matchers are methods that return a Matcher<T> which provides a method
13//  Matches(...) which is a predicate on an AST node. The Matches method's
14//  parameters define the context of the match, which allows matchers to recurse
15//  or store the current node as bound to a specific string, so that it can be
16//  retrieved later.
17//
18//  In general, matchers have two parts:
19//  1. A function Matcher<T> MatcherName(<arguments>) which returns a Matcher<T>
20//     based on the arguments and optionally on template type deduction based
21//     on the arguments. Matcher<T>s form an implicit reverse hierarchy
22//     to clang's AST class hierarchy, meaning that you can use a Matcher<Base>
23//     everywhere a Matcher<Derived> is required.
24//  2. An implementation of a class derived from MatcherInterface<T>.
25//
26//  The matcher functions are defined in ASTMatchers.h. To make it possible
27//  to implement both the matcher function and the implementation of the matcher
28//  interface in one place, ASTMatcherMacros.h defines macros that allow
29//  implementing a matcher in a single place.
30//
31//  This file contains the base classes needed to construct the actual matchers.
32//
33//===----------------------------------------------------------------------===//
34
35#ifndef LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H
36#define LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H
37
38#include "clang/AST/ASTTypeTraits.h"
39#include "clang/AST/DeclCXX.h"
40#include "clang/AST/Decl.h"
41#include "clang/AST/ExprCXX.h"
42#include "clang/AST/StmtCXX.h"
43#include "clang/AST/Stmt.h"
44#include "clang/AST/Type.h"
45#include "llvm/ADT/VariadicFunction.h"
46#include "llvm/Support/type_traits.h"
47#include <map>
48#include <string>
49#include <vector>
50
51namespace clang {
52namespace ast_matchers {
53
54/// FIXME: Move into the llvm support library.
55template <bool> struct CompileAssert {};
56#define TOOLING_COMPILE_ASSERT(Expr, Msg) \
57  typedef CompileAssert<(bool(Expr))> Msg[bool(Expr) ? 1 : -1]
58
59class BoundNodes;
60
61namespace internal {
62
63/// \brief Internal version of BoundNodes. Holds all the bound nodes.
64class BoundNodesMap {
65public:
66  /// \brief Adds \c Node to the map with key \c ID.
67  ///
68  /// The node's base type should be in NodeBaseType or it will be unaccessible.
69  template <typename T>
70  void addNode(StringRef ID, const T* Node) {
71    NodeMap[ID] = ast_type_traits::DynTypedNode::create(*Node);
72  }
73
74  /// \brief Returns the AST node bound to \c ID.
75  ///
76  /// Returns NULL if there was no node bound to \c ID or if there is a node but
77  /// it cannot be converted to the specified type.
78  template <typename T>
79  const T *getNodeAs(StringRef ID) const {
80    IDToNodeMap::const_iterator It = NodeMap.find(ID);
81    if (It == NodeMap.end()) {
82      return NULL;
83    }
84    return It->second.get<T>();
85  }
86
87  ast_type_traits::DynTypedNode getNode(StringRef ID) const {
88    IDToNodeMap::const_iterator It = NodeMap.find(ID);
89    if (It == NodeMap.end()) {
90      return ast_type_traits::DynTypedNode();
91    }
92    return It->second;
93  }
94
95  /// \brief Imposes an order on BoundNodesMaps.
96  bool operator<(const BoundNodesMap &Other) const {
97    return NodeMap < Other.NodeMap;
98  }
99
100private:
101  /// \brief A map from IDs to the bound nodes.
102  ///
103  /// Note that we're using std::map here, as for memoization:
104  /// - we need a comparison operator
105  /// - we need an assignment operator
106  typedef std::map<std::string, ast_type_traits::DynTypedNode> IDToNodeMap;
107
108  IDToNodeMap NodeMap;
109};
110
111/// \brief Creates BoundNodesTree objects.
112///
113/// The tree builder is used during the matching process to insert the bound
114/// nodes from the Id matcher.
115class BoundNodesTreeBuilder {
116public:
117  /// \brief A visitor interface to visit all BoundNodes results for a
118  /// BoundNodesTree.
119  class Visitor {
120  public:
121    virtual ~Visitor() {}
122
123    /// \brief Called multiple times during a single call to VisitMatches(...).
124    ///
125    /// 'BoundNodesView' contains the bound nodes for a single match.
126    virtual void visitMatch(const BoundNodes& BoundNodesView) = 0;
127  };
128
129  /// \brief Add a binding from an id to a node.
130  template <typename T> void setBinding(const std::string &Id, const T *Node) {
131    if (Bindings.empty())
132      Bindings.push_back(BoundNodesMap());
133    for (unsigned i = 0, e = Bindings.size(); i != e; ++i)
134      Bindings[i].addNode(Id, Node);
135  }
136
137  /// \brief Adds a branch in the tree.
138  void addMatch(const BoundNodesTreeBuilder &Bindings);
139
140  /// \brief Visits all matches that this BoundNodesTree represents.
141  ///
142  /// The ownership of 'ResultVisitor' remains at the caller.
143  void visitMatches(Visitor* ResultVisitor);
144
145  template <typename ExcludePredicate>
146  bool removeBindings(const ExcludePredicate &Predicate) {
147    Bindings.erase(std::remove_if(Bindings.begin(), Bindings.end(), Predicate),
148                   Bindings.end());
149    return !Bindings.empty();
150  }
151
152  /// \brief Imposes an order on BoundNodesTreeBuilders.
153  bool operator<(const BoundNodesTreeBuilder &Other) const {
154    return Bindings < Other.Bindings;
155  }
156
157private:
158  SmallVector<BoundNodesMap, 16> Bindings;
159};
160
161class ASTMatchFinder;
162
163/// \brief Generic interface for matchers on an AST node of type T.
164///
165/// Implement this if your matcher may need to inspect the children or
166/// descendants of the node or bind matched nodes to names. If you are
167/// writing a simple matcher that only inspects properties of the
168/// current node and doesn't care about its children or descendants,
169/// implement SingleNodeMatcherInterface instead.
170template <typename T>
171class MatcherInterface : public RefCountedBaseVPTR {
172public:
173  virtual ~MatcherInterface() {}
174
175  /// \brief Returns true if 'Node' can be matched.
176  ///
177  /// May bind 'Node' to an ID via 'Builder', or recurse into
178  /// the AST via 'Finder'.
179  virtual bool matches(const T &Node,
180                       ASTMatchFinder *Finder,
181                       BoundNodesTreeBuilder *Builder) const = 0;
182};
183
184/// \brief Interface for matchers that only evaluate properties on a single
185/// node.
186template <typename T>
187class SingleNodeMatcherInterface : public MatcherInterface<T> {
188public:
189  /// \brief Returns true if the matcher matches the provided node.
190  ///
191  /// A subclass must implement this instead of Matches().
192  virtual bool matchesNode(const T &Node) const = 0;
193
194private:
195  /// Implements MatcherInterface::Matches.
196  virtual bool matches(const T &Node,
197                       ASTMatchFinder * /* Finder */,
198                       BoundNodesTreeBuilder * /*  Builder */) const {
199    return matchesNode(Node);
200  }
201};
202
203/// \brief Base class for all matchers that works on a \c DynTypedNode.
204///
205/// Matcher implementations will check whether the \c DynTypedNode is
206/// convertible into the respecitve types and then do the actual match
207/// on the actual node, or return false if it is not convertible.
208class DynTypedMatcher {
209public:
210  virtual ~DynTypedMatcher();
211
212  /// \brief Returns true if the matcher matches the given \c DynNode.
213  virtual bool matches(const ast_type_traits::DynTypedNode DynNode,
214                       ASTMatchFinder *Finder,
215                       BoundNodesTreeBuilder *Builder) const = 0;
216
217  /// \brief Makes a copy of this matcher object.
218  virtual DynTypedMatcher *clone() const = 0;
219
220  /// \brief Returns a unique ID for the matcher.
221  virtual uint64_t getID() const = 0;
222
223  /// \brief Bind the specified \p ID to the matcher.
224  /// \return A new matcher with the \p ID bound to it if this matcher supports
225  ///   binding. Otherwise, returns NULL. Returns NULL by default.
226  virtual DynTypedMatcher* tryBind(StringRef ID) const;
227
228  /// \brief Returns the type this matcher works on.
229  ///
230  /// \c matches() will always return false unless the node passed is of this
231  /// or a derived type.
232  virtual ast_type_traits::ASTNodeKind getSupportedKind() const = 0;
233};
234
235/// \brief Wrapper of a MatcherInterface<T> *that allows copying.
236///
237/// A Matcher<Base> can be used anywhere a Matcher<Derived> is
238/// required. This establishes an is-a relationship which is reverse
239/// to the AST hierarchy. In other words, Matcher<T> is contravariant
240/// with respect to T. The relationship is built via a type conversion
241/// operator rather than a type hierarchy to be able to templatize the
242/// type hierarchy instead of spelling it out.
243template <typename T>
244class Matcher : public DynTypedMatcher {
245public:
246  /// \brief Takes ownership of the provided implementation pointer.
247  explicit Matcher(MatcherInterface<T> *Implementation)
248      : Implementation(Implementation) {}
249
250  /// \brief Implicitly converts \c Other to a Matcher<T>.
251  ///
252  /// Requires \c T to be derived from \c From.
253  template <typename From>
254  Matcher(const Matcher<From> &Other,
255          typename llvm::enable_if_c<
256            llvm::is_base_of<From, T>::value &&
257            !llvm::is_same<From, T>::value >::type* = 0)
258      : Implementation(new ImplicitCastMatcher<From>(Other)) {}
259
260  /// \brief Implicitly converts \c Matcher<Type> to \c Matcher<QualType>.
261  ///
262  /// The resulting matcher is not strict, i.e. ignores qualifiers.
263  template <typename TypeT>
264  Matcher(const Matcher<TypeT> &Other,
265          typename llvm::enable_if_c<
266            llvm::is_same<T, QualType>::value &&
267            llvm::is_same<TypeT, Type>::value >::type* = 0)
268      : Implementation(new TypeToQualType<TypeT>(Other)) {}
269
270  /// \brief Returns \c true if the passed DynTypedMatcher can be converted
271  ///   to a \c Matcher<T>.
272  ///
273  /// This method verifies that the underlying matcher in \c Other can process
274  /// nodes of types T.
275  static bool canConstructFrom(const DynTypedMatcher &Other) {
276    return Other.getSupportedKind()
277        .isBaseOf(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
278  }
279
280  /// \brief Construct a Matcher<T> interface around the dynamic matcher
281  ///   \c Other.
282  ///
283  /// This method asserts that canConstructFrom(Other) is \c true. Callers
284  /// should call canConstructFrom(Other) first to make sure that Other is
285  /// compatible with T.
286  static Matcher<T> constructFrom(const DynTypedMatcher &Other) {
287    assert(canConstructFrom(Other));
288    return Matcher<T>(new WrappedMatcher(Other));
289  }
290
291  /// \brief Forwards the call to the underlying MatcherInterface<T> pointer.
292  bool matches(const T &Node,
293               ASTMatchFinder *Finder,
294               BoundNodesTreeBuilder *Builder) const {
295    if (Implementation->matches(Node, Finder, Builder))
296      return true;
297    // Delete all bindings when a matcher does not match.
298    // This prevents unexpected exposure of bound nodes in unmatches
299    // branches of the match tree.
300    *Builder = BoundNodesTreeBuilder();
301    return false;
302  }
303
304  /// \brief Returns an ID that uniquely identifies the matcher.
305  uint64_t getID() const {
306    /// FIXME: Document the requirements this imposes on matcher
307    /// implementations (no new() implementation_ during a Matches()).
308    return reinterpret_cast<uint64_t>(Implementation.getPtr());
309  }
310
311  /// \brief Returns the type this matcher works on.
312  ast_type_traits::ASTNodeKind getSupportedKind() const {
313    return ast_type_traits::ASTNodeKind::getFromNodeKind<T>();
314  }
315
316  /// \brief Returns whether the matcher matches on the given \c DynNode.
317  virtual bool matches(const ast_type_traits::DynTypedNode DynNode,
318                       ASTMatchFinder *Finder,
319                       BoundNodesTreeBuilder *Builder) const {
320    const T *Node = DynNode.get<T>();
321    if (!Node) return false;
322    return matches(*Node, Finder, Builder);
323  }
324
325  /// \brief Makes a copy of this matcher object.
326  virtual Matcher<T> *clone() const { return new Matcher<T>(*this); }
327
328  /// \brief Allows the conversion of a \c Matcher<Type> to a \c
329  /// Matcher<QualType>.
330  ///
331  /// Depending on the constructor argument, the matcher is either strict, i.e.
332  /// does only matches in the absence of qualifiers, or not, i.e. simply
333  /// ignores any qualifiers.
334  template <typename TypeT>
335  class TypeToQualType : public MatcherInterface<QualType> {
336   public:
337    TypeToQualType(const Matcher<TypeT> &InnerMatcher)
338        : InnerMatcher(InnerMatcher) {}
339
340    virtual bool matches(const QualType &Node,
341                         ASTMatchFinder *Finder,
342                         BoundNodesTreeBuilder *Builder) const {
343      if (Node.isNull())
344        return false;
345      return InnerMatcher.matches(*Node, Finder, Builder);
346    }
347   private:
348    const Matcher<TypeT> InnerMatcher;
349  };
350
351private:
352  /// \brief Allows conversion from Matcher<Base> to Matcher<T> if T
353  /// is derived from Base.
354  template <typename Base>
355  class ImplicitCastMatcher : public MatcherInterface<T> {
356  public:
357    explicit ImplicitCastMatcher(const Matcher<Base> &From)
358        : From(From) {}
359
360    virtual bool matches(const T &Node,
361                         ASTMatchFinder *Finder,
362                         BoundNodesTreeBuilder *Builder) const {
363      return From.matches(Node, Finder, Builder);
364    }
365
366  private:
367    const Matcher<Base> From;
368  };
369
370  /// \brief Simple MatcherInterface<T> wrapper around a DynTypedMatcher.
371  class WrappedMatcher : public MatcherInterface<T> {
372  public:
373    explicit WrappedMatcher(const DynTypedMatcher &Matcher)
374        : Inner(Matcher.clone()) {}
375    virtual ~WrappedMatcher() {}
376
377    bool matches(const T &Node, ASTMatchFinder *Finder,
378                 BoundNodesTreeBuilder *Builder) const {
379      return Inner->matches(ast_type_traits::DynTypedNode::create(Node), Finder,
380                            Builder);
381    }
382
383  private:
384    const OwningPtr<DynTypedMatcher> Inner;
385  };
386
387  IntrusiveRefCntPtr< MatcherInterface<T> > Implementation;
388};  // class Matcher
389
390/// \brief A convenient helper for creating a Matcher<T> without specifying
391/// the template type argument.
392template <typename T>
393inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) {
394  return Matcher<T>(Implementation);
395}
396
397/// \brief Specialization of the conversion functions for QualType.
398///
399/// These specializations provide the Matcher<Type>->Matcher<QualType>
400/// conversion that the static API does.
401template <>
402inline bool
403Matcher<QualType>::canConstructFrom(const DynTypedMatcher &Other) {
404  ast_type_traits::ASTNodeKind SourceKind = Other.getSupportedKind();
405  // We support implicit conversion from Matcher<Type> to Matcher<QualType>
406  return SourceKind.isSame(
407             ast_type_traits::ASTNodeKind::getFromNodeKind<Type>()) ||
408         SourceKind.isSame(
409             ast_type_traits::ASTNodeKind::getFromNodeKind<QualType>());
410}
411
412template <>
413inline Matcher<QualType>
414Matcher<QualType>::constructFrom(const DynTypedMatcher &Other) {
415  assert(canConstructFrom(Other));
416  ast_type_traits::ASTNodeKind SourceKind = Other.getSupportedKind();
417  if (SourceKind.isSame(
418          ast_type_traits::ASTNodeKind::getFromNodeKind<Type>())) {
419    // We support implicit conversion from Matcher<Type> to Matcher<QualType>
420    return Matcher<Type>::constructFrom(Other);
421  }
422  return makeMatcher(new WrappedMatcher(Other));
423}
424
425/// \brief Finds the first node in a range that matches the given matcher.
426template <typename MatcherT, typename IteratorT>
427bool matchesFirstInRange(const MatcherT &Matcher, IteratorT Start,
428                         IteratorT End, ASTMatchFinder *Finder,
429                         BoundNodesTreeBuilder *Builder) {
430  for (IteratorT I = Start; I != End; ++I) {
431    BoundNodesTreeBuilder Result(*Builder);
432    if (Matcher.matches(*I, Finder, &Result)) {
433      *Builder = Result;
434      return true;
435    }
436  }
437  return false;
438}
439
440/// \brief Finds the first node in a pointer range that matches the given
441/// matcher.
442template <typename MatcherT, typename IteratorT>
443bool matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start,
444                                IteratorT End, ASTMatchFinder *Finder,
445                                BoundNodesTreeBuilder *Builder) {
446  for (IteratorT I = Start; I != End; ++I) {
447    BoundNodesTreeBuilder Result(*Builder);
448    if (Matcher.matches(**I, Finder, &Result)) {
449      *Builder = Result;
450      return true;
451    }
452  }
453  return false;
454}
455
456/// \brief Metafunction to determine if type T has a member called getDecl.
457template <typename T> struct has_getDecl {
458  struct Default { int getDecl; };
459  struct Derived : T, Default { };
460
461  template<typename C, C> struct CheckT;
462
463  // If T::getDecl exists, an ambiguity arises and CheckT will
464  // not be instantiable. This makes f(...) the only available
465  // overload.
466  template<typename C>
467  static char (&f(CheckT<int Default::*, &C::getDecl>*))[1];
468  template<typename C> static char (&f(...))[2];
469
470  static bool const value = sizeof(f<Derived>(0)) == 2;
471};
472
473/// \brief Matches overloaded operators with a specific name.
474///
475/// The type argument ArgT is not used by this matcher but is used by
476/// PolymorphicMatcherWithParam1 and should be StringRef.
477template <typename T, typename ArgT>
478class HasOverloadedOperatorNameMatcher : public SingleNodeMatcherInterface<T> {
479  TOOLING_COMPILE_ASSERT((llvm::is_same<T, CXXOperatorCallExpr>::value ||
480                          llvm::is_same<T, CXXMethodDecl>::value),
481                         unsupported_class_for_matcher);
482  TOOLING_COMPILE_ASSERT((llvm::is_same<ArgT, StringRef>::value),
483                         argument_type_must_be_StringRef);
484public:
485  explicit HasOverloadedOperatorNameMatcher(const StringRef Name)
486      : SingleNodeMatcherInterface<T>(), Name(Name) {}
487
488  virtual bool matchesNode(const T &Node) const LLVM_OVERRIDE {
489    return matchesSpecialized(Node);
490  }
491
492private:
493
494  /// \brief CXXOperatorCallExpr exist only for calls to overloaded operators
495  /// so this function returns true if the call is to an operator of the given
496  /// name.
497  bool matchesSpecialized(const CXXOperatorCallExpr &Node) const {
498    return getOperatorSpelling(Node.getOperator()) == Name;
499  }
500
501  /// \brief Returns true only if CXXMethodDecl represents an overloaded
502  /// operator and has the given operator name.
503  bool matchesSpecialized(const CXXMethodDecl &Node) const {
504    return Node.isOverloadedOperator() &&
505           getOperatorSpelling(Node.getOverloadedOperator()) == Name;
506  }
507
508  std::string Name;
509};
510
511/// \brief Matches declarations for QualType and CallExpr.
512///
513/// Type argument DeclMatcherT is required by PolymorphicMatcherWithParam1 but
514/// not actually used.
515template <typename T, typename DeclMatcherT>
516class HasDeclarationMatcher : public MatcherInterface<T> {
517  TOOLING_COMPILE_ASSERT((llvm::is_same< DeclMatcherT,
518                                         Matcher<Decl> >::value),
519                          instantiated_with_wrong_types);
520public:
521  explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher)
522      : InnerMatcher(InnerMatcher) {}
523
524  virtual bool matches(const T &Node,
525                       ASTMatchFinder *Finder,
526                       BoundNodesTreeBuilder *Builder) const {
527    return matchesSpecialized(Node, Finder, Builder);
528  }
529
530private:
531  /// \brief If getDecl exists as a member of U, returns whether the inner
532  /// matcher matches Node.getDecl().
533  template <typename U>
534  bool matchesSpecialized(
535      const U &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder,
536      typename llvm::enable_if<has_getDecl<U>, int>::type = 0) const {
537    return matchesDecl(Node.getDecl(), Finder, Builder);
538  }
539
540  /// \brief Extracts the CXXRecordDecl or EnumDecl of a QualType and returns
541  /// whether the inner matcher matches on it.
542  bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder,
543                          BoundNodesTreeBuilder *Builder) const {
544    /// FIXME: Add other ways to convert...
545    if (Node.isNull())
546      return false;
547    if (const EnumType *AsEnum = dyn_cast<EnumType>(Node.getTypePtr()))
548      return matchesDecl(AsEnum->getDecl(), Finder, Builder);
549    return matchesDecl(Node->getAsCXXRecordDecl(), Finder, Builder);
550  }
551
552  /// \brief Gets the TemplateDecl from a TemplateSpecializationType
553  /// and returns whether the inner matches on it.
554  bool matchesSpecialized(const TemplateSpecializationType &Node,
555                          ASTMatchFinder *Finder,
556                          BoundNodesTreeBuilder *Builder) const {
557    return matchesDecl(Node.getTemplateName().getAsTemplateDecl(),
558                       Finder, Builder);
559  }
560
561  /// \brief Extracts the Decl of the callee of a CallExpr and returns whether
562  /// the inner matcher matches on it.
563  bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder,
564                          BoundNodesTreeBuilder *Builder) const {
565    return matchesDecl(Node.getCalleeDecl(), Finder, Builder);
566  }
567
568  /// \brief Extracts the Decl of the constructor call and returns whether the
569  /// inner matcher matches on it.
570  bool matchesSpecialized(const CXXConstructExpr &Node,
571                          ASTMatchFinder *Finder,
572                          BoundNodesTreeBuilder *Builder) const {
573    return matchesDecl(Node.getConstructor(), Finder, Builder);
574  }
575
576  /// \brief Extracts the \c ValueDecl a \c MemberExpr refers to and returns
577  /// whether the inner matcher matches on it.
578  bool matchesSpecialized(const MemberExpr &Node,
579                          ASTMatchFinder *Finder,
580                          BoundNodesTreeBuilder *Builder) const {
581    return matchesDecl(Node.getMemberDecl(), Finder, Builder);
582  }
583
584  /// \brief Returns whether the inner matcher \c Node. Returns false if \c Node
585  /// is \c NULL.
586  bool matchesDecl(const Decl *Node,
587                   ASTMatchFinder *Finder,
588                   BoundNodesTreeBuilder *Builder) const {
589    return Node != NULL && InnerMatcher.matches(*Node, Finder, Builder);
590  }
591
592  const Matcher<Decl> InnerMatcher;
593};
594
595/// \brief IsBaseType<T>::value is true if T is a "base" type in the AST
596/// node class hierarchies.
597template <typename T>
598struct IsBaseType {
599  static const bool value =
600      (llvm::is_same<T, Decl>::value ||
601       llvm::is_same<T, Stmt>::value ||
602       llvm::is_same<T, QualType>::value ||
603       llvm::is_same<T, Type>::value ||
604       llvm::is_same<T, TypeLoc>::value ||
605       llvm::is_same<T, NestedNameSpecifier>::value ||
606       llvm::is_same<T, NestedNameSpecifierLoc>::value ||
607       llvm::is_same<T, CXXCtorInitializer>::value);
608};
609template <typename T>
610const bool IsBaseType<T>::value;
611
612/// \brief Interface that allows matchers to traverse the AST.
613/// FIXME: Find a better name.
614///
615/// This provides three entry methods for each base node type in the AST:
616/// - \c matchesChildOf:
617///   Matches a matcher on every child node of the given node. Returns true
618///   if at least one child node could be matched.
619/// - \c matchesDescendantOf:
620///   Matches a matcher on all descendant nodes of the given node. Returns true
621///   if at least one descendant matched.
622/// - \c matchesAncestorOf:
623///   Matches a matcher on all ancestors of the given node. Returns true if
624///   at least one ancestor matched.
625///
626/// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal.
627/// In the future, we wan to implement this for all nodes for which it makes
628/// sense. In the case of matchesAncestorOf, we'll want to implement it for
629/// all nodes, as all nodes have ancestors.
630class ASTMatchFinder {
631public:
632  /// \brief Defines how we descend a level in the AST when we pass
633  /// through expressions.
634  enum TraversalKind {
635    /// Will traverse any child nodes.
636    TK_AsIs,
637    /// Will not traverse implicit casts and parentheses.
638    TK_IgnoreImplicitCastsAndParentheses
639  };
640
641  /// \brief Defines how bindings are processed on recursive matches.
642  enum BindKind {
643    /// Stop at the first match and only bind the first match.
644    BK_First,
645    /// Create results for all combinations of bindings that match.
646    BK_All
647  };
648
649  /// \brief Defines which ancestors are considered for a match.
650  enum AncestorMatchMode {
651    /// All ancestors.
652    AMM_All,
653    /// Direct parent only.
654    AMM_ParentOnly
655  };
656
657  virtual ~ASTMatchFinder() {}
658
659  /// \brief Returns true if the given class is directly or indirectly derived
660  /// from a base type matching \c base.
661  ///
662  /// A class is considered to be also derived from itself.
663  virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
664                                  const Matcher<NamedDecl> &Base,
665                                  BoundNodesTreeBuilder *Builder) = 0;
666
667  template <typename T>
668  bool matchesChildOf(const T &Node,
669                      const DynTypedMatcher &Matcher,
670                      BoundNodesTreeBuilder *Builder,
671                      TraversalKind Traverse,
672                      BindKind Bind) {
673    TOOLING_COMPILE_ASSERT(
674        (llvm::is_base_of<Decl, T>::value ||
675         llvm::is_base_of<Stmt, T>::value ||
676         llvm::is_base_of<NestedNameSpecifier, T>::value ||
677         llvm::is_base_of<NestedNameSpecifierLoc, T>::value ||
678         llvm::is_base_of<TypeLoc, T>::value ||
679         llvm::is_base_of<QualType, T>::value),
680        unsupported_type_for_recursive_matching);
681   return matchesChildOf(ast_type_traits::DynTypedNode::create(Node),
682                          Matcher, Builder, Traverse, Bind);
683  }
684
685  template <typename T>
686  bool matchesDescendantOf(const T &Node,
687                           const DynTypedMatcher &Matcher,
688                           BoundNodesTreeBuilder *Builder,
689                           BindKind Bind) {
690    TOOLING_COMPILE_ASSERT(
691        (llvm::is_base_of<Decl, T>::value ||
692         llvm::is_base_of<Stmt, T>::value ||
693         llvm::is_base_of<NestedNameSpecifier, T>::value ||
694         llvm::is_base_of<NestedNameSpecifierLoc, T>::value ||
695         llvm::is_base_of<TypeLoc, T>::value ||
696         llvm::is_base_of<QualType, T>::value),
697        unsupported_type_for_recursive_matching);
698    return matchesDescendantOf(ast_type_traits::DynTypedNode::create(Node),
699                               Matcher, Builder, Bind);
700  }
701
702  // FIXME: Implement support for BindKind.
703  template <typename T>
704  bool matchesAncestorOf(const T &Node,
705                         const DynTypedMatcher &Matcher,
706                         BoundNodesTreeBuilder *Builder,
707                         AncestorMatchMode MatchMode) {
708    TOOLING_COMPILE_ASSERT((llvm::is_base_of<Decl, T>::value ||
709                            llvm::is_base_of<Stmt, T>::value),
710                           only_Decl_or_Stmt_allowed_for_recursive_matching);
711    return matchesAncestorOf(ast_type_traits::DynTypedNode::create(Node),
712                             Matcher, Builder, MatchMode);
713  }
714
715  virtual ASTContext &getASTContext() const = 0;
716
717protected:
718  virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node,
719                              const DynTypedMatcher &Matcher,
720                              BoundNodesTreeBuilder *Builder,
721                              TraversalKind Traverse,
722                              BindKind Bind) = 0;
723
724  virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node,
725                                   const DynTypedMatcher &Matcher,
726                                   BoundNodesTreeBuilder *Builder,
727                                   BindKind Bind) = 0;
728
729  virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node,
730                                 const DynTypedMatcher &Matcher,
731                                 BoundNodesTreeBuilder *Builder,
732                                 AncestorMatchMode MatchMode) = 0;
733};
734
735/// \brief A simple type-list implementation.
736///
737/// It is implemented as a flat struct with a maximum number of arguments to
738/// simplify compiler error messages.
739/// However, it is used as a "linked list" of types.
740///
741/// Note: If you need to extend for more types, add them as template arguments
742///       and to the "typedef TypeList<...> tail" below. Nothing else is needed.
743template <typename T1 = void, typename T2 = void, typename T3 = void,
744          typename T4 = void, typename T5 = void, typename T6 = void,
745          typename T7 = void, typename T8 = void>
746struct TypeList {
747  /// \brief The first type on the list.
748  typedef T1 head;
749
750  /// \brief A sub list with the tail. ie everything but the head.
751  ///
752  /// This type is used to do recursion. TypeList<>/EmptyTypeList indicates the
753  /// end of the list.
754  typedef TypeList<T2, T3, T4, T5, T6, T7, T8> tail;
755
756  /// \brief Helper meta-function to determine if some type \c T is present or
757  ///   a parent type in the list.
758  template <typename T> struct ContainsSuperOf {
759    static const bool value = llvm::is_base_of<head, T>::value ||
760                              tail::template ContainsSuperOf<T>::value;
761  };
762};
763
764/// \brief Specialization of ContainsSuperOf for the empty list.
765template <> template <typename T> struct TypeList<>::ContainsSuperOf {
766  static const bool value = false;
767};
768
769/// \brief The empty type list.
770typedef TypeList<> EmptyTypeList;
771
772/// \brief A "type list" that contains all types.
773///
774/// Useful for matchers like \c anything and \c unless.
775typedef TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc,
776        QualType, Type, TypeLoc, CXXCtorInitializer> AllNodeBaseTypes;
777
778/// \brief Helper meta-function to extract the argument out of a function of
779///   type void(Arg).
780///
781/// See AST_POLYMORPHIC_SUPPORTED_TYPES_* for details.
782template <class T> struct ExtractFunctionArgMeta;
783template <class T> struct ExtractFunctionArgMeta<void(T)> {
784  typedef T type;
785};
786
787/// \brief Default type lists for ArgumentAdaptingMatcher matchers.
788typedef AllNodeBaseTypes AdaptativeDefaultFromTypes;
789typedef TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc,
790                 TypeLoc, QualType> AdaptativeDefaultToTypes;
791
792/// \brief Converts a \c Matcher<T> to a matcher of desired type \c To by
793/// "adapting" a \c To into a \c T.
794///
795/// The \c ArgumentAdapterT argument specifies how the adaptation is done.
796///
797/// For example:
798///   \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher);
799/// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher
800/// that is convertible into any matcher of type \c To by constructing
801/// \c HasMatcher<To, T>(InnerMatcher).
802///
803/// If a matcher does not need knowledge about the inner type, prefer to use
804/// PolymorphicMatcherWithParam1.
805template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
806          typename FromTypes = AdaptativeDefaultFromTypes,
807          typename ToTypes = AdaptativeDefaultToTypes>
808struct ArgumentAdaptingMatcherFunc {
809  template <typename T> class Adaptor {
810  public:
811    explicit Adaptor(const Matcher<T> &InnerMatcher)
812        : InnerMatcher(InnerMatcher) {}
813
814    typedef ToTypes ReturnTypes;
815
816    template <typename To> operator Matcher<To>() const {
817      return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher));
818    }
819
820  private:
821    const Matcher<T> InnerMatcher;
822  };
823
824  template <typename T>
825  static Adaptor<T> create(const Matcher<T> &InnerMatcher) {
826    return Adaptor<T>(InnerMatcher);
827  }
828
829  template <typename T>
830  Adaptor<T> operator()(const Matcher<T> &InnerMatcher) const {
831    return create(InnerMatcher);
832  }
833};
834
835/// \brief A PolymorphicMatcherWithParamN<MatcherT, P1, ..., PN> object can be
836/// created from N parameters p1, ..., pN (of type P1, ..., PN) and
837/// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN)
838/// can be constructed.
839///
840/// For example:
841/// - PolymorphicMatcherWithParam0<IsDefinitionMatcher>()
842///   creates an object that can be used as a Matcher<T> for any type T
843///   where an IsDefinitionMatcher<T>() can be constructed.
844/// - PolymorphicMatcherWithParam1<ValueEqualsMatcher, int>(42)
845///   creates an object that can be used as a Matcher<T> for any type T
846///   where a ValueEqualsMatcher<T, int>(42) can be constructed.
847template <template <typename T> class MatcherT,
848          typename ReturnTypesF = void(AllNodeBaseTypes)>
849class PolymorphicMatcherWithParam0 {
850public:
851  typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
852  template <typename T>
853  operator Matcher<T>() const {
854    TOOLING_COMPILE_ASSERT(ReturnTypes::template ContainsSuperOf<T>::value,
855                           right_polymorphic_conversion);
856    return Matcher<T>(new MatcherT<T>());
857  }
858};
859
860template <template <typename T, typename P1> class MatcherT,
861          typename P1,
862          typename ReturnTypesF = void(AllNodeBaseTypes)>
863class PolymorphicMatcherWithParam1 {
864public:
865  explicit PolymorphicMatcherWithParam1(const P1 &Param1)
866      : Param1(Param1) {}
867
868  typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
869
870  template <typename T>
871  operator Matcher<T>() const {
872    TOOLING_COMPILE_ASSERT(ReturnTypes::template ContainsSuperOf<T>::value,
873                           right_polymorphic_conversion);
874    return Matcher<T>(new MatcherT<T, P1>(Param1));
875  }
876
877private:
878  const P1 Param1;
879};
880
881template <template <typename T, typename P1, typename P2> class MatcherT,
882          typename P1, typename P2,
883          typename ReturnTypesF = void(AllNodeBaseTypes)>
884class PolymorphicMatcherWithParam2 {
885public:
886  PolymorphicMatcherWithParam2(const P1 &Param1, const P2 &Param2)
887      : Param1(Param1), Param2(Param2) {}
888
889  typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
890
891  template <typename T>
892  operator Matcher<T>() const {
893    TOOLING_COMPILE_ASSERT(ReturnTypes::template ContainsSuperOf<T>::value,
894                           right_polymorphic_conversion);
895    return Matcher<T>(new MatcherT<T, P1, P2>(Param1, Param2));
896  }
897
898private:
899  const P1 Param1;
900  const P2 Param2;
901};
902
903/// \brief Matches any instance of the given NodeType.
904///
905/// This is useful when a matcher syntactically requires a child matcher,
906/// but the context doesn't care. See for example: anything().
907///
908/// FIXME: Alternatively we could also create a IsAMatcher or something
909/// that checks that a dyn_cast is possible. This is purely needed for the
910/// difference between calling for example:
911///   record()
912/// and
913///   record(SomeMatcher)
914/// In the second case we need the correct type we were dyn_cast'ed to in order
915/// to get the right type for the inner matcher. In the first case we don't need
916/// that, but we use the type conversion anyway and insert a TrueMatcher.
917template <typename T>
918class TrueMatcher : public SingleNodeMatcherInterface<T>  {
919public:
920  virtual bool matchesNode(const T &Node) const {
921    return true;
922  }
923};
924
925/// \brief Provides a MatcherInterface<T> for a Matcher<To> that matches if T is
926/// dyn_cast'able into To and the given Matcher<To> matches on the dyn_cast'ed
927/// node.
928template <typename T, typename To>
929class DynCastMatcher : public MatcherInterface<T> {
930public:
931  explicit DynCastMatcher(const Matcher<To> &InnerMatcher)
932      : InnerMatcher(InnerMatcher) {}
933
934  virtual bool matches(const T &Node,
935                       ASTMatchFinder *Finder,
936                       BoundNodesTreeBuilder *Builder) const {
937    const To *InnerMatchValue = dyn_cast<To>(&Node);
938    return InnerMatchValue != NULL &&
939      InnerMatcher.matches(*InnerMatchValue, Finder, Builder);
940  }
941
942private:
943  const Matcher<To> InnerMatcher;
944};
945
946/// \brief Matcher<T> that wraps an inner Matcher<T> and binds the matched node
947/// to an ID if the inner matcher matches on the node.
948template <typename T>
949class IdMatcher : public MatcherInterface<T> {
950public:
951  /// \brief Creates an IdMatcher that binds to 'ID' if 'InnerMatcher' matches
952  /// the node.
953  IdMatcher(StringRef ID, const Matcher<T> &InnerMatcher)
954      : ID(ID), InnerMatcher(InnerMatcher) {}
955
956  virtual bool matches(const T &Node,
957                       ASTMatchFinder *Finder,
958                       BoundNodesTreeBuilder *Builder) const {
959    bool Result = InnerMatcher.matches(Node, Finder, Builder);
960    if (Result) {
961      Builder->setBinding(ID, &Node);
962    }
963    return Result;
964  }
965
966private:
967  const std::string ID;
968  const Matcher<T> InnerMatcher;
969};
970
971/// \brief A Matcher that allows binding the node it matches to an id.
972///
973/// BindableMatcher provides a \a bind() method that allows binding the
974/// matched node to an id if the match was successful.
975template <typename T>
976class BindableMatcher : public Matcher<T> {
977public:
978  BindableMatcher(MatcherInterface<T> *Implementation)
979    : Matcher<T>(Implementation) {}
980
981  /// \brief Returns a matcher that will bind the matched node on a match.
982  ///
983  /// The returned matcher is equivalent to this matcher, but will
984  /// bind the matched node on a match.
985  Matcher<T> bind(StringRef ID) const {
986    return Matcher<T>(new IdMatcher<T>(ID, *this));
987  }
988
989  /// \brief Makes a copy of this matcher object.
990  virtual BindableMatcher<T>* clone() const {
991    return new BindableMatcher<T>(*this);
992  }
993
994  /// \brief Bind the specified \c ID to the matcher.
995  virtual Matcher<T>* tryBind(StringRef ID) const {
996    return new Matcher<T>(bind(ID));
997  }
998};
999
1000/// \brief Matches nodes of type T that have child nodes of type ChildT for
1001/// which a specified child matcher matches.
1002///
1003/// ChildT must be an AST base type.
1004template <typename T, typename ChildT>
1005class HasMatcher : public MatcherInterface<T> {
1006  TOOLING_COMPILE_ASSERT(IsBaseType<ChildT>::value,
1007                         has_only_accepts_base_type_matcher);
1008public:
1009  explicit HasMatcher(const Matcher<ChildT> &ChildMatcher)
1010      : ChildMatcher(ChildMatcher) {}
1011
1012  virtual bool matches(const T &Node,
1013                       ASTMatchFinder *Finder,
1014                       BoundNodesTreeBuilder *Builder) const {
1015    return Finder->matchesChildOf(
1016        Node, ChildMatcher, Builder,
1017        ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
1018        ASTMatchFinder::BK_First);
1019  }
1020
1021 private:
1022  const Matcher<ChildT> ChildMatcher;
1023};
1024
1025/// \brief Matches nodes of type T that have child nodes of type ChildT for
1026/// which a specified child matcher matches. ChildT must be an AST base
1027/// type.
1028/// As opposed to the HasMatcher, the ForEachMatcher will produce a match
1029/// for each child that matches.
1030template <typename T, typename ChildT>
1031class ForEachMatcher : public MatcherInterface<T> {
1032  TOOLING_COMPILE_ASSERT(IsBaseType<ChildT>::value,
1033                         for_each_only_accepts_base_type_matcher);
1034 public:
1035  explicit ForEachMatcher(const Matcher<ChildT> &ChildMatcher)
1036      : ChildMatcher(ChildMatcher) {}
1037
1038  virtual bool matches(const T& Node,
1039                       ASTMatchFinder* Finder,
1040                       BoundNodesTreeBuilder* Builder) const {
1041    return Finder->matchesChildOf(
1042      Node, ChildMatcher, Builder,
1043      ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
1044      ASTMatchFinder::BK_All);
1045  }
1046
1047private:
1048  const Matcher<ChildT> ChildMatcher;
1049};
1050
1051/// \brief Matches nodes of type T if the given Matcher<T> does not match.
1052///
1053/// Type argument MatcherT is required by PolymorphicMatcherWithParam1
1054/// but not actually used. It will always be instantiated with a type
1055/// convertible to Matcher<T>.
1056template <typename T, typename MatcherT>
1057class NotMatcher : public MatcherInterface<T> {
1058public:
1059  explicit NotMatcher(const Matcher<T> &InnerMatcher)
1060      : InnerMatcher(InnerMatcher) {}
1061
1062  virtual bool matches(const T &Node,
1063                       ASTMatchFinder *Finder,
1064                       BoundNodesTreeBuilder *Builder) const {
1065    // The 'unless' matcher will always discard the result:
1066    // If the inner matcher doesn't match, unless returns true,
1067    // but the inner matcher cannot have bound anything.
1068    // If the inner matcher matches, the result is false, and
1069    // any possible binding will be discarded.
1070    // We still need to hand in all the bound nodes up to this
1071    // point so the inner matcher can depend on bound nodes,
1072    // and we need to actively discard the bound nodes, otherwise
1073    // the inner matcher will reset the bound nodes if it doesn't
1074    // match, but this would be inversed by 'unless'.
1075    BoundNodesTreeBuilder Discard(*Builder);
1076    return !InnerMatcher.matches(Node, Finder, &Discard);
1077  }
1078
1079private:
1080  const Matcher<T> InnerMatcher;
1081};
1082
1083/// \brief VariadicOperatorMatcher related types.
1084/// @{
1085
1086/// \brief Function signature for any variadic operator. It takes the inner
1087///   matchers as an array of DynTypedMatcher.
1088typedef bool (*VariadicOperatorFunction)(
1089    const ast_type_traits::DynTypedNode DynNode, ASTMatchFinder *Finder,
1090    BoundNodesTreeBuilder *Builder,
1091    ArrayRef<const DynTypedMatcher *> InnerMatchers);
1092
1093/// \brief \c MatcherInterface<T> implementation for an variadic operator.
1094template <typename T>
1095class VariadicOperatorMatcherInterface : public MatcherInterface<T> {
1096public:
1097  VariadicOperatorMatcherInterface(VariadicOperatorFunction Func,
1098                                   ArrayRef<const Matcher<T> *> InputMatchers)
1099      : Func(Func) {
1100    for (size_t i = 0, e = InputMatchers.size(); i != e; ++i) {
1101      InnerMatchers.push_back(new Matcher<T>(*InputMatchers[i]));
1102    }
1103  }
1104
1105  ~VariadicOperatorMatcherInterface() {
1106    llvm::DeleteContainerPointers(InnerMatchers);
1107  }
1108
1109  virtual bool matches(const T &Node, ASTMatchFinder *Finder,
1110                       BoundNodesTreeBuilder *Builder) const {
1111    return Func(ast_type_traits::DynTypedNode::create(Node), Finder, Builder,
1112                InnerMatchers);
1113  }
1114
1115private:
1116  const VariadicOperatorFunction Func;
1117  std::vector<const DynTypedMatcher *> InnerMatchers;
1118};
1119
1120/// \brief "No argument" placeholder to use as template paratemers.
1121struct VariadicOperatorNoArg {};
1122
1123/// \brief Polymorphic matcher object that uses a \c VariadicOperatorFunction
1124///   operator.
1125///
1126/// Input matchers can have any type (including other polymorphic matcher
1127/// types), and the actual Matcher<T> is generated on demand with an implicit
1128/// coversion operator.
1129template <typename P1, typename P2,
1130          typename P3 = VariadicOperatorNoArg,
1131          typename P4 = VariadicOperatorNoArg,
1132          typename P5 = VariadicOperatorNoArg>
1133class VariadicOperatorMatcher {
1134public:
1135  VariadicOperatorMatcher(VariadicOperatorFunction Func, const P1 &Param1,
1136                          const P2 &Param2,
1137                          const P3 &Param3 = VariadicOperatorNoArg(),
1138                          const P4 &Param4 = VariadicOperatorNoArg(),
1139                          const P5 &Param5 = VariadicOperatorNoArg())
1140      : Func(Func), Param1(Param1), Param2(Param2), Param3(Param3),
1141        Param4(Param4), Param5(Param5) {}
1142
1143  template <typename T> operator Matcher<T>() const {
1144    Matcher<T> *Array[5];
1145    size_t Size = 0;
1146
1147    addMatcher<T>(Param1, Array, Size);
1148    addMatcher<T>(Param2, Array, Size);
1149    addMatcher<T>(Param3, Array, Size);
1150    addMatcher<T>(Param4, Array, Size);
1151    addMatcher<T>(Param5, Array, Size);
1152    Matcher<T> Result(new VariadicOperatorMatcherInterface<T>(
1153        Func, ArrayRef<const Matcher<T> *>(Array, Size)));
1154    for (size_t i = 0, e = Size; i != e; ++i) delete Array[i];
1155    return Result;
1156  }
1157
1158private:
1159  template <typename T>
1160  static void addMatcher(const Matcher<T> &M, Matcher<T> **Array,
1161                         size_t &Size) {
1162    Array[Size++] = new Matcher<T>(M);
1163  }
1164
1165  /// \brief Overload to ignore \c VariadicOperatorNoArg arguments.
1166  template <typename T>
1167  static void addMatcher(VariadicOperatorNoArg, Matcher<T> **Array,
1168                         size_t &Size) {}
1169
1170  const VariadicOperatorFunction Func;
1171  const P1 Param1;
1172  const P2 Param2;
1173  const P3 Param3;
1174  const P4 Param4;
1175  const P5 Param5;
1176};
1177
1178/// \brief Overloaded function object to generate VariadicOperatorMatcher
1179///   objects from arbitrary matchers.
1180///
1181/// It supports 2-5 argument overloaded operator(). More can be added if needed.
1182struct VariadicOperatorMatcherFunc {
1183  VariadicOperatorFunction Func;
1184
1185  template <typename M1, typename M2>
1186  VariadicOperatorMatcher<M1, M2> operator()(const M1 &P1, const M2 &P2) const {
1187    return VariadicOperatorMatcher<M1, M2>(Func, P1, P2);
1188  }
1189  template <typename M1, typename M2, typename M3>
1190  VariadicOperatorMatcher<M1, M2, M3> operator()(const M1 &P1, const M2 &P2,
1191                                                 const M3 &P3) const {
1192    return VariadicOperatorMatcher<M1, M2, M3>(Func, P1, P2, P3);
1193  }
1194  template <typename M1, typename M2, typename M3, typename M4>
1195  VariadicOperatorMatcher<M1, M2, M3, M4>
1196  operator()(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4) const {
1197    return VariadicOperatorMatcher<M1, M2, M3, M4>(Func, P1, P2, P3, P4);
1198  }
1199  template <typename M1, typename M2, typename M3, typename M4, typename M5>
1200  VariadicOperatorMatcher<M1, M2, M3, M4, M5>
1201  operator()(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4,
1202             const M5 &P5) const {
1203    return VariadicOperatorMatcher<M1, M2, M3, M4, M5>(Func, P1, P2, P3, P4,
1204                                                       P5);
1205  }
1206};
1207
1208/// @}
1209
1210/// \brief Matches nodes for which all provided matchers match.
1211bool
1212AllOfVariadicOperator(const ast_type_traits::DynTypedNode DynNode,
1213                      ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder,
1214                      ArrayRef<const DynTypedMatcher *> InnerMatchers);
1215
1216/// \brief Matches nodes for which at least one of the provided matchers
1217/// matches, but doesn't stop at the first match.
1218bool
1219EachOfVariadicOperator(const ast_type_traits::DynTypedNode DynNode,
1220                       ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder,
1221                       ArrayRef<const DynTypedMatcher *> InnerMatchers);
1222
1223/// \brief Matches nodes for which at least one of the provided matchers
1224/// matches.
1225bool
1226AnyOfVariadicOperator(const ast_type_traits::DynTypedNode DynNode,
1227                      ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder,
1228                      ArrayRef<const DynTypedMatcher *> InnerMatchers);
1229
1230/// \brief Creates a Matcher<T> that matches if all inner matchers match.
1231template<typename T>
1232BindableMatcher<T> makeAllOfComposite(
1233    ArrayRef<const Matcher<T> *> InnerMatchers) {
1234  if (InnerMatchers.empty())
1235    return BindableMatcher<T>(new TrueMatcher<T>);
1236  return BindableMatcher<T>(new VariadicOperatorMatcherInterface<T>(
1237      AllOfVariadicOperator, InnerMatchers));
1238}
1239
1240/// \brief Creates a Matcher<T> that matches if
1241/// T is dyn_cast'able into InnerT and all inner matchers match.
1242///
1243/// Returns BindableMatcher, as matchers that use dyn_cast have
1244/// the same object both to match on and to run submatchers on,
1245/// so there is no ambiguity with what gets bound.
1246template<typename T, typename InnerT>
1247BindableMatcher<T> makeDynCastAllOfComposite(
1248    ArrayRef<const Matcher<InnerT> *> InnerMatchers) {
1249  return BindableMatcher<T>(new DynCastMatcher<T, InnerT>(
1250    makeAllOfComposite(InnerMatchers)));
1251}
1252
1253/// \brief Matches nodes of type T that have at least one descendant node of
1254/// type DescendantT for which the given inner matcher matches.
1255///
1256/// DescendantT must be an AST base type.
1257template <typename T, typename DescendantT>
1258class HasDescendantMatcher : public MatcherInterface<T> {
1259  TOOLING_COMPILE_ASSERT(IsBaseType<DescendantT>::value,
1260                         has_descendant_only_accepts_base_type_matcher);
1261public:
1262  explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher)
1263      : DescendantMatcher(DescendantMatcher) {}
1264
1265  virtual bool matches(const T &Node,
1266                       ASTMatchFinder *Finder,
1267                       BoundNodesTreeBuilder *Builder) const {
1268    return Finder->matchesDescendantOf(
1269        Node, DescendantMatcher, Builder, ASTMatchFinder::BK_First);
1270  }
1271
1272 private:
1273  const Matcher<DescendantT> DescendantMatcher;
1274};
1275
1276/// \brief Matches nodes of type \c T that have a parent node of type \c ParentT
1277/// for which the given inner matcher matches.
1278///
1279/// \c ParentT must be an AST base type.
1280template <typename T, typename ParentT>
1281class HasParentMatcher : public MatcherInterface<T> {
1282  TOOLING_COMPILE_ASSERT(IsBaseType<ParentT>::value,
1283                         has_parent_only_accepts_base_type_matcher);
1284public:
1285  explicit HasParentMatcher(const Matcher<ParentT> &ParentMatcher)
1286      : ParentMatcher(ParentMatcher) {}
1287
1288  virtual bool matches(const T &Node,
1289                       ASTMatchFinder *Finder,
1290                       BoundNodesTreeBuilder *Builder) const {
1291    return Finder->matchesAncestorOf(
1292        Node, ParentMatcher, Builder, ASTMatchFinder::AMM_ParentOnly);
1293  }
1294
1295 private:
1296  const Matcher<ParentT> ParentMatcher;
1297};
1298
1299/// \brief Matches nodes of type \c T that have at least one ancestor node of
1300/// type \c AncestorT for which the given inner matcher matches.
1301///
1302/// \c AncestorT must be an AST base type.
1303template <typename T, typename AncestorT>
1304class HasAncestorMatcher : public MatcherInterface<T> {
1305  TOOLING_COMPILE_ASSERT(IsBaseType<AncestorT>::value,
1306                         has_ancestor_only_accepts_base_type_matcher);
1307public:
1308  explicit HasAncestorMatcher(const Matcher<AncestorT> &AncestorMatcher)
1309      : AncestorMatcher(AncestorMatcher) {}
1310
1311  virtual bool matches(const T &Node,
1312                       ASTMatchFinder *Finder,
1313                       BoundNodesTreeBuilder *Builder) const {
1314    return Finder->matchesAncestorOf(
1315        Node, AncestorMatcher, Builder, ASTMatchFinder::AMM_All);
1316  }
1317
1318 private:
1319  const Matcher<AncestorT> AncestorMatcher;
1320};
1321
1322/// \brief Matches nodes of type T that have at least one descendant node of
1323/// type DescendantT for which the given inner matcher matches.
1324///
1325/// DescendantT must be an AST base type.
1326/// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match
1327/// for each descendant node that matches instead of only for the first.
1328template <typename T, typename DescendantT>
1329class ForEachDescendantMatcher : public MatcherInterface<T> {
1330  TOOLING_COMPILE_ASSERT(IsBaseType<DescendantT>::value,
1331                         for_each_descendant_only_accepts_base_type_matcher);
1332 public:
1333  explicit ForEachDescendantMatcher(
1334      const Matcher<DescendantT>& DescendantMatcher)
1335      : DescendantMatcher(DescendantMatcher) {}
1336
1337  virtual bool matches(const T& Node,
1338                       ASTMatchFinder* Finder,
1339                       BoundNodesTreeBuilder* Builder) const {
1340    return Finder->matchesDescendantOf(Node, DescendantMatcher, Builder,
1341                                       ASTMatchFinder::BK_All);
1342  }
1343
1344private:
1345  const Matcher<DescendantT> DescendantMatcher;
1346};
1347
1348/// \brief Matches on nodes that have a getValue() method if getValue() equals
1349/// the value the ValueEqualsMatcher was constructed with.
1350template <typename T, typename ValueT>
1351class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> {
1352  TOOLING_COMPILE_ASSERT((llvm::is_base_of<CharacterLiteral, T>::value ||
1353                         llvm::is_base_of<CXXBoolLiteralExpr,
1354                                          T>::value ||
1355                         llvm::is_base_of<FloatingLiteral, T>::value ||
1356                         llvm::is_base_of<IntegerLiteral, T>::value),
1357                         the_node_must_have_a_getValue_method);
1358public:
1359  explicit ValueEqualsMatcher(const ValueT &ExpectedValue)
1360      : ExpectedValue(ExpectedValue) {}
1361
1362  virtual bool matchesNode(const T &Node) const {
1363    return Node.getValue() == ExpectedValue;
1364  }
1365
1366private:
1367  const ValueT ExpectedValue;
1368};
1369
1370/// \brief A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a
1371/// variadic functor that takes a number of Matcher<TargetT> and returns a
1372/// Matcher<SourceT> that matches TargetT nodes that are matched by all of the
1373/// given matchers, if SourceT can be dynamically casted into TargetT.
1374///
1375/// For example:
1376///   const VariadicDynCastAllOfMatcher<
1377///       Decl, CXXRecordDecl> record;
1378/// Creates a functor record(...) that creates a Matcher<Decl> given
1379/// a variable number of arguments of type Matcher<CXXRecordDecl>.
1380/// The returned matcher matches if the given Decl can by dynamically
1381/// casted to CXXRecordDecl and all given matchers match.
1382template <typename SourceT, typename TargetT>
1383class VariadicDynCastAllOfMatcher
1384    : public llvm::VariadicFunction<
1385        BindableMatcher<SourceT>, Matcher<TargetT>,
1386        makeDynCastAllOfComposite<SourceT, TargetT> > {
1387public:
1388  VariadicDynCastAllOfMatcher() {}
1389};
1390
1391/// \brief A \c VariadicAllOfMatcher<T> object is a variadic functor that takes
1392/// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T
1393/// nodes that are matched by all of the given matchers.
1394///
1395/// For example:
1396///   const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
1397/// Creates a functor nestedNameSpecifier(...) that creates a
1398/// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type
1399/// \c Matcher<NestedNameSpecifier>.
1400/// The returned matcher matches if all given matchers match.
1401template <typename T>
1402class VariadicAllOfMatcher : public llvm::VariadicFunction<
1403                               BindableMatcher<T>, Matcher<T>,
1404                               makeAllOfComposite<T> > {
1405public:
1406  VariadicAllOfMatcher() {}
1407};
1408
1409/// \brief Matches nodes of type \c TLoc for which the inner
1410/// \c Matcher<T> matches.
1411template <typename TLoc, typename T>
1412class LocMatcher : public MatcherInterface<TLoc> {
1413public:
1414  explicit LocMatcher(const Matcher<T> &InnerMatcher)
1415    : InnerMatcher(InnerMatcher) {}
1416
1417  virtual bool matches(const TLoc &Node,
1418                       ASTMatchFinder *Finder,
1419                       BoundNodesTreeBuilder *Builder) const {
1420    if (!Node)
1421      return false;
1422    return InnerMatcher.matches(*extract(Node), Finder, Builder);
1423  }
1424
1425private:
1426  const NestedNameSpecifier *extract(const NestedNameSpecifierLoc &Loc) const {
1427    return Loc.getNestedNameSpecifier();
1428  }
1429
1430  const Matcher<T> InnerMatcher;
1431};
1432
1433/// \brief Matches \c TypeLocs based on an inner matcher matching a certain
1434/// \c QualType.
1435///
1436/// Used to implement the \c loc() matcher.
1437class TypeLocTypeMatcher : public MatcherInterface<TypeLoc> {
1438public:
1439  explicit TypeLocTypeMatcher(const Matcher<QualType> &InnerMatcher)
1440      : InnerMatcher(InnerMatcher) {}
1441
1442  virtual bool matches(const TypeLoc &Node,
1443                       ASTMatchFinder *Finder,
1444                       BoundNodesTreeBuilder *Builder) const {
1445    if (!Node)
1446      return false;
1447    return InnerMatcher.matches(Node.getType(), Finder, Builder);
1448  }
1449
1450private:
1451  const Matcher<QualType> InnerMatcher;
1452};
1453
1454/// \brief Matches nodes of type \c T for which the inner matcher matches on a
1455/// another node of type \c T that can be reached using a given traverse
1456/// function.
1457template <typename T>
1458class TypeTraverseMatcher : public MatcherInterface<T> {
1459public:
1460  explicit TypeTraverseMatcher(const Matcher<QualType> &InnerMatcher,
1461                               QualType (T::*TraverseFunction)() const)
1462      : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {}
1463
1464  virtual bool matches(const T &Node,
1465                       ASTMatchFinder *Finder,
1466                       BoundNodesTreeBuilder *Builder) const {
1467    QualType NextNode = (Node.*TraverseFunction)();
1468    if (NextNode.isNull())
1469      return false;
1470    return InnerMatcher.matches(NextNode, Finder, Builder);
1471  }
1472
1473private:
1474  const Matcher<QualType> InnerMatcher;
1475  QualType (T::*TraverseFunction)() const;
1476};
1477
1478/// \brief Matches nodes of type \c T in a ..Loc hierarchy, for which the inner
1479/// matcher matches on a another node of type \c T that can be reached using a
1480/// given traverse function.
1481template <typename T>
1482class TypeLocTraverseMatcher : public MatcherInterface<T> {
1483public:
1484  explicit TypeLocTraverseMatcher(const Matcher<TypeLoc> &InnerMatcher,
1485                                  TypeLoc (T::*TraverseFunction)() const)
1486      : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {}
1487
1488  virtual bool matches(const T &Node,
1489                       ASTMatchFinder *Finder,
1490                       BoundNodesTreeBuilder *Builder) const {
1491    TypeLoc NextNode = (Node.*TraverseFunction)();
1492    if (!NextNode)
1493      return false;
1494    return InnerMatcher.matches(NextNode, Finder, Builder);
1495  }
1496
1497private:
1498  const Matcher<TypeLoc> InnerMatcher;
1499  TypeLoc (T::*TraverseFunction)() const;
1500};
1501
1502/// \brief Converts a \c Matcher<InnerT> to a \c Matcher<OuterT>, where
1503/// \c OuterT is any type that is supported by \c Getter.
1504///
1505/// \code Getter<OuterT>::value() \endcode returns a
1506/// \code InnerTBase (OuterT::*)() \endcode, which is used to adapt a \c OuterT
1507/// object into a \c InnerT
1508template <typename InnerTBase,
1509          template <typename OuterT> class Getter,
1510          template <typename OuterT> class MatcherImpl,
1511          typename ReturnTypesF>
1512class TypeTraversePolymorphicMatcher {
1513private:
1514  typedef TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl,
1515                                         ReturnTypesF> Self;
1516  static Self create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers);
1517
1518public:
1519  typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
1520
1521  explicit TypeTraversePolymorphicMatcher(
1522      ArrayRef<const Matcher<InnerTBase> *> InnerMatchers)
1523      : InnerMatcher(makeAllOfComposite(InnerMatchers)) {}
1524
1525  template <typename OuterT> operator Matcher<OuterT>() const {
1526    return Matcher<OuterT>(
1527        new MatcherImpl<OuterT>(InnerMatcher, Getter<OuterT>::value()));
1528  }
1529
1530  struct Func : public llvm::VariadicFunction<Self, Matcher<InnerTBase>,
1531                                              &Self::create> {
1532    Func() {}
1533  };
1534
1535private:
1536  const Matcher<InnerTBase> InnerMatcher;
1537};
1538
1539// Define the create() method out of line to silence a GCC warning about
1540// the struct "Func" having greater visibility than its base, which comes from
1541// using the flag -fvisibility-inlines-hidden.
1542template <typename InnerTBase, template <typename OuterT> class Getter,
1543          template <typename OuterT> class MatcherImpl, typename ReturnTypesF>
1544TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl, ReturnTypesF>
1545TypeTraversePolymorphicMatcher<
1546    InnerTBase, Getter, MatcherImpl,
1547    ReturnTypesF>::create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers) {
1548  return Self(InnerMatchers);
1549}
1550
1551} // end namespace internal
1552} // end namespace ast_matchers
1553} // end namespace clang
1554
1555#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H
1556