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/DeclFriend.h"
42 #include "clang/AST/DeclTemplate.h"
43 #include "clang/AST/Expr.h"
44 #include "clang/AST/ExprObjC.h"
45 #include "clang/AST/ExprCXX.h"
46 #include "clang/AST/ExprObjC.h"
47 #include "clang/AST/NestedNameSpecifier.h"
48 #include "clang/AST/Stmt.h"
49 #include "clang/AST/TemplateName.h"
50 #include "clang/AST/Type.h"
51 #include "clang/AST/TypeLoc.h"
52 #include "clang/Basic/LLVM.h"
53 #include "clang/Basic/OperatorKinds.h"
54 #include "llvm/ADT/APFloat.h"
55 #include "llvm/ADT/ArrayRef.h"
56 #include "llvm/ADT/IntrusiveRefCntPtr.h"
57 #include "llvm/ADT/None.h"
58 #include "llvm/ADT/Optional.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include "llvm/ADT/SmallVector.h"
61 #include "llvm/ADT/StringRef.h"
62 #include "llvm/ADT/iterator.h"
63 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/ManagedStatic.h"
72 #include <type_traits>
80 namespace ast_matchers {
86 /// Variadic function object.
88 /// Most of the functions below that use VariadicFunction could be implemented
89 /// using plain C++11 variadic functions, but the function object allows us to
90 /// capture it on the dynamic matcher registry.
91 template <typename ResultT, typename ArgT,
92 ResultT (*Func)(ArrayRef<const ArgT *>)>
93 struct VariadicFunction {
94 ResultT operator()() const { return Func(None); }
96 template <typename... ArgsT>
97 ResultT operator()(const ArgT &Arg1, const ArgsT &... Args) const {
98 return Execute(Arg1, static_cast<const ArgT &>(Args)...);
101 // We also allow calls with an already created array, in case the caller
103 ResultT operator()(ArrayRef<ArgT> Args) const {
104 SmallVector<const ArgT*, 8> InnerArgs;
105 for (const ArgT &Arg : Args)
106 InnerArgs.push_back(&Arg);
107 return Func(InnerArgs);
111 // Trampoline function to allow for implicit conversions to take place
112 // before we make the array.
113 template <typename... ArgsT> ResultT Execute(const ArgsT &... Args) const {
114 const ArgT *const ArgsArray[] = {&Args...};
115 return Func(ArrayRef<const ArgT *>(ArgsArray, sizeof...(ArgsT)));
119 /// Unifies obtaining the underlying type of a regular node through
120 /// `getType` and a TypedefNameDecl node through `getUnderlyingType`.
121 inline QualType getUnderlyingType(const Expr &Node) { return Node.getType(); }
123 inline QualType getUnderlyingType(const ValueDecl &Node) {
124 return Node.getType();
126 inline QualType getUnderlyingType(const TypedefNameDecl &Node) {
127 return Node.getUnderlyingType();
129 inline QualType getUnderlyingType(const FriendDecl &Node) {
130 if (const TypeSourceInfo *TSI = Node.getFriendType())
131 return TSI->getType();
135 /// Unifies obtaining the FunctionProtoType pointer from both
136 /// FunctionProtoType and FunctionDecl nodes..
137 inline const FunctionProtoType *
138 getFunctionProtoType(const FunctionProtoType &Node) {
142 inline const FunctionProtoType *getFunctionProtoType(const FunctionDecl &Node) {
143 return Node.getType()->getAs<FunctionProtoType>();
146 /// Internal version of BoundNodes. Holds all the bound nodes.
147 class BoundNodesMap {
149 /// Adds \c Node to the map with key \c ID.
151 /// The node's base type should be in NodeBaseType or it will be unaccessible.
152 void addNode(StringRef ID, const ast_type_traits::DynTypedNode& DynNode) {
153 NodeMap[ID] = DynNode;
156 /// Returns the AST node bound to \c ID.
158 /// Returns NULL if there was no node bound to \c ID or if there is a node but
159 /// it cannot be converted to the specified type.
160 template <typename T>
161 const T *getNodeAs(StringRef ID) const {
162 IDToNodeMap::const_iterator It = NodeMap.find(ID);
163 if (It == NodeMap.end()) {
166 return It->second.get<T>();
169 ast_type_traits::DynTypedNode getNode(StringRef ID) const {
170 IDToNodeMap::const_iterator It = NodeMap.find(ID);
171 if (It == NodeMap.end()) {
172 return ast_type_traits::DynTypedNode();
177 /// Imposes an order on BoundNodesMaps.
178 bool operator<(const BoundNodesMap &Other) const {
179 return NodeMap < Other.NodeMap;
182 /// A map from IDs to the bound nodes.
184 /// Note that we're using std::map here, as for memoization:
185 /// - we need a comparison operator
186 /// - we need an assignment operator
187 using IDToNodeMap = std::map<std::string, ast_type_traits::DynTypedNode>;
189 const IDToNodeMap &getMap() const {
193 /// Returns \c true if this \c BoundNodesMap can be compared, i.e. all
194 /// stored nodes have memoization data.
195 bool isComparable() const {
196 for (const auto &IDAndNode : NodeMap) {
197 if (!IDAndNode.second.getMemoizationData())
207 /// Creates BoundNodesTree objects.
209 /// The tree builder is used during the matching process to insert the bound
210 /// nodes from the Id matcher.
211 class BoundNodesTreeBuilder {
213 /// A visitor interface to visit all BoundNodes results for a
217 virtual ~Visitor() = default;
219 /// Called multiple times during a single call to VisitMatches(...).
221 /// 'BoundNodesView' contains the bound nodes for a single match.
222 virtual void visitMatch(const BoundNodes& BoundNodesView) = 0;
225 /// Add a binding from an id to a node.
226 void setBinding(StringRef Id, const ast_type_traits::DynTypedNode &DynNode) {
227 if (Bindings.empty())
228 Bindings.emplace_back();
229 for (BoundNodesMap &Binding : Bindings)
230 Binding.addNode(Id, DynNode);
233 /// Adds a branch in the tree.
234 void addMatch(const BoundNodesTreeBuilder &Bindings);
236 /// Visits all matches that this BoundNodesTree represents.
238 /// The ownership of 'ResultVisitor' remains at the caller.
239 void visitMatches(Visitor* ResultVisitor);
241 template <typename ExcludePredicate>
242 bool removeBindings(const ExcludePredicate &Predicate) {
243 Bindings.erase(std::remove_if(Bindings.begin(), Bindings.end(), Predicate),
245 return !Bindings.empty();
248 /// Imposes an order on BoundNodesTreeBuilders.
249 bool operator<(const BoundNodesTreeBuilder &Other) const {
250 return Bindings < Other.Bindings;
253 /// Returns \c true if this \c BoundNodesTreeBuilder can be compared,
254 /// i.e. all stored node maps have memoization data.
255 bool isComparable() const {
256 for (const BoundNodesMap &NodesMap : Bindings) {
257 if (!NodesMap.isComparable())
264 SmallVector<BoundNodesMap, 16> Bindings;
267 class ASTMatchFinder;
269 /// Generic interface for all matchers.
271 /// Used by the implementation of Matcher<T> and DynTypedMatcher.
272 /// In general, implement MatcherInterface<T> or SingleNodeMatcherInterface<T>
274 class DynMatcherInterface
275 : public llvm::ThreadSafeRefCountedBase<DynMatcherInterface> {
277 virtual ~DynMatcherInterface() = default;
279 /// Returns true if \p DynNode can be matched.
281 /// May bind \p DynNode to an ID via \p Builder, or recurse into
282 /// the AST via \p Finder.
283 virtual bool dynMatches(const ast_type_traits::DynTypedNode &DynNode,
284 ASTMatchFinder *Finder,
285 BoundNodesTreeBuilder *Builder) const = 0;
288 /// Generic interface for matchers on an AST node of type T.
290 /// Implement this if your matcher may need to inspect the children or
291 /// descendants of the node or bind matched nodes to names. If you are
292 /// writing a simple matcher that only inspects properties of the
293 /// current node and doesn't care about its children or descendants,
294 /// implement SingleNodeMatcherInterface instead.
295 template <typename T>
296 class MatcherInterface : public DynMatcherInterface {
298 /// Returns true if 'Node' can be matched.
300 /// May bind 'Node' to an ID via 'Builder', or recurse into
301 /// the AST via 'Finder'.
302 virtual bool matches(const T &Node,
303 ASTMatchFinder *Finder,
304 BoundNodesTreeBuilder *Builder) const = 0;
306 bool dynMatches(const ast_type_traits::DynTypedNode &DynNode,
307 ASTMatchFinder *Finder,
308 BoundNodesTreeBuilder *Builder) const override {
309 return matches(DynNode.getUnchecked<T>(), Finder, Builder);
313 /// Interface for matchers that only evaluate properties on a single
315 template <typename T>
316 class SingleNodeMatcherInterface : public MatcherInterface<T> {
318 /// Returns true if the matcher matches the provided node.
320 /// A subclass must implement this instead of Matches().
321 virtual bool matchesNode(const T &Node) const = 0;
324 /// Implements MatcherInterface::Matches.
325 bool matches(const T &Node,
326 ASTMatchFinder * /* Finder */,
327 BoundNodesTreeBuilder * /* Builder */) const override {
328 return matchesNode(Node);
332 template <typename> class Matcher;
334 /// Matcher that works on a \c DynTypedNode.
336 /// It is constructed from a \c Matcher<T> object and redirects most calls to
337 /// underlying matcher.
338 /// It checks whether the \c DynTypedNode is convertible into the type of the
339 /// underlying matcher and then do the actual match on the actual node, or
340 /// return false if it is not convertible.
341 class DynTypedMatcher {
343 /// Takes ownership of the provided implementation pointer.
344 template <typename T>
345 DynTypedMatcher(MatcherInterface<T> *Implementation)
346 : SupportedKind(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()),
347 RestrictKind(SupportedKind), Implementation(Implementation) {}
349 /// Construct from a variadic function.
350 enum VariadicOperator {
351 /// Matches nodes for which all provided matchers match.
354 /// Matches nodes for which at least one of the provided matchers
358 /// Matches nodes for which at least one of the provided matchers
359 /// matches, but doesn't stop at the first match.
362 /// Matches nodes that do not match the provided matcher.
364 /// Uses the variadic matcher interface, but fails if
365 /// InnerMatchers.size() != 1.
369 static DynTypedMatcher
370 constructVariadic(VariadicOperator Op,
371 ast_type_traits::ASTNodeKind SupportedKind,
372 std::vector<DynTypedMatcher> InnerMatchers);
374 /// Get a "true" matcher for \p NodeKind.
376 /// It only checks that the node is of the right kind.
377 static DynTypedMatcher trueMatcher(ast_type_traits::ASTNodeKind NodeKind);
379 void setAllowBind(bool AB) { AllowBind = AB; }
381 /// Check whether this matcher could ever match a node of kind \p Kind.
382 /// \return \c false if this matcher will never match such a node. Otherwise,
384 bool canMatchNodesOfKind(ast_type_traits::ASTNodeKind Kind) const;
386 /// Return a matcher that points to the same implementation, but
387 /// restricts the node types for \p Kind.
388 DynTypedMatcher dynCastTo(const ast_type_traits::ASTNodeKind Kind) const;
390 /// Returns true if the matcher matches the given \c DynNode.
391 bool matches(const ast_type_traits::DynTypedNode &DynNode,
392 ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const;
394 /// Same as matches(), but skips the kind check.
396 /// It is faster, but the caller must ensure the node is valid for the
397 /// kind of this matcher.
398 bool matchesNoKindCheck(const ast_type_traits::DynTypedNode &DynNode,
399 ASTMatchFinder *Finder,
400 BoundNodesTreeBuilder *Builder) const;
402 /// Bind the specified \p ID to the matcher.
403 /// \return A new matcher with the \p ID bound to it if this matcher supports
404 /// binding. Otherwise, returns an empty \c Optional<>.
405 llvm::Optional<DynTypedMatcher> tryBind(StringRef ID) const;
407 /// Returns a unique \p ID for the matcher.
409 /// Casting a Matcher<T> to Matcher<U> creates a matcher that has the
410 /// same \c Implementation pointer, but different \c RestrictKind. We need to
411 /// include both in the ID to make it unique.
413 /// \c MatcherIDType supports operator< and provides strict weak ordering.
414 using MatcherIDType = std::pair<ast_type_traits::ASTNodeKind, uint64_t>;
415 MatcherIDType getID() const {
416 /// FIXME: Document the requirements this imposes on matcher
417 /// implementations (no new() implementation_ during a Matches()).
418 return std::make_pair(RestrictKind,
419 reinterpret_cast<uint64_t>(Implementation.get()));
422 /// Returns the type this matcher works on.
424 /// \c matches() will always return false unless the node passed is of this
425 /// or a derived type.
426 ast_type_traits::ASTNodeKind getSupportedKind() const {
427 return SupportedKind;
430 /// Returns \c true if the passed \c DynTypedMatcher can be converted
431 /// to a \c Matcher<T>.
433 /// This method verifies that the underlying matcher in \c Other can process
434 /// nodes of types T.
435 template <typename T> bool canConvertTo() const {
436 return canConvertTo(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
438 bool canConvertTo(ast_type_traits::ASTNodeKind To) const;
440 /// Construct a \c Matcher<T> interface around the dynamic matcher.
442 /// This method asserts that \c canConvertTo() is \c true. Callers
443 /// should call \c canConvertTo() first to make sure that \c this is
444 /// compatible with T.
445 template <typename T> Matcher<T> convertTo() const {
446 assert(canConvertTo<T>());
447 return unconditionalConvertTo<T>();
450 /// Same as \c convertTo(), but does not check that the underlying
451 /// matcher can handle a value of T.
453 /// If it is not compatible, then this matcher will never match anything.
454 template <typename T> Matcher<T> unconditionalConvertTo() const;
457 DynTypedMatcher(ast_type_traits::ASTNodeKind SupportedKind,
458 ast_type_traits::ASTNodeKind RestrictKind,
459 IntrusiveRefCntPtr<DynMatcherInterface> Implementation)
460 : SupportedKind(SupportedKind), RestrictKind(RestrictKind),
461 Implementation(std::move(Implementation)) {}
463 bool AllowBind = false;
464 ast_type_traits::ASTNodeKind SupportedKind;
466 /// A potentially stricter node kind.
468 /// It allows to perform implicit and dynamic cast of matchers without
469 /// needing to change \c Implementation.
470 ast_type_traits::ASTNodeKind RestrictKind;
471 IntrusiveRefCntPtr<DynMatcherInterface> Implementation;
474 /// Wrapper base class for a wrapping matcher.
476 /// This is just a container for a DynTypedMatcher that can be used as a base
477 /// class for another matcher.
478 template <typename T>
479 class WrapperMatcherInterface : public MatcherInterface<T> {
481 explicit WrapperMatcherInterface(DynTypedMatcher &&InnerMatcher)
482 : InnerMatcher(std::move(InnerMatcher)) {}
484 const DynTypedMatcher InnerMatcher;
487 /// Wrapper of a MatcherInterface<T> *that allows copying.
489 /// A Matcher<Base> can be used anywhere a Matcher<Derived> is
490 /// required. This establishes an is-a relationship which is reverse
491 /// to the AST hierarchy. In other words, Matcher<T> is contravariant
492 /// with respect to T. The relationship is built via a type conversion
493 /// operator rather than a type hierarchy to be able to templatize the
494 /// type hierarchy instead of spelling it out.
495 template <typename T>
498 /// Takes ownership of the provided implementation pointer.
499 explicit Matcher(MatcherInterface<T> *Implementation)
500 : Implementation(Implementation) {}
502 /// Implicitly converts \c Other to a Matcher<T>.
504 /// Requires \c T to be derived from \c From.
505 template <typename From>
506 Matcher(const Matcher<From> &Other,
507 typename std::enable_if<std::is_base_of<From, T>::value &&
508 !std::is_same<From, T>::value>::type * = nullptr)
509 : Implementation(restrictMatcher(Other.Implementation)) {
510 assert(Implementation.getSupportedKind().isSame(
511 ast_type_traits::ASTNodeKind::getFromNodeKind<T>()));
514 /// Implicitly converts \c Matcher<Type> to \c Matcher<QualType>.
516 /// The resulting matcher is not strict, i.e. ignores qualifiers.
517 template <typename TypeT>
518 Matcher(const Matcher<TypeT> &Other,
519 typename std::enable_if<
520 std::is_same<T, QualType>::value &&
521 std::is_same<TypeT, Type>::value>::type* = nullptr)
522 : Implementation(new TypeToQualType<TypeT>(Other)) {}
524 /// Convert \c this into a \c Matcher<T> by applying dyn_cast<> to the
526 /// \c To must be a base class of \c T.
527 template <typename To>
528 Matcher<To> dynCastTo() const {
529 static_assert(std::is_base_of<To, T>::value, "Invalid dynCast call.");
530 return Matcher<To>(Implementation);
533 /// Forwards the call to the underlying MatcherInterface<T> pointer.
534 bool matches(const T &Node,
535 ASTMatchFinder *Finder,
536 BoundNodesTreeBuilder *Builder) const {
537 return Implementation.matches(ast_type_traits::DynTypedNode::create(Node),
541 /// Returns an ID that uniquely identifies the matcher.
542 DynTypedMatcher::MatcherIDType getID() const {
543 return Implementation.getID();
546 /// Extract the dynamic matcher.
548 /// The returned matcher keeps the same restrictions as \c this and remembers
549 /// that it is meant to support nodes of type \c T.
550 operator DynTypedMatcher() const { return Implementation; }
552 /// Allows the conversion of a \c Matcher<Type> to a \c
553 /// Matcher<QualType>.
555 /// Depending on the constructor argument, the matcher is either strict, i.e.
556 /// does only matches in the absence of qualifiers, or not, i.e. simply
557 /// ignores any qualifiers.
558 template <typename TypeT>
559 class TypeToQualType : public WrapperMatcherInterface<QualType> {
561 TypeToQualType(const Matcher<TypeT> &InnerMatcher)
562 : TypeToQualType::WrapperMatcherInterface(InnerMatcher) {}
564 bool matches(const QualType &Node, ASTMatchFinder *Finder,
565 BoundNodesTreeBuilder *Builder) const override {
568 return this->InnerMatcher.matches(
569 ast_type_traits::DynTypedNode::create(*Node), Finder, Builder);
574 // For Matcher<T> <=> Matcher<U> conversions.
575 template <typename U> friend class Matcher;
577 // For DynTypedMatcher::unconditionalConvertTo<T>.
578 friend class DynTypedMatcher;
580 static DynTypedMatcher restrictMatcher(const DynTypedMatcher &Other) {
581 return Other.dynCastTo(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
584 explicit Matcher(const DynTypedMatcher &Implementation)
585 : Implementation(restrictMatcher(Implementation)) {
586 assert(this->Implementation.getSupportedKind()
587 .isSame(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()));
590 DynTypedMatcher Implementation;
593 /// A convenient helper for creating a Matcher<T> without specifying
594 /// the template type argument.
595 template <typename T>
596 inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) {
597 return Matcher<T>(Implementation);
600 /// Specialization of the conversion functions for QualType.
602 /// This specialization provides the Matcher<Type>->Matcher<QualType>
603 /// conversion that the static API does.
605 inline Matcher<QualType> DynTypedMatcher::convertTo<QualType>() const {
606 assert(canConvertTo<QualType>());
607 const ast_type_traits::ASTNodeKind SourceKind = getSupportedKind();
608 if (SourceKind.isSame(
609 ast_type_traits::ASTNodeKind::getFromNodeKind<Type>())) {
610 // We support implicit conversion from Matcher<Type> to Matcher<QualType>
611 return unconditionalConvertTo<Type>();
613 return unconditionalConvertTo<QualType>();
616 /// Finds the first node in a range that matches the given matcher.
617 template <typename MatcherT, typename IteratorT>
618 bool matchesFirstInRange(const MatcherT &Matcher, IteratorT Start,
619 IteratorT End, ASTMatchFinder *Finder,
620 BoundNodesTreeBuilder *Builder) {
621 for (IteratorT I = Start; I != End; ++I) {
622 BoundNodesTreeBuilder Result(*Builder);
623 if (Matcher.matches(*I, Finder, &Result)) {
624 *Builder = std::move(Result);
631 /// Finds the first node in a pointer range that matches the given
633 template <typename MatcherT, typename IteratorT>
634 bool matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start,
635 IteratorT End, ASTMatchFinder *Finder,
636 BoundNodesTreeBuilder *Builder) {
637 for (IteratorT I = Start; I != End; ++I) {
638 BoundNodesTreeBuilder Result(*Builder);
639 if (Matcher.matches(**I, Finder, &Result)) {
640 *Builder = std::move(Result);
647 // Metafunction to determine if type T has a member called getDecl.
648 template <typename Ty>
653 template <typename Inner>
654 static yes& test(Inner *I, decltype(I->getDecl()) * = nullptr);
657 static no& test(...);
660 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
663 /// Matches overloaded operators with a specific name.
665 /// The type argument ArgT is not used by this matcher but is used by
666 /// PolymorphicMatcherWithParam1 and should be StringRef.
667 template <typename T, typename ArgT>
668 class HasOverloadedOperatorNameMatcher : public SingleNodeMatcherInterface<T> {
669 static_assert(std::is_same<T, CXXOperatorCallExpr>::value ||
670 std::is_base_of<FunctionDecl, T>::value,
671 "unsupported class for matcher");
672 static_assert(std::is_same<ArgT, StringRef>::value,
673 "argument type must be StringRef");
676 explicit HasOverloadedOperatorNameMatcher(const StringRef Name)
677 : SingleNodeMatcherInterface<T>(), Name(Name) {}
679 bool matchesNode(const T &Node) const override {
680 return matchesSpecialized(Node);
685 /// CXXOperatorCallExpr exist only for calls to overloaded operators
686 /// so this function returns true if the call is to an operator of the given
688 bool matchesSpecialized(const CXXOperatorCallExpr &Node) const {
689 return getOperatorSpelling(Node.getOperator()) == Name;
692 /// Returns true only if CXXMethodDecl represents an overloaded
693 /// operator and has the given operator name.
694 bool matchesSpecialized(const FunctionDecl &Node) const {
695 return Node.isOverloadedOperator() &&
696 getOperatorSpelling(Node.getOverloadedOperator()) == Name;
702 /// Matches named declarations with a specific name.
704 /// See \c hasName() and \c hasAnyName() in ASTMatchers.h for details.
705 class HasNameMatcher : public SingleNodeMatcherInterface<NamedDecl> {
707 explicit HasNameMatcher(std::vector<std::string> Names);
709 bool matchesNode(const NamedDecl &Node) const override;
712 /// Unqualified match routine.
714 /// It is much faster than the full match, but it only works for unqualified
716 bool matchesNodeUnqualified(const NamedDecl &Node) const;
718 /// Full match routine
720 /// Fast implementation for the simple case of a named declaration at
721 /// namespace or RecordDecl scope.
722 /// It is slower than matchesNodeUnqualified, but faster than
723 /// matchesNodeFullSlow.
724 bool matchesNodeFullFast(const NamedDecl &Node) const;
726 /// Full match routine
728 /// It generates the fully qualified name of the declaration (which is
729 /// expensive) before trying to match.
730 /// It is slower but simple and works on all cases.
731 bool matchesNodeFullSlow(const NamedDecl &Node) const;
733 const bool UseUnqualifiedMatch;
734 const std::vector<std::string> Names;
737 /// Trampoline function to use VariadicFunction<> to construct a
739 Matcher<NamedDecl> hasAnyNameFunc(ArrayRef<const StringRef *> NameRefs);
741 /// Trampoline function to use VariadicFunction<> to construct a
742 /// hasAnySelector matcher.
743 Matcher<ObjCMessageExpr> hasAnySelectorFunc(
744 ArrayRef<const StringRef *> NameRefs);
746 /// Matches declarations for QualType and CallExpr.
748 /// Type argument DeclMatcherT is required by PolymorphicMatcherWithParam1 but
749 /// not actually used.
750 template <typename T, typename DeclMatcherT>
751 class HasDeclarationMatcher : public WrapperMatcherInterface<T> {
752 static_assert(std::is_same<DeclMatcherT, Matcher<Decl>>::value,
753 "instantiated with wrong types");
756 explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher)
757 : HasDeclarationMatcher::WrapperMatcherInterface(InnerMatcher) {}
759 bool matches(const T &Node, ASTMatchFinder *Finder,
760 BoundNodesTreeBuilder *Builder) const override {
761 return matchesSpecialized(Node, Finder, Builder);
765 /// Forwards to matching on the underlying type of the QualType.
766 bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder,
767 BoundNodesTreeBuilder *Builder) const {
771 return matchesSpecialized(*Node, Finder, Builder);
774 /// Finds the best declaration for a type and returns whether the inner
775 /// matcher matches on it.
776 bool matchesSpecialized(const Type &Node, ASTMatchFinder *Finder,
777 BoundNodesTreeBuilder *Builder) const {
778 // DeducedType does not have declarations of its own, so
779 // match the deduced type instead.
780 const Type *EffectiveType = &Node;
781 if (const auto *S = dyn_cast<DeducedType>(&Node)) {
782 EffectiveType = S->getDeducedType().getTypePtrOrNull();
787 // First, for any types that have a declaration, extract the declaration and
789 if (const auto *S = dyn_cast<TagType>(EffectiveType)) {
790 return matchesDecl(S->getDecl(), Finder, Builder);
792 if (const auto *S = dyn_cast<InjectedClassNameType>(EffectiveType)) {
793 return matchesDecl(S->getDecl(), Finder, Builder);
795 if (const auto *S = dyn_cast<TemplateTypeParmType>(EffectiveType)) {
796 return matchesDecl(S->getDecl(), Finder, Builder);
798 if (const auto *S = dyn_cast<TypedefType>(EffectiveType)) {
799 return matchesDecl(S->getDecl(), Finder, Builder);
801 if (const auto *S = dyn_cast<UnresolvedUsingType>(EffectiveType)) {
802 return matchesDecl(S->getDecl(), Finder, Builder);
804 if (const auto *S = dyn_cast<ObjCObjectType>(EffectiveType)) {
805 return matchesDecl(S->getInterface(), Finder, Builder);
808 // A SubstTemplateTypeParmType exists solely to mark a type substitution
809 // on the instantiated template. As users usually want to match the
810 // template parameter on the uninitialized template, we can always desugar
811 // one level without loss of expressivness.
812 // For example, given:
813 // template<typename T> struct X { T t; } class A {}; X<A> a;
814 // The following matcher will match, which otherwise would not:
815 // fieldDecl(hasType(pointerType())).
816 if (const auto *S = dyn_cast<SubstTemplateTypeParmType>(EffectiveType)) {
817 return matchesSpecialized(S->getReplacementType(), Finder, Builder);
820 // For template specialization types, we want to match the template
821 // declaration, as long as the type is still dependent, and otherwise the
822 // declaration of the instantiated tag type.
823 if (const auto *S = dyn_cast<TemplateSpecializationType>(EffectiveType)) {
824 if (!S->isTypeAlias() && S->isSugared()) {
825 // If the template is non-dependent, we want to match the instantiated
827 // For example, given:
828 // template<typename T> struct X {}; X<int> a;
829 // The following matcher will match, which otherwise would not:
830 // templateSpecializationType(hasDeclaration(cxxRecordDecl())).
831 return matchesSpecialized(*S->desugar(), Finder, Builder);
833 // If the template is dependent or an alias, match the template
835 return matchesDecl(S->getTemplateName().getAsTemplateDecl(), Finder,
839 // FIXME: We desugar elaborated types. This makes the assumption that users
840 // do never want to match on whether a type is elaborated - there are
841 // arguments for both sides; for now, continue desugaring.
842 if (const auto *S = dyn_cast<ElaboratedType>(EffectiveType)) {
843 return matchesSpecialized(S->desugar(), Finder, Builder);
848 /// Extracts the Decl the DeclRefExpr references and returns whether
849 /// the inner matcher matches on it.
850 bool matchesSpecialized(const DeclRefExpr &Node, ASTMatchFinder *Finder,
851 BoundNodesTreeBuilder *Builder) const {
852 return matchesDecl(Node.getDecl(), Finder, Builder);
855 /// Extracts the Decl of the callee of a CallExpr and returns whether
856 /// the inner matcher matches on it.
857 bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder,
858 BoundNodesTreeBuilder *Builder) const {
859 return matchesDecl(Node.getCalleeDecl(), Finder, Builder);
862 /// Extracts the Decl of the constructor call and returns whether the
863 /// inner matcher matches on it.
864 bool matchesSpecialized(const CXXConstructExpr &Node,
865 ASTMatchFinder *Finder,
866 BoundNodesTreeBuilder *Builder) const {
867 return matchesDecl(Node.getConstructor(), Finder, Builder);
870 bool matchesSpecialized(const ObjCIvarRefExpr &Node,
871 ASTMatchFinder *Finder,
872 BoundNodesTreeBuilder *Builder) const {
873 return matchesDecl(Node.getDecl(), Finder, Builder);
876 /// Extracts the operator new of the new call and returns whether the
877 /// inner matcher matches on it.
878 bool matchesSpecialized(const CXXNewExpr &Node,
879 ASTMatchFinder *Finder,
880 BoundNodesTreeBuilder *Builder) const {
881 return matchesDecl(Node.getOperatorNew(), Finder, Builder);
884 /// Extracts the \c ValueDecl a \c MemberExpr refers to and returns
885 /// whether the inner matcher matches on it.
886 bool matchesSpecialized(const MemberExpr &Node,
887 ASTMatchFinder *Finder,
888 BoundNodesTreeBuilder *Builder) const {
889 return matchesDecl(Node.getMemberDecl(), Finder, Builder);
892 /// Extracts the \c LabelDecl a \c AddrLabelExpr refers to and returns
893 /// whether the inner matcher matches on it.
894 bool matchesSpecialized(const AddrLabelExpr &Node,
895 ASTMatchFinder *Finder,
896 BoundNodesTreeBuilder *Builder) const {
897 return matchesDecl(Node.getLabel(), Finder, Builder);
900 /// Extracts the declaration of a LabelStmt and returns whether the
901 /// inner matcher matches on it.
902 bool matchesSpecialized(const LabelStmt &Node, ASTMatchFinder *Finder,
903 BoundNodesTreeBuilder *Builder) const {
904 return matchesDecl(Node.getDecl(), Finder, Builder);
907 /// Returns whether the inner matcher \c Node. Returns false if \c Node
909 bool matchesDecl(const Decl *Node, ASTMatchFinder *Finder,
910 BoundNodesTreeBuilder *Builder) const {
911 return Node != nullptr &&
912 this->InnerMatcher.matches(
913 ast_type_traits::DynTypedNode::create(*Node), Finder, Builder);
917 /// IsBaseType<T>::value is true if T is a "base" type in the AST
918 /// node class hierarchies.
919 template <typename T>
921 static const bool value =
922 std::is_same<T, Decl>::value ||
923 std::is_same<T, Stmt>::value ||
924 std::is_same<T, QualType>::value ||
925 std::is_same<T, Type>::value ||
926 std::is_same<T, TypeLoc>::value ||
927 std::is_same<T, NestedNameSpecifier>::value ||
928 std::is_same<T, NestedNameSpecifierLoc>::value ||
929 std::is_same<T, CXXCtorInitializer>::value;
931 template <typename T>
932 const bool IsBaseType<T>::value;
934 /// Interface that allows matchers to traverse the AST.
935 /// FIXME: Find a better name.
937 /// This provides three entry methods for each base node type in the AST:
938 /// - \c matchesChildOf:
939 /// Matches a matcher on every child node of the given node. Returns true
940 /// if at least one child node could be matched.
941 /// - \c matchesDescendantOf:
942 /// Matches a matcher on all descendant nodes of the given node. Returns true
943 /// if at least one descendant matched.
944 /// - \c matchesAncestorOf:
945 /// Matches a matcher on all ancestors of the given node. Returns true if
946 /// at least one ancestor matched.
948 /// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal.
949 /// In the future, we want to implement this for all nodes for which it makes
950 /// sense. In the case of matchesAncestorOf, we'll want to implement it for
951 /// all nodes, as all nodes have ancestors.
952 class ASTMatchFinder {
954 /// Defines how we descend a level in the AST when we pass
955 /// through expressions.
957 /// Will traverse any child nodes.
960 /// Will not traverse implicit casts and parentheses.
961 TK_IgnoreImplicitCastsAndParentheses
964 /// Defines how bindings are processed on recursive matches.
966 /// Stop at the first match and only bind the first match.
969 /// Create results for all combinations of bindings that match.
973 /// Defines which ancestors are considered for a match.
974 enum AncestorMatchMode {
978 /// Direct parent only.
982 virtual ~ASTMatchFinder() = default;
984 /// Returns true if the given class is directly or indirectly derived
985 /// from a base type matching \c base.
987 /// A class is considered to be also derived from itself.
988 virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
989 const Matcher<NamedDecl> &Base,
990 BoundNodesTreeBuilder *Builder) = 0;
992 template <typename T>
993 bool matchesChildOf(const T &Node,
994 const DynTypedMatcher &Matcher,
995 BoundNodesTreeBuilder *Builder,
996 TraversalKind Traverse,
998 static_assert(std::is_base_of<Decl, T>::value ||
999 std::is_base_of<Stmt, T>::value ||
1000 std::is_base_of<NestedNameSpecifier, T>::value ||
1001 std::is_base_of<NestedNameSpecifierLoc, T>::value ||
1002 std::is_base_of<TypeLoc, T>::value ||
1003 std::is_base_of<QualType, T>::value,
1004 "unsupported type for recursive matching");
1005 return matchesChildOf(ast_type_traits::DynTypedNode::create(Node),
1006 Matcher, Builder, Traverse, Bind);
1009 template <typename T>
1010 bool matchesDescendantOf(const T &Node,
1011 const DynTypedMatcher &Matcher,
1012 BoundNodesTreeBuilder *Builder,
1014 static_assert(std::is_base_of<Decl, T>::value ||
1015 std::is_base_of<Stmt, T>::value ||
1016 std::is_base_of<NestedNameSpecifier, T>::value ||
1017 std::is_base_of<NestedNameSpecifierLoc, T>::value ||
1018 std::is_base_of<TypeLoc, T>::value ||
1019 std::is_base_of<QualType, T>::value,
1020 "unsupported type for recursive matching");
1021 return matchesDescendantOf(ast_type_traits::DynTypedNode::create(Node),
1022 Matcher, Builder, Bind);
1025 // FIXME: Implement support for BindKind.
1026 template <typename T>
1027 bool matchesAncestorOf(const T &Node,
1028 const DynTypedMatcher &Matcher,
1029 BoundNodesTreeBuilder *Builder,
1030 AncestorMatchMode MatchMode) {
1031 static_assert(std::is_base_of<Decl, T>::value ||
1032 std::is_base_of<NestedNameSpecifierLoc, T>::value ||
1033 std::is_base_of<Stmt, T>::value ||
1034 std::is_base_of<TypeLoc, T>::value,
1035 "type not allowed for recursive matching");
1036 return matchesAncestorOf(ast_type_traits::DynTypedNode::create(Node),
1037 Matcher, Builder, MatchMode);
1040 virtual ASTContext &getASTContext() const = 0;
1043 virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node,
1044 const DynTypedMatcher &Matcher,
1045 BoundNodesTreeBuilder *Builder,
1046 TraversalKind Traverse,
1049 virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node,
1050 const DynTypedMatcher &Matcher,
1051 BoundNodesTreeBuilder *Builder,
1054 virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node,
1055 const DynTypedMatcher &Matcher,
1056 BoundNodesTreeBuilder *Builder,
1057 AncestorMatchMode MatchMode) = 0;
1060 /// A type-list implementation.
1062 /// A "linked list" of types, accessible by using the ::head and ::tail
1064 template <typename... Ts> struct TypeList {}; // Empty sentinel type list.
1066 template <typename T1, typename... Ts> struct TypeList<T1, Ts...> {
1067 /// The first type on the list.
1070 /// A sublist with the tail. ie everything but the head.
1072 /// This type is used to do recursion. TypeList<>/EmptyTypeList indicates the
1073 /// end of the list.
1074 using tail = TypeList<Ts...>;
1077 /// The empty type list.
1078 using EmptyTypeList = TypeList<>;
1080 /// Helper meta-function to determine if some type \c T is present or
1081 /// a parent type in the list.
1082 template <typename AnyTypeList, typename T>
1083 struct TypeListContainsSuperOf {
1084 static const bool value =
1085 std::is_base_of<typename AnyTypeList::head, T>::value ||
1086 TypeListContainsSuperOf<typename AnyTypeList::tail, T>::value;
1088 template <typename T>
1089 struct TypeListContainsSuperOf<EmptyTypeList, T> {
1090 static const bool value = false;
1093 /// A "type list" that contains all types.
1095 /// Useful for matchers like \c anything and \c unless.
1096 using AllNodeBaseTypes =
1097 TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc, QualType,
1098 Type, TypeLoc, CXXCtorInitializer>;
1100 /// Helper meta-function to extract the argument out of a function of
1103 /// See AST_POLYMORPHIC_SUPPORTED_TYPES for details.
1104 template <class T> struct ExtractFunctionArgMeta;
1105 template <class T> struct ExtractFunctionArgMeta<void(T)> {
1109 /// Default type lists for ArgumentAdaptingMatcher matchers.
1110 using AdaptativeDefaultFromTypes = AllNodeBaseTypes;
1111 using AdaptativeDefaultToTypes =
1112 TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc, TypeLoc,
1115 /// All types that are supported by HasDeclarationMatcher above.
1116 using HasDeclarationSupportedTypes =
1117 TypeList<CallExpr, CXXConstructExpr, CXXNewExpr, DeclRefExpr, EnumType,
1118 ElaboratedType, InjectedClassNameType, LabelStmt, AddrLabelExpr,
1119 MemberExpr, QualType, RecordType, TagType,
1120 TemplateSpecializationType, TemplateTypeParmType, TypedefType,
1121 UnresolvedUsingType, ObjCIvarRefExpr>;
1123 /// Converts a \c Matcher<T> to a matcher of desired type \c To by
1124 /// "adapting" a \c To into a \c T.
1126 /// The \c ArgumentAdapterT argument specifies how the adaptation is done.
1129 /// \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher);
1130 /// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher
1131 /// that is convertible into any matcher of type \c To by constructing
1132 /// \c HasMatcher<To, T>(InnerMatcher).
1134 /// If a matcher does not need knowledge about the inner type, prefer to use
1135 /// PolymorphicMatcherWithParam1.
1136 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
1137 typename FromTypes = AdaptativeDefaultFromTypes,
1138 typename ToTypes = AdaptativeDefaultToTypes>
1139 struct ArgumentAdaptingMatcherFunc {
1140 template <typename T> class Adaptor {
1142 explicit Adaptor(const Matcher<T> &InnerMatcher)
1143 : InnerMatcher(InnerMatcher) {}
1145 using ReturnTypes = ToTypes;
1147 template <typename To> operator Matcher<To>() const {
1148 return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher));
1152 const Matcher<T> InnerMatcher;
1155 template <typename T>
1156 static Adaptor<T> create(const Matcher<T> &InnerMatcher) {
1157 return Adaptor<T>(InnerMatcher);
1160 template <typename T>
1161 Adaptor<T> operator()(const Matcher<T> &InnerMatcher) const {
1162 return create(InnerMatcher);
1166 /// A PolymorphicMatcherWithParamN<MatcherT, P1, ..., PN> object can be
1167 /// created from N parameters p1, ..., pN (of type P1, ..., PN) and
1168 /// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN)
1169 /// can be constructed.
1172 /// - PolymorphicMatcherWithParam0<IsDefinitionMatcher>()
1173 /// creates an object that can be used as a Matcher<T> for any type T
1174 /// where an IsDefinitionMatcher<T>() can be constructed.
1175 /// - PolymorphicMatcherWithParam1<ValueEqualsMatcher, int>(42)
1176 /// creates an object that can be used as a Matcher<T> for any type T
1177 /// where a ValueEqualsMatcher<T, int>(42) can be constructed.
1178 template <template <typename T> class MatcherT,
1179 typename ReturnTypesF = void(AllNodeBaseTypes)>
1180 class PolymorphicMatcherWithParam0 {
1182 using ReturnTypes = typename ExtractFunctionArgMeta<ReturnTypesF>::type;
1184 template <typename T>
1185 operator Matcher<T>() const {
1186 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
1187 "right polymorphic conversion");
1188 return Matcher<T>(new MatcherT<T>());
1192 template <template <typename T, typename P1> class MatcherT,
1194 typename ReturnTypesF = void(AllNodeBaseTypes)>
1195 class PolymorphicMatcherWithParam1 {
1197 explicit PolymorphicMatcherWithParam1(const P1 &Param1)
1200 using ReturnTypes = typename ExtractFunctionArgMeta<ReturnTypesF>::type;
1202 template <typename T>
1203 operator Matcher<T>() const {
1204 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
1205 "right polymorphic conversion");
1206 return Matcher<T>(new MatcherT<T, P1>(Param1));
1213 template <template <typename T, typename P1, typename P2> class MatcherT,
1214 typename P1, typename P2,
1215 typename ReturnTypesF = void(AllNodeBaseTypes)>
1216 class PolymorphicMatcherWithParam2 {
1218 PolymorphicMatcherWithParam2(const P1 &Param1, const P2 &Param2)
1219 : Param1(Param1), Param2(Param2) {}
1221 using ReturnTypes = typename ExtractFunctionArgMeta<ReturnTypesF>::type;
1223 template <typename T>
1224 operator Matcher<T>() const {
1225 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
1226 "right polymorphic conversion");
1227 return Matcher<T>(new MatcherT<T, P1, P2>(Param1, Param2));
1235 /// Matches any instance of the given NodeType.
1237 /// This is useful when a matcher syntactically requires a child matcher,
1238 /// but the context doesn't care. See for example: anything().
1241 using ReturnTypes = AllNodeBaseTypes;
1243 template <typename T>
1244 operator Matcher<T>() const {
1245 return DynTypedMatcher::trueMatcher(
1246 ast_type_traits::ASTNodeKind::getFromNodeKind<T>())
1247 .template unconditionalConvertTo<T>();
1251 /// A Matcher that allows binding the node it matches to an id.
1253 /// BindableMatcher provides a \a bind() method that allows binding the
1254 /// matched node to an id if the match was successful.
1255 template <typename T>
1256 class BindableMatcher : public Matcher<T> {
1258 explicit BindableMatcher(const Matcher<T> &M) : Matcher<T>(M) {}
1259 explicit BindableMatcher(MatcherInterface<T> *Implementation)
1260 : Matcher<T>(Implementation) {}
1262 /// Returns a matcher that will bind the matched node on a match.
1264 /// The returned matcher is equivalent to this matcher, but will
1265 /// bind the matched node on a match.
1266 Matcher<T> bind(StringRef ID) const {
1267 return DynTypedMatcher(*this)
1269 ->template unconditionalConvertTo<T>();
1272 /// Same as Matcher<T>'s conversion operator, but enables binding on
1273 /// the returned matcher.
1274 operator DynTypedMatcher() const {
1275 DynTypedMatcher Result = static_cast<const Matcher<T>&>(*this);
1276 Result.setAllowBind(true);
1281 /// Matches nodes of type T that have child nodes of type ChildT for
1282 /// which a specified child matcher matches.
1284 /// ChildT must be an AST base type.
1285 template <typename T, typename ChildT>
1286 class HasMatcher : public WrapperMatcherInterface<T> {
1288 explicit HasMatcher(const Matcher<ChildT> &ChildMatcher)
1289 : HasMatcher::WrapperMatcherInterface(ChildMatcher) {}
1291 bool matches(const T &Node, ASTMatchFinder *Finder,
1292 BoundNodesTreeBuilder *Builder) const override {
1293 return Finder->matchesChildOf(Node, this->InnerMatcher, Builder,
1294 ASTMatchFinder::TK_AsIs,
1295 ASTMatchFinder::BK_First);
1299 /// Matches nodes of type T that have child nodes of type ChildT for
1300 /// which a specified child matcher matches. ChildT must be an AST base
1302 /// As opposed to the HasMatcher, the ForEachMatcher will produce a match
1303 /// for each child that matches.
1304 template <typename T, typename ChildT>
1305 class ForEachMatcher : public WrapperMatcherInterface<T> {
1306 static_assert(IsBaseType<ChildT>::value,
1307 "for each only accepts base type matcher");
1310 explicit ForEachMatcher(const Matcher<ChildT> &ChildMatcher)
1311 : ForEachMatcher::WrapperMatcherInterface(ChildMatcher) {}
1313 bool matches(const T& Node, ASTMatchFinder* Finder,
1314 BoundNodesTreeBuilder* Builder) const override {
1315 return Finder->matchesChildOf(
1316 Node, this->InnerMatcher, Builder,
1317 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
1318 ASTMatchFinder::BK_All);
1322 /// VariadicOperatorMatcher related types.
1325 /// Polymorphic matcher object that uses a \c
1326 /// DynTypedMatcher::VariadicOperator operator.
1328 /// Input matchers can have any type (including other polymorphic matcher
1329 /// types), and the actual Matcher<T> is generated on demand with an implicit
1330 /// coversion operator.
1331 template <typename... Ps> class VariadicOperatorMatcher {
1333 VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op, Ps &&... Params)
1334 : Op(Op), Params(std::forward<Ps>(Params)...) {}
1336 template <typename T> operator Matcher<T>() const {
1337 return DynTypedMatcher::constructVariadic(
1338 Op, ast_type_traits::ASTNodeKind::getFromNodeKind<T>(),
1339 getMatchers<T>(llvm::index_sequence_for<Ps...>()))
1340 .template unconditionalConvertTo<T>();
1344 // Helper method to unpack the tuple into a vector.
1345 template <typename T, std::size_t... Is>
1346 std::vector<DynTypedMatcher> getMatchers(llvm::index_sequence<Is...>) const {
1347 return {Matcher<T>(std::get<Is>(Params))...};
1350 const DynTypedMatcher::VariadicOperator Op;
1351 std::tuple<Ps...> Params;
1354 /// Overloaded function object to generate VariadicOperatorMatcher
1355 /// objects from arbitrary matchers.
1356 template <unsigned MinCount, unsigned MaxCount>
1357 struct VariadicOperatorMatcherFunc {
1358 DynTypedMatcher::VariadicOperator Op;
1360 template <typename... Ms>
1361 VariadicOperatorMatcher<Ms...> operator()(Ms &&... Ps) const {
1362 static_assert(MinCount <= sizeof...(Ms) && sizeof...(Ms) <= MaxCount,
1363 "invalid number of parameters for variadic matcher");
1364 return VariadicOperatorMatcher<Ms...>(Op, std::forward<Ms>(Ps)...);
1370 template <typename T>
1371 inline Matcher<T> DynTypedMatcher::unconditionalConvertTo() const {
1372 return Matcher<T>(*this);
1375 /// Creates a Matcher<T> that matches if all inner matchers match.
1376 template<typename T>
1377 BindableMatcher<T> makeAllOfComposite(
1378 ArrayRef<const Matcher<T> *> InnerMatchers) {
1379 // For the size() == 0 case, we return a "true" matcher.
1380 if (InnerMatchers.empty()) {
1381 return BindableMatcher<T>(TrueMatcher());
1383 // For the size() == 1 case, we simply return that one matcher.
1384 // No need to wrap it in a variadic operation.
1385 if (InnerMatchers.size() == 1) {
1386 return BindableMatcher<T>(*InnerMatchers[0]);
1389 using PI = llvm::pointee_iterator<const Matcher<T> *const *>;
1391 std::vector<DynTypedMatcher> DynMatchers(PI(InnerMatchers.begin()),
1392 PI(InnerMatchers.end()));
1393 return BindableMatcher<T>(
1394 DynTypedMatcher::constructVariadic(
1395 DynTypedMatcher::VO_AllOf,
1396 ast_type_traits::ASTNodeKind::getFromNodeKind<T>(),
1397 std::move(DynMatchers))
1398 .template unconditionalConvertTo<T>());
1401 /// Creates a Matcher<T> that matches if
1402 /// T is dyn_cast'able into InnerT and all inner matchers match.
1404 /// Returns BindableMatcher, as matchers that use dyn_cast have
1405 /// the same object both to match on and to run submatchers on,
1406 /// so there is no ambiguity with what gets bound.
1407 template<typename T, typename InnerT>
1408 BindableMatcher<T> makeDynCastAllOfComposite(
1409 ArrayRef<const Matcher<InnerT> *> InnerMatchers) {
1410 return BindableMatcher<T>(
1411 makeAllOfComposite(InnerMatchers).template dynCastTo<T>());
1414 /// Matches nodes of type T that have at least one descendant node of
1415 /// type DescendantT for which the given inner matcher matches.
1417 /// DescendantT must be an AST base type.
1418 template <typename T, typename DescendantT>
1419 class HasDescendantMatcher : public WrapperMatcherInterface<T> {
1420 static_assert(IsBaseType<DescendantT>::value,
1421 "has descendant only accepts base type matcher");
1424 explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher)
1425 : HasDescendantMatcher::WrapperMatcherInterface(DescendantMatcher) {}
1427 bool matches(const T &Node, ASTMatchFinder *Finder,
1428 BoundNodesTreeBuilder *Builder) const override {
1429 return Finder->matchesDescendantOf(Node, this->InnerMatcher, Builder,
1430 ASTMatchFinder::BK_First);
1434 /// Matches nodes of type \c T that have a parent node of type \c ParentT
1435 /// for which the given inner matcher matches.
1437 /// \c ParentT must be an AST base type.
1438 template <typename T, typename ParentT>
1439 class HasParentMatcher : public WrapperMatcherInterface<T> {
1440 static_assert(IsBaseType<ParentT>::value,
1441 "has parent only accepts base type matcher");
1444 explicit HasParentMatcher(const Matcher<ParentT> &ParentMatcher)
1445 : HasParentMatcher::WrapperMatcherInterface(ParentMatcher) {}
1447 bool matches(const T &Node, ASTMatchFinder *Finder,
1448 BoundNodesTreeBuilder *Builder) const override {
1449 return Finder->matchesAncestorOf(Node, this->InnerMatcher, Builder,
1450 ASTMatchFinder::AMM_ParentOnly);
1454 /// Matches nodes of type \c T that have at least one ancestor node of
1455 /// type \c AncestorT for which the given inner matcher matches.
1457 /// \c AncestorT must be an AST base type.
1458 template <typename T, typename AncestorT>
1459 class HasAncestorMatcher : public WrapperMatcherInterface<T> {
1460 static_assert(IsBaseType<AncestorT>::value,
1461 "has ancestor only accepts base type matcher");
1464 explicit HasAncestorMatcher(const Matcher<AncestorT> &AncestorMatcher)
1465 : HasAncestorMatcher::WrapperMatcherInterface(AncestorMatcher) {}
1467 bool matches(const T &Node, ASTMatchFinder *Finder,
1468 BoundNodesTreeBuilder *Builder) const override {
1469 return Finder->matchesAncestorOf(Node, this->InnerMatcher, Builder,
1470 ASTMatchFinder::AMM_All);
1474 /// Matches nodes of type T that have at least one descendant node of
1475 /// type DescendantT for which the given inner matcher matches.
1477 /// DescendantT must be an AST base type.
1478 /// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match
1479 /// for each descendant node that matches instead of only for the first.
1480 template <typename T, typename DescendantT>
1481 class ForEachDescendantMatcher : public WrapperMatcherInterface<T> {
1482 static_assert(IsBaseType<DescendantT>::value,
1483 "for each descendant only accepts base type matcher");
1486 explicit ForEachDescendantMatcher(
1487 const Matcher<DescendantT> &DescendantMatcher)
1488 : ForEachDescendantMatcher::WrapperMatcherInterface(DescendantMatcher) {}
1490 bool matches(const T &Node, ASTMatchFinder *Finder,
1491 BoundNodesTreeBuilder *Builder) const override {
1492 return Finder->matchesDescendantOf(Node, this->InnerMatcher, Builder,
1493 ASTMatchFinder::BK_All);
1497 /// Matches on nodes that have a getValue() method if getValue() equals
1498 /// the value the ValueEqualsMatcher was constructed with.
1499 template <typename T, typename ValueT>
1500 class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> {
1501 static_assert(std::is_base_of<CharacterLiteral, T>::value ||
1502 std::is_base_of<CXXBoolLiteralExpr, T>::value ||
1503 std::is_base_of<FloatingLiteral, T>::value ||
1504 std::is_base_of<IntegerLiteral, T>::value,
1505 "the node must have a getValue method");
1508 explicit ValueEqualsMatcher(const ValueT &ExpectedValue)
1509 : ExpectedValue(ExpectedValue) {}
1511 bool matchesNode(const T &Node) const override {
1512 return Node.getValue() == ExpectedValue;
1516 const ValueT ExpectedValue;
1519 /// Template specializations to easily write matchers for floating point
1522 inline bool ValueEqualsMatcher<FloatingLiteral, double>::matchesNode(
1523 const FloatingLiteral &Node) const {
1524 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle())
1525 return Node.getValue().convertToFloat() == ExpectedValue;
1526 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble())
1527 return Node.getValue().convertToDouble() == ExpectedValue;
1531 inline bool ValueEqualsMatcher<FloatingLiteral, float>::matchesNode(
1532 const FloatingLiteral &Node) const {
1533 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle())
1534 return Node.getValue().convertToFloat() == ExpectedValue;
1535 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble())
1536 return Node.getValue().convertToDouble() == ExpectedValue;
1540 inline bool ValueEqualsMatcher<FloatingLiteral, llvm::APFloat>::matchesNode(
1541 const FloatingLiteral &Node) const {
1542 return ExpectedValue.compare(Node.getValue()) == llvm::APFloat::cmpEqual;
1545 /// A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a
1546 /// variadic functor that takes a number of Matcher<TargetT> and returns a
1547 /// Matcher<SourceT> that matches TargetT nodes that are matched by all of the
1548 /// given matchers, if SourceT can be dynamically casted into TargetT.
1551 /// const VariadicDynCastAllOfMatcher<
1552 /// Decl, CXXRecordDecl> record;
1553 /// Creates a functor record(...) that creates a Matcher<Decl> given
1554 /// a variable number of arguments of type Matcher<CXXRecordDecl>.
1555 /// The returned matcher matches if the given Decl can by dynamically
1556 /// casted to CXXRecordDecl and all given matchers match.
1557 template <typename SourceT, typename TargetT>
1558 class VariadicDynCastAllOfMatcher
1559 : public VariadicFunction<BindableMatcher<SourceT>, Matcher<TargetT>,
1560 makeDynCastAllOfComposite<SourceT, TargetT>> {
1562 VariadicDynCastAllOfMatcher() {}
1565 /// A \c VariadicAllOfMatcher<T> object is a variadic functor that takes
1566 /// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T
1567 /// nodes that are matched by all of the given matchers.
1570 /// const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
1571 /// Creates a functor nestedNameSpecifier(...) that creates a
1572 /// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type
1573 /// \c Matcher<NestedNameSpecifier>.
1574 /// The returned matcher matches if all given matchers match.
1575 template <typename T>
1576 class VariadicAllOfMatcher
1577 : public VariadicFunction<BindableMatcher<T>, Matcher<T>,
1578 makeAllOfComposite<T>> {
1580 VariadicAllOfMatcher() {}
1583 /// Matches nodes of type \c TLoc for which the inner
1584 /// \c Matcher<T> matches.
1585 template <typename TLoc, typename T>
1586 class LocMatcher : public WrapperMatcherInterface<TLoc> {
1588 explicit LocMatcher(const Matcher<T> &InnerMatcher)
1589 : LocMatcher::WrapperMatcherInterface(InnerMatcher) {}
1591 bool matches(const TLoc &Node, ASTMatchFinder *Finder,
1592 BoundNodesTreeBuilder *Builder) const override {
1595 return this->InnerMatcher.matches(extract(Node), Finder, Builder);
1599 static ast_type_traits::DynTypedNode
1600 extract(const NestedNameSpecifierLoc &Loc) {
1601 return ast_type_traits::DynTypedNode::create(*Loc.getNestedNameSpecifier());
1605 /// Matches \c TypeLocs based on an inner matcher matching a certain
1608 /// Used to implement the \c loc() matcher.
1609 class TypeLocTypeMatcher : public WrapperMatcherInterface<TypeLoc> {
1611 explicit TypeLocTypeMatcher(const Matcher<QualType> &InnerMatcher)
1612 : TypeLocTypeMatcher::WrapperMatcherInterface(InnerMatcher) {}
1614 bool matches(const TypeLoc &Node, ASTMatchFinder *Finder,
1615 BoundNodesTreeBuilder *Builder) const override {
1618 return this->InnerMatcher.matches(
1619 ast_type_traits::DynTypedNode::create(Node.getType()), Finder, Builder);
1623 /// Matches nodes of type \c T for which the inner matcher matches on a
1624 /// another node of type \c T that can be reached using a given traverse
1626 template <typename T>
1627 class TypeTraverseMatcher : public WrapperMatcherInterface<T> {
1629 explicit TypeTraverseMatcher(const Matcher<QualType> &InnerMatcher,
1630 QualType (T::*TraverseFunction)() const)
1631 : TypeTraverseMatcher::WrapperMatcherInterface(InnerMatcher),
1632 TraverseFunction(TraverseFunction) {}
1634 bool matches(const T &Node, ASTMatchFinder *Finder,
1635 BoundNodesTreeBuilder *Builder) const override {
1636 QualType NextNode = (Node.*TraverseFunction)();
1637 if (NextNode.isNull())
1639 return this->InnerMatcher.matches(
1640 ast_type_traits::DynTypedNode::create(NextNode), Finder, Builder);
1644 QualType (T::*TraverseFunction)() const;
1647 /// Matches nodes of type \c T in a ..Loc hierarchy, for which the inner
1648 /// matcher matches on a another node of type \c T that can be reached using a
1649 /// given traverse function.
1650 template <typename T>
1651 class TypeLocTraverseMatcher : public WrapperMatcherInterface<T> {
1653 explicit TypeLocTraverseMatcher(const Matcher<TypeLoc> &InnerMatcher,
1654 TypeLoc (T::*TraverseFunction)() const)
1655 : TypeLocTraverseMatcher::WrapperMatcherInterface(InnerMatcher),
1656 TraverseFunction(TraverseFunction) {}
1658 bool matches(const T &Node, ASTMatchFinder *Finder,
1659 BoundNodesTreeBuilder *Builder) const override {
1660 TypeLoc NextNode = (Node.*TraverseFunction)();
1663 return this->InnerMatcher.matches(
1664 ast_type_traits::DynTypedNode::create(NextNode), Finder, Builder);
1668 TypeLoc (T::*TraverseFunction)() const;
1671 /// Converts a \c Matcher<InnerT> to a \c Matcher<OuterT>, where
1672 /// \c OuterT is any type that is supported by \c Getter.
1674 /// \code Getter<OuterT>::value() \endcode returns a
1675 /// \code InnerTBase (OuterT::*)() \endcode, which is used to adapt a \c OuterT
1676 /// object into a \c InnerT
1677 template <typename InnerTBase,
1678 template <typename OuterT> class Getter,
1679 template <typename OuterT> class MatcherImpl,
1680 typename ReturnTypesF>
1681 class TypeTraversePolymorphicMatcher {
1683 using Self = TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl,
1686 static Self create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers);
1689 using ReturnTypes = typename ExtractFunctionArgMeta<ReturnTypesF>::type;
1691 explicit TypeTraversePolymorphicMatcher(
1692 ArrayRef<const Matcher<InnerTBase> *> InnerMatchers)
1693 : InnerMatcher(makeAllOfComposite(InnerMatchers)) {}
1695 template <typename OuterT> operator Matcher<OuterT>() const {
1696 return Matcher<OuterT>(
1697 new MatcherImpl<OuterT>(InnerMatcher, Getter<OuterT>::value()));
1701 : public VariadicFunction<Self, Matcher<InnerTBase>, &Self::create> {
1706 const Matcher<InnerTBase> InnerMatcher;
1709 /// A simple memoizer of T(*)() functions.
1711 /// It will call the passed 'Func' template parameter at most once.
1712 /// Used to support AST_MATCHER_FUNCTION() macro.
1713 template <typename Matcher, Matcher (*Func)()> class MemoizedMatcher {
1715 Wrapper() : M(Func()) {}
1721 static const Matcher &getInstance() {
1722 static llvm::ManagedStatic<Wrapper> Instance;
1727 // Define the create() method out of line to silence a GCC warning about
1728 // the struct "Func" having greater visibility than its base, which comes from
1729 // using the flag -fvisibility-inlines-hidden.
1730 template <typename InnerTBase, template <typename OuterT> class Getter,
1731 template <typename OuterT> class MatcherImpl, typename ReturnTypesF>
1732 TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl, ReturnTypesF>
1733 TypeTraversePolymorphicMatcher<
1734 InnerTBase, Getter, MatcherImpl,
1735 ReturnTypesF>::create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers) {
1736 return Self(InnerMatchers);
1739 // FIXME: unify ClassTemplateSpecializationDecl and TemplateSpecializationType's
1740 // APIs for accessing the template argument list.
1741 inline ArrayRef<TemplateArgument>
1742 getTemplateSpecializationArgs(const ClassTemplateSpecializationDecl &D) {
1743 return D.getTemplateArgs().asArray();
1746 inline ArrayRef<TemplateArgument>
1747 getTemplateSpecializationArgs(const TemplateSpecializationType &T) {
1748 return llvm::makeArrayRef(T.getArgs(), T.getNumArgs());
1751 inline ArrayRef<TemplateArgument>
1752 getTemplateSpecializationArgs(const FunctionDecl &FD) {
1753 if (const auto* TemplateArgs = FD.getTemplateSpecializationArgs())
1754 return TemplateArgs->asArray();
1755 return ArrayRef<TemplateArgument>();
1758 struct NotEqualsBoundNodePredicate {
1759 bool operator()(const internal::BoundNodesMap &Nodes) const {
1760 return Nodes.getNode(ID) != Node;
1764 ast_type_traits::DynTypedNode Node;
1767 template <typename Ty>
1768 struct GetBodyMatcher {
1769 static const Stmt *get(const Ty &Node) {
1770 return Node.getBody();
1775 inline const Stmt *GetBodyMatcher<FunctionDecl>::get(const FunctionDecl &Node) {
1776 return Node.doesThisDeclarationHaveABody() ? Node.getBody() : nullptr;
1779 template <typename Ty>
1780 struct HasSizeMatcher {
1781 static bool hasSize(const Ty &Node, unsigned int N) {
1782 return Node.getSize() == N;
1787 inline bool HasSizeMatcher<StringLiteral>::hasSize(
1788 const StringLiteral &Node, unsigned int N) {
1789 return Node.getLength() == N;
1792 template <typename Ty>
1793 struct GetSourceExpressionMatcher {
1794 static const Expr *get(const Ty &Node) {
1795 return Node.getSubExpr();
1800 inline const Expr *GetSourceExpressionMatcher<OpaqueValueExpr>::get(
1801 const OpaqueValueExpr &Node) {
1802 return Node.getSourceExpr();
1805 template <typename Ty>
1806 struct CompoundStmtMatcher {
1807 static const CompoundStmt *get(const Ty &Node) {
1813 inline const CompoundStmt *
1814 CompoundStmtMatcher<StmtExpr>::get(const StmtExpr &Node) {
1815 return Node.getSubStmt();
1818 } // namespace internal
1820 } // namespace ast_matchers
1822 } // namespace clang
1824 #endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERSINTERNAL_H