1 //===--- ASTMatchersInternal.h - Structural query framework -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implements the base layer of the matcher framework.
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
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>.
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.
31 // This file contains the base classes needed to construct the actual matchers.
33 //===----------------------------------------------------------------------===//
35 #ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERSINTERNAL_H
36 #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERSINTERNAL_H
38 #include "clang/AST/ASTTypeTraits.h"
39 #include "clang/AST/Decl.h"
40 #include "clang/AST/DeclCXX.h"
41 #include "clang/AST/ExprCXX.h"
42 #include "clang/AST/Stmt.h"
43 #include "clang/AST/StmtCXX.h"
44 #include "clang/AST/Type.h"
45 #include "llvm/ADT/Optional.h"
46 #include "llvm/ADT/VariadicFunction.h"
47 #include "llvm/Support/ManagedStatic.h"
53 namespace ast_matchers {
59 /// \brief Internal version of BoundNodes. Holds all the bound nodes.
62 /// \brief Adds \c Node to the map with key \c ID.
64 /// The node's base type should be in NodeBaseType or it will be unaccessible.
65 void addNode(StringRef ID, const ast_type_traits::DynTypedNode& DynNode) {
66 NodeMap[ID] = DynNode;
69 /// \brief Returns the AST node bound to \c ID.
71 /// Returns NULL if there was no node bound to \c ID or if there is a node but
72 /// it cannot be converted to the specified type.
74 const T *getNodeAs(StringRef ID) const {
75 IDToNodeMap::const_iterator It = NodeMap.find(ID);
76 if (It == NodeMap.end()) {
79 return It->second.get<T>();
82 ast_type_traits::DynTypedNode getNode(StringRef ID) const {
83 IDToNodeMap::const_iterator It = NodeMap.find(ID);
84 if (It == NodeMap.end()) {
85 return ast_type_traits::DynTypedNode();
90 /// \brief Imposes an order on BoundNodesMaps.
91 bool operator<(const BoundNodesMap &Other) const {
92 return NodeMap < Other.NodeMap;
95 /// \brief A map from IDs to the bound nodes.
97 /// Note that we're using std::map here, as for memoization:
98 /// - we need a comparison operator
99 /// - we need an assignment operator
100 typedef std::map<std::string, ast_type_traits::DynTypedNode> IDToNodeMap;
102 const IDToNodeMap &getMap() const {
106 /// \brief Returns \c true if this \c BoundNodesMap can be compared, i.e. all
107 /// stored nodes have memoization data.
108 bool isComparable() const {
109 for (const auto &IDAndNode : NodeMap) {
110 if (!IDAndNode.second.getMemoizationData())
120 /// \brief Creates BoundNodesTree objects.
122 /// The tree builder is used during the matching process to insert the bound
123 /// nodes from the Id matcher.
124 class BoundNodesTreeBuilder {
126 /// \brief A visitor interface to visit all BoundNodes results for a
130 virtual ~Visitor() {}
132 /// \brief Called multiple times during a single call to VisitMatches(...).
134 /// 'BoundNodesView' contains the bound nodes for a single match.
135 virtual void visitMatch(const BoundNodes& BoundNodesView) = 0;
138 /// \brief Add a binding from an id to a node.
139 void setBinding(const std::string &Id,
140 const ast_type_traits::DynTypedNode &DynNode) {
141 if (Bindings.empty())
142 Bindings.push_back(BoundNodesMap());
143 for (BoundNodesMap &Binding : Bindings)
144 Binding.addNode(Id, DynNode);
147 /// \brief Adds a branch in the tree.
148 void addMatch(const BoundNodesTreeBuilder &Bindings);
150 /// \brief Visits all matches that this BoundNodesTree represents.
152 /// The ownership of 'ResultVisitor' remains at the caller.
153 void visitMatches(Visitor* ResultVisitor);
155 template <typename ExcludePredicate>
156 bool removeBindings(const ExcludePredicate &Predicate) {
157 Bindings.erase(std::remove_if(Bindings.begin(), Bindings.end(), Predicate),
159 return !Bindings.empty();
162 /// \brief Imposes an order on BoundNodesTreeBuilders.
163 bool operator<(const BoundNodesTreeBuilder &Other) const {
164 return Bindings < Other.Bindings;
167 /// \brief Returns \c true if this \c BoundNodesTreeBuilder can be compared,
168 /// i.e. all stored node maps have memoization data.
169 bool isComparable() const {
170 for (const BoundNodesMap &NodesMap : Bindings) {
171 if (!NodesMap.isComparable())
178 SmallVector<BoundNodesMap, 16> Bindings;
181 class ASTMatchFinder;
183 /// \brief Generic interface for all matchers.
185 /// Used by the implementation of Matcher<T> and DynTypedMatcher.
186 /// In general, implement MatcherInterface<T> or SingleNodeMatcherInterface<T>
188 class DynMatcherInterface : public RefCountedBaseVPTR {
190 /// \brief Returns true if \p DynNode can be matched.
192 /// May bind \p DynNode to an ID via \p Builder, or recurse into
193 /// the AST via \p Finder.
194 virtual bool dynMatches(const ast_type_traits::DynTypedNode &DynNode,
195 ASTMatchFinder *Finder,
196 BoundNodesTreeBuilder *Builder) const = 0;
199 /// \brief Generic interface for matchers on an AST node of type T.
201 /// Implement this if your matcher may need to inspect the children or
202 /// descendants of the node or bind matched nodes to names. If you are
203 /// writing a simple matcher that only inspects properties of the
204 /// current node and doesn't care about its children or descendants,
205 /// implement SingleNodeMatcherInterface instead.
206 template <typename T>
207 class MatcherInterface : public DynMatcherInterface {
209 virtual ~MatcherInterface() {}
211 /// \brief Returns true if 'Node' can be matched.
213 /// May bind 'Node' to an ID via 'Builder', or recurse into
214 /// the AST via 'Finder'.
215 virtual bool matches(const T &Node,
216 ASTMatchFinder *Finder,
217 BoundNodesTreeBuilder *Builder) const = 0;
219 bool dynMatches(const ast_type_traits::DynTypedNode &DynNode,
220 ASTMatchFinder *Finder,
221 BoundNodesTreeBuilder *Builder) const override {
222 return matches(DynNode.getUnchecked<T>(), Finder, Builder);
226 /// \brief Interface for matchers that only evaluate properties on a single
228 template <typename T>
229 class SingleNodeMatcherInterface : public MatcherInterface<T> {
231 /// \brief Returns true if the matcher matches the provided node.
233 /// A subclass must implement this instead of Matches().
234 virtual bool matchesNode(const T &Node) const = 0;
237 /// Implements MatcherInterface::Matches.
238 bool matches(const T &Node,
239 ASTMatchFinder * /* Finder */,
240 BoundNodesTreeBuilder * /* Builder */) const override {
241 return matchesNode(Node);
245 template <typename> class Matcher;
247 /// \brief Matcher that works on a \c DynTypedNode.
249 /// It is constructed from a \c Matcher<T> object and redirects most calls to
250 /// underlying matcher.
251 /// It checks whether the \c DynTypedNode is convertible into the type of the
252 /// underlying matcher and then do the actual match on the actual node, or
253 /// return false if it is not convertible.
254 class DynTypedMatcher {
256 /// \brief Takes ownership of the provided implementation pointer.
257 template <typename T>
258 DynTypedMatcher(MatcherInterface<T> *Implementation)
260 SupportedKind(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()),
261 RestrictKind(SupportedKind), Implementation(Implementation) {}
263 /// \brief Construct from a variadic function.
264 enum VariadicOperator {
265 /// \brief Matches nodes for which all provided matchers match.
267 /// \brief Matches nodes for which at least one of the provided matchers
270 /// \brief Matches nodes for which at least one of the provided matchers
271 /// matches, but doesn't stop at the first match.
273 /// \brief Matches nodes that do not match the provided matcher.
275 /// Uses the variadic matcher interface, but fails if
276 /// InnerMatchers.size() != 1.
279 static DynTypedMatcher
280 constructVariadic(VariadicOperator Op,
281 std::vector<DynTypedMatcher> InnerMatchers);
283 /// \brief Get a "true" matcher for \p NodeKind.
285 /// It only checks that the node is of the right kind.
286 static DynTypedMatcher trueMatcher(ast_type_traits::ASTNodeKind NodeKind);
288 void setAllowBind(bool AB) { AllowBind = AB; }
290 /// \brief Check whether this matcher could ever match a node of kind \p Kind.
291 /// \return \c false if this matcher will never match such a node. Otherwise,
293 bool canMatchNodesOfKind(ast_type_traits::ASTNodeKind Kind) const;
295 /// \brief Return a matcher that points to the same implementation, but
296 /// restricts the node types for \p Kind.
297 DynTypedMatcher dynCastTo(const ast_type_traits::ASTNodeKind Kind) const;
299 /// \brief Returns true if the matcher matches the given \c DynNode.
300 bool matches(const ast_type_traits::DynTypedNode &DynNode,
301 ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const;
303 /// \brief Same as matches(), but skips the kind check.
305 /// It is faster, but the caller must ensure the node is valid for the
306 /// kind of this matcher.
307 bool matchesNoKindCheck(const ast_type_traits::DynTypedNode &DynNode,
308 ASTMatchFinder *Finder,
309 BoundNodesTreeBuilder *Builder) const;
311 /// \brief Bind the specified \p ID to the matcher.
312 /// \return A new matcher with the \p ID bound to it if this matcher supports
313 /// binding. Otherwise, returns an empty \c Optional<>.
314 llvm::Optional<DynTypedMatcher> tryBind(StringRef ID) const;
316 /// \brief Returns a unique \p ID for the matcher.
318 /// Casting a Matcher<T> to Matcher<U> creates a matcher that has the
319 /// same \c Implementation pointer, but different \c RestrictKind. We need to
320 /// include both in the ID to make it unique.
322 /// \c MatcherIDType supports operator< and provides strict weak ordering.
323 typedef std::pair<ast_type_traits::ASTNodeKind, uint64_t> MatcherIDType;
324 MatcherIDType getID() const {
325 /// FIXME: Document the requirements this imposes on matcher
326 /// implementations (no new() implementation_ during a Matches()).
327 return std::make_pair(RestrictKind,
328 reinterpret_cast<uint64_t>(Implementation.get()));
331 /// \brief Returns the type this matcher works on.
333 /// \c matches() will always return false unless the node passed is of this
334 /// or a derived type.
335 ast_type_traits::ASTNodeKind getSupportedKind() const {
336 return SupportedKind;
339 /// \brief Returns \c true if the passed \c DynTypedMatcher can be converted
340 /// to a \c Matcher<T>.
342 /// This method verifies that the underlying matcher in \c Other can process
343 /// nodes of types T.
344 template <typename T> bool canConvertTo() const {
345 return canConvertTo(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
347 bool canConvertTo(ast_type_traits::ASTNodeKind To) const;
349 /// \brief Construct a \c Matcher<T> interface around the dynamic matcher.
351 /// This method asserts that \c canConvertTo() is \c true. Callers
352 /// should call \c canConvertTo() first to make sure that \c this is
353 /// compatible with T.
354 template <typename T> Matcher<T> convertTo() const {
355 assert(canConvertTo<T>());
356 return unconditionalConvertTo<T>();
359 /// \brief Same as \c convertTo(), but does not check that the underlying
360 /// matcher can handle a value of T.
362 /// If it is not compatible, then this matcher will never match anything.
363 template <typename T> Matcher<T> unconditionalConvertTo() const;
366 DynTypedMatcher(ast_type_traits::ASTNodeKind SupportedKind,
367 ast_type_traits::ASTNodeKind RestrictKind,
368 IntrusiveRefCntPtr<DynMatcherInterface> Implementation)
370 SupportedKind(SupportedKind),
371 RestrictKind(RestrictKind),
372 Implementation(std::move(Implementation)) {}
375 ast_type_traits::ASTNodeKind SupportedKind;
376 /// \brief A potentially stricter node kind.
378 /// It allows to perform implicit and dynamic cast of matchers without
379 /// needing to change \c Implementation.
380 ast_type_traits::ASTNodeKind RestrictKind;
381 IntrusiveRefCntPtr<DynMatcherInterface> Implementation;
384 /// \brief Wrapper of a MatcherInterface<T> *that allows copying.
386 /// A Matcher<Base> can be used anywhere a Matcher<Derived> is
387 /// required. This establishes an is-a relationship which is reverse
388 /// to the AST hierarchy. In other words, Matcher<T> is contravariant
389 /// with respect to T. The relationship is built via a type conversion
390 /// operator rather than a type hierarchy to be able to templatize the
391 /// type hierarchy instead of spelling it out.
392 template <typename T>
395 /// \brief Takes ownership of the provided implementation pointer.
396 explicit Matcher(MatcherInterface<T> *Implementation)
397 : Implementation(Implementation) {}
399 /// \brief Implicitly converts \c Other to a Matcher<T>.
401 /// Requires \c T to be derived from \c From.
402 template <typename From>
403 Matcher(const Matcher<From> &Other,
404 typename std::enable_if<std::is_base_of<From, T>::value &&
405 !std::is_same<From, T>::value>::type * = 0)
406 : Implementation(restrictMatcher(Other.Implementation)) {
407 assert(Implementation.getSupportedKind().isSame(
408 ast_type_traits::ASTNodeKind::getFromNodeKind<T>()));
411 /// \brief Implicitly converts \c Matcher<Type> to \c Matcher<QualType>.
413 /// The resulting matcher is not strict, i.e. ignores qualifiers.
414 template <typename TypeT>
415 Matcher(const Matcher<TypeT> &Other,
416 typename std::enable_if<
417 std::is_same<T, QualType>::value &&
418 std::is_same<TypeT, Type>::value>::type* = 0)
419 : Implementation(new TypeToQualType<TypeT>(Other)) {}
421 /// \brief Convert \c this into a \c Matcher<T> by applying dyn_cast<> to the
423 /// \c To must be a base class of \c T.
424 template <typename To>
425 Matcher<To> dynCastTo() const {
426 static_assert(std::is_base_of<To, T>::value, "Invalid dynCast call.");
427 return Matcher<To>(Implementation);
430 /// \brief Forwards the call to the underlying MatcherInterface<T> pointer.
431 bool matches(const T &Node,
432 ASTMatchFinder *Finder,
433 BoundNodesTreeBuilder *Builder) const {
434 return Implementation.matches(ast_type_traits::DynTypedNode::create(Node),
438 /// \brief Returns an ID that uniquely identifies the matcher.
439 DynTypedMatcher::MatcherIDType getID() const {
440 return Implementation.getID();
443 /// \brief Extract the dynamic matcher.
445 /// The returned matcher keeps the same restrictions as \c this and remembers
446 /// that it is meant to support nodes of type \c T.
447 operator DynTypedMatcher() const { return Implementation; }
449 /// \brief Allows the conversion of a \c Matcher<Type> to a \c
450 /// Matcher<QualType>.
452 /// Depending on the constructor argument, the matcher is either strict, i.e.
453 /// does only matches in the absence of qualifiers, or not, i.e. simply
454 /// ignores any qualifiers.
455 template <typename TypeT>
456 class TypeToQualType : public MatcherInterface<QualType> {
458 TypeToQualType(const Matcher<TypeT> &InnerMatcher)
459 : InnerMatcher(InnerMatcher) {}
461 bool matches(const QualType &Node, ASTMatchFinder *Finder,
462 BoundNodesTreeBuilder *Builder) const override {
465 return InnerMatcher.matches(*Node, Finder, Builder);
468 const Matcher<TypeT> InnerMatcher;
472 // For Matcher<T> <=> Matcher<U> conversions.
473 template <typename U> friend class Matcher;
474 // For DynTypedMatcher::unconditionalConvertTo<T>.
475 friend class DynTypedMatcher;
477 static DynTypedMatcher restrictMatcher(const DynTypedMatcher &Other) {
478 return Other.dynCastTo(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
481 explicit Matcher(const DynTypedMatcher &Implementation)
482 : Implementation(restrictMatcher(Implementation)) {
483 assert(this->Implementation.getSupportedKind()
484 .isSame(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()));
487 DynTypedMatcher Implementation;
490 /// \brief A convenient helper for creating a Matcher<T> without specifying
491 /// the template type argument.
492 template <typename T>
493 inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) {
494 return Matcher<T>(Implementation);
497 /// \brief Specialization of the conversion functions for QualType.
499 /// This specialization provides the Matcher<Type>->Matcher<QualType>
500 /// conversion that the static API does.
502 inline Matcher<QualType> DynTypedMatcher::convertTo<QualType>() const {
503 assert(canConvertTo<QualType>());
504 const ast_type_traits::ASTNodeKind SourceKind = getSupportedKind();
505 if (SourceKind.isSame(
506 ast_type_traits::ASTNodeKind::getFromNodeKind<Type>())) {
507 // We support implicit conversion from Matcher<Type> to Matcher<QualType>
508 return unconditionalConvertTo<Type>();
510 return unconditionalConvertTo<QualType>();
513 /// \brief Finds the first node in a range that matches the given matcher.
514 template <typename MatcherT, typename IteratorT>
515 bool matchesFirstInRange(const MatcherT &Matcher, IteratorT Start,
516 IteratorT End, ASTMatchFinder *Finder,
517 BoundNodesTreeBuilder *Builder) {
518 for (IteratorT I = Start; I != End; ++I) {
519 BoundNodesTreeBuilder Result(*Builder);
520 if (Matcher.matches(*I, Finder, &Result)) {
521 *Builder = std::move(Result);
528 /// \brief Finds the first node in a pointer range that matches the given
530 template <typename MatcherT, typename IteratorT>
531 bool matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start,
532 IteratorT End, ASTMatchFinder *Finder,
533 BoundNodesTreeBuilder *Builder) {
534 for (IteratorT I = Start; I != End; ++I) {
535 BoundNodesTreeBuilder Result(*Builder);
536 if (Matcher.matches(**I, Finder, &Result)) {
537 *Builder = std::move(Result);
544 /// \brief Metafunction to determine if type T has a member called getDecl.
545 template <typename T> struct has_getDecl {
546 struct Default { int getDecl; };
547 struct Derived : T, Default { };
549 template<typename C, C> struct CheckT;
551 // If T::getDecl exists, an ambiguity arises and CheckT will
552 // not be instantiable. This makes f(...) the only available
555 static char (&f(CheckT<int Default::*, &C::getDecl>*))[1];
556 template<typename C> static char (&f(...))[2];
558 static bool const value = sizeof(f<Derived>(nullptr)) == 2;
561 /// \brief Matches overloaded operators with a specific name.
563 /// The type argument ArgT is not used by this matcher but is used by
564 /// PolymorphicMatcherWithParam1 and should be StringRef.
565 template <typename T, typename ArgT>
566 class HasOverloadedOperatorNameMatcher : public SingleNodeMatcherInterface<T> {
567 static_assert(std::is_same<T, CXXOperatorCallExpr>::value ||
568 std::is_base_of<FunctionDecl, T>::value,
569 "unsupported class for matcher");
570 static_assert(std::is_same<ArgT, StringRef>::value,
571 "argument type must be StringRef");
574 explicit HasOverloadedOperatorNameMatcher(const StringRef Name)
575 : SingleNodeMatcherInterface<T>(), Name(Name) {}
577 bool matchesNode(const T &Node) const override {
578 return matchesSpecialized(Node);
583 /// \brief CXXOperatorCallExpr exist only for calls to overloaded operators
584 /// so this function returns true if the call is to an operator of the given
586 bool matchesSpecialized(const CXXOperatorCallExpr &Node) const {
587 return getOperatorSpelling(Node.getOperator()) == Name;
590 /// \brief Returns true only if CXXMethodDecl represents an overloaded
591 /// operator and has the given operator name.
592 bool matchesSpecialized(const FunctionDecl &Node) const {
593 return Node.isOverloadedOperator() &&
594 getOperatorSpelling(Node.getOverloadedOperator()) == Name;
600 /// \brief Matches named declarations with a specific name.
602 /// See \c hasName() in ASTMatchers.h for details.
603 class HasNameMatcher : public SingleNodeMatcherInterface<NamedDecl> {
605 explicit HasNameMatcher(StringRef Name);
607 bool matchesNode(const NamedDecl &Node) const override;
610 /// \brief Unqualified match routine.
612 /// It is much faster than the full match, but it only works for unqualified
614 bool matchesNodeUnqualified(const NamedDecl &Node) const;
616 /// \brief Full match routine
618 /// It generates the fully qualified name of the declaration (which is
619 /// expensive) before trying to match.
620 /// It is slower but simple and works on all cases.
621 bool matchesNodeFull(const NamedDecl &Node) const;
623 const bool UseUnqualifiedMatch;
624 const std::string Name;
627 /// \brief Matches declarations for QualType and CallExpr.
629 /// Type argument DeclMatcherT is required by PolymorphicMatcherWithParam1 but
630 /// not actually used.
631 template <typename T, typename DeclMatcherT>
632 class HasDeclarationMatcher : public MatcherInterface<T> {
633 static_assert(std::is_same<DeclMatcherT, Matcher<Decl>>::value,
634 "instantiated with wrong types");
637 explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher)
638 : InnerMatcher(InnerMatcher) {}
640 bool matches(const T &Node, ASTMatchFinder *Finder,
641 BoundNodesTreeBuilder *Builder) const override {
642 return matchesSpecialized(Node, Finder, Builder);
646 /// \brief If getDecl exists as a member of U, returns whether the inner
647 /// matcher matches Node.getDecl().
648 template <typename U>
649 bool matchesSpecialized(
650 const U &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder,
651 typename std::enable_if<has_getDecl<U>::value, int>::type = 0) const {
652 return matchesDecl(Node.getDecl(), Finder, Builder);
655 /// \brief Extracts the CXXRecordDecl or EnumDecl of a QualType and returns
656 /// whether the inner matcher matches on it.
657 bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder,
658 BoundNodesTreeBuilder *Builder) const {
659 /// FIXME: Add other ways to convert...
662 if (const EnumType *AsEnum = dyn_cast<EnumType>(Node.getTypePtr()))
663 return matchesDecl(AsEnum->getDecl(), Finder, Builder);
664 return matchesDecl(Node->getAsCXXRecordDecl(), Finder, Builder);
667 /// \brief Gets the TemplateDecl from a TemplateSpecializationType
668 /// and returns whether the inner matches on it.
669 bool matchesSpecialized(const TemplateSpecializationType &Node,
670 ASTMatchFinder *Finder,
671 BoundNodesTreeBuilder *Builder) const {
672 return matchesDecl(Node.getTemplateName().getAsTemplateDecl(),
676 /// \brief Extracts the Decl of the callee of a CallExpr and returns whether
677 /// the inner matcher matches on it.
678 bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder,
679 BoundNodesTreeBuilder *Builder) const {
680 return matchesDecl(Node.getCalleeDecl(), Finder, Builder);
683 /// \brief Extracts the Decl of the constructor call and returns whether the
684 /// inner matcher matches on it.
685 bool matchesSpecialized(const CXXConstructExpr &Node,
686 ASTMatchFinder *Finder,
687 BoundNodesTreeBuilder *Builder) const {
688 return matchesDecl(Node.getConstructor(), Finder, Builder);
691 /// \brief Extracts the \c ValueDecl a \c MemberExpr refers to and returns
692 /// whether the inner matcher matches on it.
693 bool matchesSpecialized(const MemberExpr &Node,
694 ASTMatchFinder *Finder,
695 BoundNodesTreeBuilder *Builder) const {
696 return matchesDecl(Node.getMemberDecl(), Finder, Builder);
699 /// \brief Returns whether the inner matcher \c Node. Returns false if \c Node
701 bool matchesDecl(const Decl *Node,
702 ASTMatchFinder *Finder,
703 BoundNodesTreeBuilder *Builder) const {
704 return Node != nullptr && InnerMatcher.matches(*Node, Finder, Builder);
707 const Matcher<Decl> InnerMatcher;
710 /// \brief IsBaseType<T>::value is true if T is a "base" type in the AST
711 /// node class hierarchies.
712 template <typename T>
714 static const bool value =
715 std::is_same<T, Decl>::value ||
716 std::is_same<T, Stmt>::value ||
717 std::is_same<T, QualType>::value ||
718 std::is_same<T, Type>::value ||
719 std::is_same<T, TypeLoc>::value ||
720 std::is_same<T, NestedNameSpecifier>::value ||
721 std::is_same<T, NestedNameSpecifierLoc>::value ||
722 std::is_same<T, CXXCtorInitializer>::value;
724 template <typename T>
725 const bool IsBaseType<T>::value;
727 /// \brief Interface that allows matchers to traverse the AST.
728 /// FIXME: Find a better name.
730 /// This provides three entry methods for each base node type in the AST:
731 /// - \c matchesChildOf:
732 /// Matches a matcher on every child node of the given node. Returns true
733 /// if at least one child node could be matched.
734 /// - \c matchesDescendantOf:
735 /// Matches a matcher on all descendant nodes of the given node. Returns true
736 /// if at least one descendant matched.
737 /// - \c matchesAncestorOf:
738 /// Matches a matcher on all ancestors of the given node. Returns true if
739 /// at least one ancestor matched.
741 /// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal.
742 /// In the future, we wan to implement this for all nodes for which it makes
743 /// sense. In the case of matchesAncestorOf, we'll want to implement it for
744 /// all nodes, as all nodes have ancestors.
745 class ASTMatchFinder {
747 /// \brief Defines how we descend a level in the AST when we pass
748 /// through expressions.
750 /// Will traverse any child nodes.
752 /// Will not traverse implicit casts and parentheses.
753 TK_IgnoreImplicitCastsAndParentheses
756 /// \brief Defines how bindings are processed on recursive matches.
758 /// Stop at the first match and only bind the first match.
760 /// Create results for all combinations of bindings that match.
764 /// \brief Defines which ancestors are considered for a match.
765 enum AncestorMatchMode {
768 /// Direct parent only.
772 virtual ~ASTMatchFinder() {}
774 /// \brief Returns true if the given class is directly or indirectly derived
775 /// from a base type matching \c base.
777 /// A class is considered to be also derived from itself.
778 virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
779 const Matcher<NamedDecl> &Base,
780 BoundNodesTreeBuilder *Builder) = 0;
782 template <typename T>
783 bool matchesChildOf(const T &Node,
784 const DynTypedMatcher &Matcher,
785 BoundNodesTreeBuilder *Builder,
786 TraversalKind Traverse,
788 static_assert(std::is_base_of<Decl, T>::value ||
789 std::is_base_of<Stmt, T>::value ||
790 std::is_base_of<NestedNameSpecifier, T>::value ||
791 std::is_base_of<NestedNameSpecifierLoc, T>::value ||
792 std::is_base_of<TypeLoc, T>::value ||
793 std::is_base_of<QualType, T>::value,
794 "unsupported type for recursive matching");
795 return matchesChildOf(ast_type_traits::DynTypedNode::create(Node),
796 Matcher, Builder, Traverse, Bind);
799 template <typename T>
800 bool matchesDescendantOf(const T &Node,
801 const DynTypedMatcher &Matcher,
802 BoundNodesTreeBuilder *Builder,
804 static_assert(std::is_base_of<Decl, T>::value ||
805 std::is_base_of<Stmt, T>::value ||
806 std::is_base_of<NestedNameSpecifier, T>::value ||
807 std::is_base_of<NestedNameSpecifierLoc, T>::value ||
808 std::is_base_of<TypeLoc, T>::value ||
809 std::is_base_of<QualType, T>::value,
810 "unsupported type for recursive matching");
811 return matchesDescendantOf(ast_type_traits::DynTypedNode::create(Node),
812 Matcher, Builder, Bind);
815 // FIXME: Implement support for BindKind.
816 template <typename T>
817 bool matchesAncestorOf(const T &Node,
818 const DynTypedMatcher &Matcher,
819 BoundNodesTreeBuilder *Builder,
820 AncestorMatchMode MatchMode) {
821 static_assert(std::is_base_of<Decl, T>::value ||
822 std::is_base_of<Stmt, T>::value,
823 "only Decl or Stmt allowed for recursive matching");
824 return matchesAncestorOf(ast_type_traits::DynTypedNode::create(Node),
825 Matcher, Builder, MatchMode);
828 virtual ASTContext &getASTContext() const = 0;
831 virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node,
832 const DynTypedMatcher &Matcher,
833 BoundNodesTreeBuilder *Builder,
834 TraversalKind Traverse,
837 virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node,
838 const DynTypedMatcher &Matcher,
839 BoundNodesTreeBuilder *Builder,
842 virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node,
843 const DynTypedMatcher &Matcher,
844 BoundNodesTreeBuilder *Builder,
845 AncestorMatchMode MatchMode) = 0;
848 /// \brief A type-list implementation.
850 /// A list is declared as a tree of type list nodes, where the leafs are the
852 /// However, it is used as a "linked list" of types, by using the ::head and
854 /// Each node supports up to 4 children (instead of just 2) to reduce the
855 /// nesting required by large lists.
856 template <typename T1 = void, typename T2 = void, typename T3 = void,
859 /// \brief Implementation detail. Combined with the specializations below,
860 /// this typedef allows for flattening of nested structures.
861 typedef TypeList<T1, T2, T3, T4> self;
863 /// \brief The first type on the list.
866 /// \brief A sublist with the tail. ie everything but the head.
868 /// This type is used to do recursion. TypeList<>/EmptyTypeList indicates the
870 typedef typename TypeList<T2, T3, T4>::self tail;
873 /// \brief Template specialization to allow nested lists.
875 /// First element is a typelist. Pop its first element.
876 template <typename Sub1, typename Sub2, typename Sub3, typename Sub4,
877 typename T2, typename T3, typename T4>
878 struct TypeList<TypeList<Sub1, Sub2, Sub3, Sub4>, T2, T3,
879 T4> : public TypeList<Sub1,
880 typename TypeList<Sub2, Sub3, Sub4>::self,
881 typename TypeList<T2, T3, T4>::self> {};
883 /// \brief Template specialization to allow nested lists.
885 /// First element is an empty typelist. Skip it.
886 template <typename T2, typename T3, typename T4>
887 struct TypeList<TypeList<>, T2, T3, T4> : public TypeList<T2, T3, T4> {
890 /// \brief The empty type list.
891 typedef TypeList<> EmptyTypeList;
893 /// \brief Helper meta-function to determine if some type \c T is present or
894 /// a parent type in the list.
895 template <typename AnyTypeList, typename T>
896 struct TypeListContainsSuperOf {
897 static const bool value =
898 std::is_base_of<typename AnyTypeList::head, T>::value ||
899 TypeListContainsSuperOf<typename AnyTypeList::tail, T>::value;
901 template <typename T>
902 struct TypeListContainsSuperOf<EmptyTypeList, T> {
903 static const bool value = false;
906 /// \brief A "type list" that contains all types.
908 /// Useful for matchers like \c anything and \c unless.
910 TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc>,
911 TypeList<QualType, Type, TypeLoc, CXXCtorInitializer> > AllNodeBaseTypes;
913 /// \brief Helper meta-function to extract the argument out of a function of
916 /// See AST_POLYMORPHIC_SUPPORTED_TYPES_* for details.
917 template <class T> struct ExtractFunctionArgMeta;
918 template <class T> struct ExtractFunctionArgMeta<void(T)> {
922 /// \brief Default type lists for ArgumentAdaptingMatcher matchers.
923 typedef AllNodeBaseTypes AdaptativeDefaultFromTypes;
924 typedef TypeList<TypeList<Decl, Stmt, NestedNameSpecifier>,
925 TypeList<NestedNameSpecifierLoc, TypeLoc, QualType> >
926 AdaptativeDefaultToTypes;
928 /// \brief All types that are supported by HasDeclarationMatcher above.
929 typedef TypeList<TypeList<CallExpr, CXXConstructExpr, DeclRefExpr, EnumType>,
930 TypeList<InjectedClassNameType, LabelStmt, MemberExpr>,
931 TypeList<QualType, RecordType, TagType>,
932 TypeList<TemplateSpecializationType, TemplateTypeParmType,
933 TypedefType, UnresolvedUsingType> >
934 HasDeclarationSupportedTypes;
936 /// \brief Converts a \c Matcher<T> to a matcher of desired type \c To by
937 /// "adapting" a \c To into a \c T.
939 /// The \c ArgumentAdapterT argument specifies how the adaptation is done.
942 /// \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher);
943 /// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher
944 /// that is convertible into any matcher of type \c To by constructing
945 /// \c HasMatcher<To, T>(InnerMatcher).
947 /// If a matcher does not need knowledge about the inner type, prefer to use
948 /// PolymorphicMatcherWithParam1.
949 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
950 typename FromTypes = AdaptativeDefaultFromTypes,
951 typename ToTypes = AdaptativeDefaultToTypes>
952 struct ArgumentAdaptingMatcherFunc {
953 template <typename T> class Adaptor {
955 explicit Adaptor(const Matcher<T> &InnerMatcher)
956 : InnerMatcher(InnerMatcher) {}
958 typedef ToTypes ReturnTypes;
960 template <typename To> operator Matcher<To>() const {
961 return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher));
965 const Matcher<T> InnerMatcher;
968 template <typename T>
969 static Adaptor<T> create(const Matcher<T> &InnerMatcher) {
970 return Adaptor<T>(InnerMatcher);
973 template <typename T>
974 Adaptor<T> operator()(const Matcher<T> &InnerMatcher) const {
975 return create(InnerMatcher);
979 /// \brief A PolymorphicMatcherWithParamN<MatcherT, P1, ..., PN> object can be
980 /// created from N parameters p1, ..., pN (of type P1, ..., PN) and
981 /// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN)
982 /// can be constructed.
985 /// - PolymorphicMatcherWithParam0<IsDefinitionMatcher>()
986 /// creates an object that can be used as a Matcher<T> for any type T
987 /// where an IsDefinitionMatcher<T>() can be constructed.
988 /// - PolymorphicMatcherWithParam1<ValueEqualsMatcher, int>(42)
989 /// creates an object that can be used as a Matcher<T> for any type T
990 /// where a ValueEqualsMatcher<T, int>(42) can be constructed.
991 template <template <typename T> class MatcherT,
992 typename ReturnTypesF = void(AllNodeBaseTypes)>
993 class PolymorphicMatcherWithParam0 {
995 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
996 template <typename T>
997 operator Matcher<T>() const {
998 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
999 "right polymorphic conversion");
1000 return Matcher<T>(new MatcherT<T>());
1004 template <template <typename T, typename P1> class MatcherT,
1006 typename ReturnTypesF = void(AllNodeBaseTypes)>
1007 class PolymorphicMatcherWithParam1 {
1009 explicit PolymorphicMatcherWithParam1(const P1 &Param1)
1012 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
1014 template <typename T>
1015 operator Matcher<T>() const {
1016 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
1017 "right polymorphic conversion");
1018 return Matcher<T>(new MatcherT<T, P1>(Param1));
1025 template <template <typename T, typename P1, typename P2> class MatcherT,
1026 typename P1, typename P2,
1027 typename ReturnTypesF = void(AllNodeBaseTypes)>
1028 class PolymorphicMatcherWithParam2 {
1030 PolymorphicMatcherWithParam2(const P1 &Param1, const P2 &Param2)
1031 : Param1(Param1), Param2(Param2) {}
1033 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
1035 template <typename T>
1036 operator Matcher<T>() const {
1037 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
1038 "right polymorphic conversion");
1039 return Matcher<T>(new MatcherT<T, P1, P2>(Param1, Param2));
1047 /// \brief Matches any instance of the given NodeType.
1049 /// This is useful when a matcher syntactically requires a child matcher,
1050 /// but the context doesn't care. See for example: anything().
1053 typedef AllNodeBaseTypes ReturnTypes;
1055 template <typename T>
1056 operator Matcher<T>() const {
1057 return DynTypedMatcher::trueMatcher(
1058 ast_type_traits::ASTNodeKind::getFromNodeKind<T>())
1059 .template unconditionalConvertTo<T>();
1063 /// \brief A Matcher that allows binding the node it matches to an id.
1065 /// BindableMatcher provides a \a bind() method that allows binding the
1066 /// matched node to an id if the match was successful.
1067 template <typename T>
1068 class BindableMatcher : public Matcher<T> {
1070 explicit BindableMatcher(const Matcher<T> &M) : Matcher<T>(M) {}
1071 explicit BindableMatcher(MatcherInterface<T> *Implementation)
1072 : Matcher<T>(Implementation) {}
1074 /// \brief Returns a matcher that will bind the matched node on a match.
1076 /// The returned matcher is equivalent to this matcher, but will
1077 /// bind the matched node on a match.
1078 Matcher<T> bind(StringRef ID) const {
1079 return DynTypedMatcher(*this)
1081 ->template unconditionalConvertTo<T>();
1084 /// \brief Same as Matcher<T>'s conversion operator, but enables binding on
1085 /// the returned matcher.
1086 operator DynTypedMatcher() const {
1087 DynTypedMatcher Result = static_cast<const Matcher<T>&>(*this);
1088 Result.setAllowBind(true);
1093 /// \brief Matches nodes of type T that have child nodes of type ChildT for
1094 /// which a specified child matcher matches.
1096 /// ChildT must be an AST base type.
1097 template <typename T, typename ChildT>
1098 class HasMatcher : public MatcherInterface<T> {
1099 static_assert(IsBaseType<ChildT>::value,
1100 "has only accepts base type matcher");
1103 explicit HasMatcher(const Matcher<ChildT> &ChildMatcher)
1104 : ChildMatcher(ChildMatcher) {}
1106 bool matches(const T &Node, ASTMatchFinder *Finder,
1107 BoundNodesTreeBuilder *Builder) const override {
1108 return Finder->matchesChildOf(
1109 Node, ChildMatcher, Builder,
1110 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
1111 ASTMatchFinder::BK_First);
1115 const Matcher<ChildT> ChildMatcher;
1118 /// \brief Matches nodes of type T that have child nodes of type ChildT for
1119 /// which a specified child matcher matches. ChildT must be an AST base
1121 /// As opposed to the HasMatcher, the ForEachMatcher will produce a match
1122 /// for each child that matches.
1123 template <typename T, typename ChildT>
1124 class ForEachMatcher : public MatcherInterface<T> {
1125 static_assert(IsBaseType<ChildT>::value,
1126 "for each only accepts base type matcher");
1129 explicit ForEachMatcher(const Matcher<ChildT> &ChildMatcher)
1130 : ChildMatcher(ChildMatcher) {}
1132 bool matches(const T& Node, ASTMatchFinder* Finder,
1133 BoundNodesTreeBuilder* Builder) const override {
1134 return Finder->matchesChildOf(
1135 Node, ChildMatcher, Builder,
1136 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
1137 ASTMatchFinder::BK_All);
1141 const Matcher<ChildT> ChildMatcher;
1144 /// \brief VariadicOperatorMatcher related types.
1147 /// \brief "No argument" placeholder to use as template paratemers.
1148 struct VariadicOperatorNoArg {};
1150 /// \brief Polymorphic matcher object that uses a \c
1151 /// DynTypedMatcher::VariadicOperator operator.
1153 /// Input matchers can have any type (including other polymorphic matcher
1154 /// types), and the actual Matcher<T> is generated on demand with an implicit
1155 /// coversion operator.
1156 template <typename P1, typename P2 = VariadicOperatorNoArg,
1157 typename P3 = VariadicOperatorNoArg,
1158 typename P4 = VariadicOperatorNoArg,
1159 typename P5 = VariadicOperatorNoArg,
1160 typename P6 = VariadicOperatorNoArg,
1161 typename P7 = VariadicOperatorNoArg,
1162 typename P8 = VariadicOperatorNoArg,
1163 typename P9 = VariadicOperatorNoArg>
1164 class VariadicOperatorMatcher {
1166 VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op,
1168 const P2 &Param2 = VariadicOperatorNoArg(),
1169 const P3 &Param3 = VariadicOperatorNoArg(),
1170 const P4 &Param4 = VariadicOperatorNoArg(),
1171 const P5 &Param5 = VariadicOperatorNoArg(),
1172 const P6 &Param6 = VariadicOperatorNoArg(),
1173 const P7 &Param7 = VariadicOperatorNoArg(),
1174 const P8 &Param8 = VariadicOperatorNoArg(),
1175 const P9 &Param9 = VariadicOperatorNoArg())
1176 : Op(Op), Param1(Param1), Param2(Param2), Param3(Param3),
1177 Param4(Param4), Param5(Param5), Param6(Param6), Param7(Param7),
1178 Param8(Param8), Param9(Param9) {}
1180 template <typename T> operator Matcher<T>() const {
1181 std::vector<DynTypedMatcher> Matchers;
1182 addMatcher<T>(Param1, Matchers);
1183 addMatcher<T>(Param2, Matchers);
1184 addMatcher<T>(Param3, Matchers);
1185 addMatcher<T>(Param4, Matchers);
1186 addMatcher<T>(Param5, Matchers);
1187 addMatcher<T>(Param6, Matchers);
1188 addMatcher<T>(Param7, Matchers);
1189 addMatcher<T>(Param8, Matchers);
1190 addMatcher<T>(Param9, Matchers);
1191 return DynTypedMatcher::constructVariadic(Op, std::move(Matchers))
1192 .template unconditionalConvertTo<T>();
1196 template <typename T>
1197 static void addMatcher(const Matcher<T> &M,
1198 std::vector<DynTypedMatcher> &Matchers) {
1199 Matchers.push_back(M);
1202 /// \brief Overload to ignore \c VariadicOperatorNoArg arguments.
1203 template <typename T>
1204 static void addMatcher(VariadicOperatorNoArg,
1205 std::vector<DynTypedMatcher> &Matchers) {}
1207 const DynTypedMatcher::VariadicOperator Op;
1219 /// \brief Overloaded function object to generate VariadicOperatorMatcher
1220 /// objects from arbitrary matchers.
1222 /// It supports 1-9 argument overloaded operator(). More can be added if needed.
1223 template <unsigned MinCount, unsigned MaxCount>
1224 struct VariadicOperatorMatcherFunc {
1225 DynTypedMatcher::VariadicOperator Op;
1227 template <unsigned Count, typename T>
1228 struct EnableIfValidArity
1229 : public std::enable_if<MinCount <= Count && Count <= MaxCount, T> {};
1231 template <typename M1>
1232 typename EnableIfValidArity<1, VariadicOperatorMatcher<M1> >::type
1233 operator()(const M1 &P1) const {
1234 return VariadicOperatorMatcher<M1>(Op, P1);
1236 template <typename M1, typename M2>
1237 typename EnableIfValidArity<2, VariadicOperatorMatcher<M1, M2> >::type
1238 operator()(const M1 &P1, const M2 &P2) const {
1239 return VariadicOperatorMatcher<M1, M2>(Op, P1, P2);
1241 template <typename M1, typename M2, typename M3>
1242 typename EnableIfValidArity<3, VariadicOperatorMatcher<M1, M2, M3> >::type
1243 operator()(const M1 &P1, const M2 &P2, const M3 &P3) const {
1244 return VariadicOperatorMatcher<M1, M2, M3>(Op, P1, P2, P3);
1246 template <typename M1, typename M2, typename M3, typename M4>
1247 typename EnableIfValidArity<4, VariadicOperatorMatcher<M1, M2, M3, M4> >::type
1248 operator()(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4) const {
1249 return VariadicOperatorMatcher<M1, M2, M3, M4>(Op, P1, P2, P3, P4);
1251 template <typename M1, typename M2, typename M3, typename M4, typename M5>
1252 typename EnableIfValidArity<
1253 5, VariadicOperatorMatcher<M1, M2, M3, M4, M5> >::type
1254 operator()(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4,
1255 const M5 &P5) const {
1256 return VariadicOperatorMatcher<M1, M2, M3, M4, M5>(Op, P1, P2, P3, P4, P5);
1258 template <typename M1, typename M2, typename M3, typename M4, typename M5,
1260 typename EnableIfValidArity<
1261 6, VariadicOperatorMatcher<M1, M2, M3, M4, M5, M6> >::type
1262 operator()(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4,
1263 const M5 &P5, const M6 &P6) const {
1264 return VariadicOperatorMatcher<M1, M2, M3, M4, M5, M6>(
1265 Op, P1, P2, P3, P4, P5, P6);
1267 template <typename M1, typename M2, typename M3, typename M4, typename M5,
1268 typename M6, typename M7>
1269 typename EnableIfValidArity<
1270 7, VariadicOperatorMatcher<M1, M2, M3, M4, M5, M6, M7> >::type
1271 operator()(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4,
1272 const M5 &P5, const M6 &P6, const M7 &P7) const {
1273 return VariadicOperatorMatcher<M1, M2, M3, M4, M5, M6, M7>(
1274 Op, P1, P2, P3, P4, P5, P6, P7);
1276 template <typename M1, typename M2, typename M3, typename M4, typename M5,
1277 typename M6, typename M7, typename M8>
1278 typename EnableIfValidArity<
1279 8, VariadicOperatorMatcher<M1, M2, M3, M4, M5, M6, M7, M8> >::type
1280 operator()(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4,
1281 const M5 &P5, const M6 &P6, const M7 &P7, const M8 &P8) const {
1282 return VariadicOperatorMatcher<M1, M2, M3, M4, M5, M6, M7, M8>(
1283 Op, P1, P2, P3, P4, P5, P6, P7, P8);
1285 template <typename M1, typename M2, typename M3, typename M4, typename M5,
1286 typename M6, typename M7, typename M8, typename M9>
1287 typename EnableIfValidArity<
1288 9, VariadicOperatorMatcher<M1, M2, M3, M4, M5, M6, M7, M8, M9> >::type
1289 operator()(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4,
1290 const M5 &P5, const M6 &P6, const M7 &P7, const M8 &P8,
1291 const M9 &P9) const {
1292 return VariadicOperatorMatcher<M1, M2, M3, M4, M5, M6, M7, M8, M9>(
1293 Op, P1, P2, P3, P4, P5, P6, P7, P8, P9);
1299 template <typename T>
1300 inline Matcher<T> DynTypedMatcher::unconditionalConvertTo() const {
1301 return Matcher<T>(*this);
1304 /// \brief Creates a Matcher<T> that matches if all inner matchers match.
1305 template<typename T>
1306 BindableMatcher<T> makeAllOfComposite(
1307 ArrayRef<const Matcher<T> *> InnerMatchers) {
1308 // For the size() == 0 case, we return a "true" matcher.
1309 if (InnerMatchers.size() == 0) {
1310 return BindableMatcher<T>(TrueMatcher());
1312 // For the size() == 1 case, we simply return that one matcher.
1313 // No need to wrap it in a variadic operation.
1314 if (InnerMatchers.size() == 1) {
1315 return BindableMatcher<T>(*InnerMatchers[0]);
1318 std::vector<DynTypedMatcher> DynMatchers;
1319 DynMatchers.reserve(InnerMatchers.size());
1320 for (const auto *InnerMatcher : InnerMatchers) {
1321 DynMatchers.push_back(*InnerMatcher);
1323 return BindableMatcher<T>(
1324 DynTypedMatcher::constructVariadic(DynTypedMatcher::VO_AllOf,
1325 std::move(DynMatchers))
1326 .template unconditionalConvertTo<T>());
1329 /// \brief Creates a Matcher<T> that matches if
1330 /// T is dyn_cast'able into InnerT and all inner matchers match.
1332 /// Returns BindableMatcher, as matchers that use dyn_cast have
1333 /// the same object both to match on and to run submatchers on,
1334 /// so there is no ambiguity with what gets bound.
1335 template<typename T, typename InnerT>
1336 BindableMatcher<T> makeDynCastAllOfComposite(
1337 ArrayRef<const Matcher<InnerT> *> InnerMatchers) {
1338 return BindableMatcher<T>(
1339 makeAllOfComposite(InnerMatchers).template dynCastTo<T>());
1342 /// \brief Matches nodes of type T that have at least one descendant node of
1343 /// type DescendantT for which the given inner matcher matches.
1345 /// DescendantT must be an AST base type.
1346 template <typename T, typename DescendantT>
1347 class HasDescendantMatcher : public MatcherInterface<T> {
1348 static_assert(IsBaseType<DescendantT>::value,
1349 "has descendant only accepts base type matcher");
1352 explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher)
1353 : DescendantMatcher(DescendantMatcher) {}
1355 bool matches(const T &Node, ASTMatchFinder *Finder,
1356 BoundNodesTreeBuilder *Builder) const override {
1357 return Finder->matchesDescendantOf(
1358 Node, DescendantMatcher, Builder, ASTMatchFinder::BK_First);
1362 const Matcher<DescendantT> DescendantMatcher;
1365 /// \brief Matches nodes of type \c T that have a parent node of type \c ParentT
1366 /// for which the given inner matcher matches.
1368 /// \c ParentT must be an AST base type.
1369 template <typename T, typename ParentT>
1370 class HasParentMatcher : public MatcherInterface<T> {
1371 static_assert(IsBaseType<ParentT>::value,
1372 "has parent only accepts base type matcher");
1375 explicit HasParentMatcher(const Matcher<ParentT> &ParentMatcher)
1376 : ParentMatcher(ParentMatcher) {}
1378 bool matches(const T &Node, ASTMatchFinder *Finder,
1379 BoundNodesTreeBuilder *Builder) const override {
1380 return Finder->matchesAncestorOf(
1381 Node, ParentMatcher, Builder, ASTMatchFinder::AMM_ParentOnly);
1385 const Matcher<ParentT> ParentMatcher;
1388 /// \brief Matches nodes of type \c T that have at least one ancestor node of
1389 /// type \c AncestorT for which the given inner matcher matches.
1391 /// \c AncestorT must be an AST base type.
1392 template <typename T, typename AncestorT>
1393 class HasAncestorMatcher : public MatcherInterface<T> {
1394 static_assert(IsBaseType<AncestorT>::value,
1395 "has ancestor only accepts base type matcher");
1398 explicit HasAncestorMatcher(const Matcher<AncestorT> &AncestorMatcher)
1399 : AncestorMatcher(AncestorMatcher) {}
1401 bool matches(const T &Node, ASTMatchFinder *Finder,
1402 BoundNodesTreeBuilder *Builder) const override {
1403 return Finder->matchesAncestorOf(
1404 Node, AncestorMatcher, Builder, ASTMatchFinder::AMM_All);
1408 const Matcher<AncestorT> AncestorMatcher;
1411 /// \brief Matches nodes of type T that have at least one descendant node of
1412 /// type DescendantT for which the given inner matcher matches.
1414 /// DescendantT must be an AST base type.
1415 /// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match
1416 /// for each descendant node that matches instead of only for the first.
1417 template <typename T, typename DescendantT>
1418 class ForEachDescendantMatcher : public MatcherInterface<T> {
1419 static_assert(IsBaseType<DescendantT>::value,
1420 "for each descendant only accepts base type matcher");
1423 explicit ForEachDescendantMatcher(
1424 const Matcher<DescendantT>& DescendantMatcher)
1425 : DescendantMatcher(DescendantMatcher) {}
1427 bool matches(const T& Node, ASTMatchFinder* Finder,
1428 BoundNodesTreeBuilder* Builder) const override {
1429 return Finder->matchesDescendantOf(Node, DescendantMatcher, Builder,
1430 ASTMatchFinder::BK_All);
1434 const Matcher<DescendantT> DescendantMatcher;
1437 /// \brief Matches on nodes that have a getValue() method if getValue() equals
1438 /// the value the ValueEqualsMatcher was constructed with.
1439 template <typename T, typename ValueT>
1440 class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> {
1441 static_assert(std::is_base_of<CharacterLiteral, T>::value ||
1442 std::is_base_of<CXXBoolLiteralExpr, T>::value ||
1443 std::is_base_of<FloatingLiteral, T>::value ||
1444 std::is_base_of<IntegerLiteral, T>::value,
1445 "the node must have a getValue method");
1448 explicit ValueEqualsMatcher(const ValueT &ExpectedValue)
1449 : ExpectedValue(ExpectedValue) {}
1451 bool matchesNode(const T &Node) const override {
1452 return Node.getValue() == ExpectedValue;
1456 const ValueT ExpectedValue;
1459 /// \brief A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a
1460 /// variadic functor that takes a number of Matcher<TargetT> and returns a
1461 /// Matcher<SourceT> that matches TargetT nodes that are matched by all of the
1462 /// given matchers, if SourceT can be dynamically casted into TargetT.
1465 /// const VariadicDynCastAllOfMatcher<
1466 /// Decl, CXXRecordDecl> record;
1467 /// Creates a functor record(...) that creates a Matcher<Decl> given
1468 /// a variable number of arguments of type Matcher<CXXRecordDecl>.
1469 /// The returned matcher matches if the given Decl can by dynamically
1470 /// casted to CXXRecordDecl and all given matchers match.
1471 template <typename SourceT, typename TargetT>
1472 class VariadicDynCastAllOfMatcher
1473 : public llvm::VariadicFunction<
1474 BindableMatcher<SourceT>, Matcher<TargetT>,
1475 makeDynCastAllOfComposite<SourceT, TargetT> > {
1477 VariadicDynCastAllOfMatcher() {}
1480 /// \brief A \c VariadicAllOfMatcher<T> object is a variadic functor that takes
1481 /// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T
1482 /// nodes that are matched by all of the given matchers.
1485 /// const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
1486 /// Creates a functor nestedNameSpecifier(...) that creates a
1487 /// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type
1488 /// \c Matcher<NestedNameSpecifier>.
1489 /// The returned matcher matches if all given matchers match.
1490 template <typename T>
1491 class VariadicAllOfMatcher : public llvm::VariadicFunction<
1492 BindableMatcher<T>, Matcher<T>,
1493 makeAllOfComposite<T> > {
1495 VariadicAllOfMatcher() {}
1498 /// \brief Matches nodes of type \c TLoc for which the inner
1499 /// \c Matcher<T> matches.
1500 template <typename TLoc, typename T>
1501 class LocMatcher : public MatcherInterface<TLoc> {
1503 explicit LocMatcher(const Matcher<T> &InnerMatcher)
1504 : InnerMatcher(InnerMatcher) {}
1506 bool matches(const TLoc &Node, ASTMatchFinder *Finder,
1507 BoundNodesTreeBuilder *Builder) const override {
1510 return InnerMatcher.matches(*extract(Node), Finder, Builder);
1514 const NestedNameSpecifier *extract(const NestedNameSpecifierLoc &Loc) const {
1515 return Loc.getNestedNameSpecifier();
1518 const Matcher<T> InnerMatcher;
1521 /// \brief Matches \c TypeLocs based on an inner matcher matching a certain
1524 /// Used to implement the \c loc() matcher.
1525 class TypeLocTypeMatcher : public MatcherInterface<TypeLoc> {
1527 explicit TypeLocTypeMatcher(const Matcher<QualType> &InnerMatcher)
1528 : InnerMatcher(InnerMatcher) {}
1530 bool matches(const TypeLoc &Node, ASTMatchFinder *Finder,
1531 BoundNodesTreeBuilder *Builder) const override {
1534 return InnerMatcher.matches(Node.getType(), Finder, Builder);
1538 const Matcher<QualType> InnerMatcher;
1541 /// \brief Matches nodes of type \c T for which the inner matcher matches on a
1542 /// another node of type \c T that can be reached using a given traverse
1544 template <typename T>
1545 class TypeTraverseMatcher : public MatcherInterface<T> {
1547 explicit TypeTraverseMatcher(const Matcher<QualType> &InnerMatcher,
1548 QualType (T::*TraverseFunction)() const)
1549 : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {}
1551 bool matches(const T &Node, ASTMatchFinder *Finder,
1552 BoundNodesTreeBuilder *Builder) const override {
1553 QualType NextNode = (Node.*TraverseFunction)();
1554 if (NextNode.isNull())
1556 return InnerMatcher.matches(NextNode, Finder, Builder);
1560 const Matcher<QualType> InnerMatcher;
1561 QualType (T::*TraverseFunction)() const;
1564 /// \brief Matches nodes of type \c T in a ..Loc hierarchy, for which the inner
1565 /// matcher matches on a another node of type \c T that can be reached using a
1566 /// given traverse function.
1567 template <typename T>
1568 class TypeLocTraverseMatcher : public MatcherInterface<T> {
1570 explicit TypeLocTraverseMatcher(const Matcher<TypeLoc> &InnerMatcher,
1571 TypeLoc (T::*TraverseFunction)() const)
1572 : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {}
1574 bool matches(const T &Node, ASTMatchFinder *Finder,
1575 BoundNodesTreeBuilder *Builder) const override {
1576 TypeLoc NextNode = (Node.*TraverseFunction)();
1579 return InnerMatcher.matches(NextNode, Finder, Builder);
1583 const Matcher<TypeLoc> InnerMatcher;
1584 TypeLoc (T::*TraverseFunction)() const;
1587 /// \brief Converts a \c Matcher<InnerT> to a \c Matcher<OuterT>, where
1588 /// \c OuterT is any type that is supported by \c Getter.
1590 /// \code Getter<OuterT>::value() \endcode returns a
1591 /// \code InnerTBase (OuterT::*)() \endcode, which is used to adapt a \c OuterT
1592 /// object into a \c InnerT
1593 template <typename InnerTBase,
1594 template <typename OuterT> class Getter,
1595 template <typename OuterT> class MatcherImpl,
1596 typename ReturnTypesF>
1597 class TypeTraversePolymorphicMatcher {
1599 typedef TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl,
1601 static Self create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers);
1604 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
1606 explicit TypeTraversePolymorphicMatcher(
1607 ArrayRef<const Matcher<InnerTBase> *> InnerMatchers)
1608 : InnerMatcher(makeAllOfComposite(InnerMatchers)) {}
1610 template <typename OuterT> operator Matcher<OuterT>() const {
1611 return Matcher<OuterT>(
1612 new MatcherImpl<OuterT>(InnerMatcher, Getter<OuterT>::value()));
1615 struct Func : public llvm::VariadicFunction<Self, Matcher<InnerTBase>,
1621 const Matcher<InnerTBase> InnerMatcher;
1624 /// \brief A simple memoizer of T(*)() functions.
1626 /// It will call the passed 'Func' template parameter at most once.
1627 /// Used to support AST_MATCHER_FUNCTION() macro.
1628 template <typename Matcher, Matcher (*Func)()> class MemoizedMatcher {
1630 Wrapper() : M(Func()) {}
1635 static const Matcher &getInstance() {
1636 static llvm::ManagedStatic<Wrapper> Instance;
1641 // Define the create() method out of line to silence a GCC warning about
1642 // the struct "Func" having greater visibility than its base, which comes from
1643 // using the flag -fvisibility-inlines-hidden.
1644 template <typename InnerTBase, template <typename OuterT> class Getter,
1645 template <typename OuterT> class MatcherImpl, typename ReturnTypesF>
1646 TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl, ReturnTypesF>
1647 TypeTraversePolymorphicMatcher<
1648 InnerTBase, Getter, MatcherImpl,
1649 ReturnTypesF>::create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers) {
1650 return Self(InnerMatchers);
1653 // FIXME: unify ClassTemplateSpecializationDecl and TemplateSpecializationType's
1654 // APIs for accessing the template argument list.
1655 inline ArrayRef<TemplateArgument>
1656 getTemplateSpecializationArgs(const ClassTemplateSpecializationDecl &D) {
1657 return D.getTemplateArgs().asArray();
1660 inline ArrayRef<TemplateArgument>
1661 getTemplateSpecializationArgs(const TemplateSpecializationType &T) {
1662 return llvm::makeArrayRef(T.getArgs(), T.getNumArgs());
1665 struct NotEqualsBoundNodePredicate {
1666 bool operator()(const internal::BoundNodesMap &Nodes) const {
1667 return Nodes.getNode(ID) != Node;
1670 ast_type_traits::DynTypedNode Node;
1673 } // end namespace internal
1674 } // end namespace ast_matchers
1675 } // end namespace clang