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/DeclObjC.h"
42 #include "clang/AST/DeclTemplate.h"
43 #include "clang/AST/ExprCXX.h"
44 #include "clang/AST/ExprObjC.h"
45 #include "clang/AST/Stmt.h"
46 #include "clang/AST/StmtCXX.h"
47 #include "clang/AST/StmtObjC.h"
48 #include "clang/AST/Type.h"
49 #include "llvm/ADT/ArrayRef.h"
50 #include "llvm/ADT/Optional.h"
51 #include "llvm/ADT/SmallVector.h"
52 #include "llvm/Support/ManagedStatic.h"
58 namespace ast_matchers {
64 /// \brief Variadic function object.
66 /// Most of the functions below that use VariadicFunction could be implemented
67 /// using plain C++11 variadic functions, but the function object allows us to
68 /// capture it on the dynamic matcher registry.
69 template <typename ResultT, typename ArgT,
70 ResultT (*Func)(ArrayRef<const ArgT *>)>
71 struct VariadicFunction {
72 ResultT operator()() const { return Func(None); }
74 template <typename... ArgsT>
75 ResultT operator()(const ArgT &Arg1, const ArgsT &... Args) const {
76 return Execute(Arg1, static_cast<const ArgT &>(Args)...);
79 // We also allow calls with an already created array, in case the caller
81 ResultT operator()(ArrayRef<ArgT> Args) const {
82 SmallVector<const ArgT*, 8> InnerArgs;
83 for (const ArgT &Arg : Args)
84 InnerArgs.push_back(&Arg);
85 return Func(InnerArgs);
89 // Trampoline function to allow for implicit conversions to take place
90 // before we make the array.
91 template <typename... ArgsT> ResultT Execute(const ArgsT &... Args) const {
92 const ArgT *const ArgsArray[] = {&Args...};
93 return Func(ArrayRef<const ArgT *>(ArgsArray, sizeof...(ArgsT)));
97 /// \brief Unifies obtaining the underlying type of a regular node through
98 /// `getType` and a TypedefNameDecl node through `getUnderlyingType`.
99 inline QualType getUnderlyingType(const Expr &Node) { return Node.getType(); }
101 inline QualType getUnderlyingType(const ValueDecl &Node) {
102 return Node.getType();
105 inline QualType getUnderlyingType(const TypedefNameDecl &Node) {
106 return Node.getUnderlyingType();
109 /// \brief Unifies obtaining the FunctionProtoType pointer from both
110 /// FunctionProtoType and FunctionDecl nodes..
111 inline const FunctionProtoType *
112 getFunctionProtoType(const FunctionProtoType &Node) {
116 inline const FunctionProtoType *getFunctionProtoType(const FunctionDecl &Node) {
117 return Node.getType()->getAs<FunctionProtoType>();
120 /// \brief Internal version of BoundNodes. Holds all the bound nodes.
121 class BoundNodesMap {
123 /// \brief Adds \c Node to the map with key \c ID.
125 /// The node's base type should be in NodeBaseType or it will be unaccessible.
126 void addNode(StringRef ID, const ast_type_traits::DynTypedNode& DynNode) {
127 NodeMap[ID] = DynNode;
130 /// \brief Returns the AST node bound to \c ID.
132 /// Returns NULL if there was no node bound to \c ID or if there is a node but
133 /// it cannot be converted to the specified type.
134 template <typename T>
135 const T *getNodeAs(StringRef ID) const {
136 IDToNodeMap::const_iterator It = NodeMap.find(ID);
137 if (It == NodeMap.end()) {
140 return It->second.get<T>();
143 ast_type_traits::DynTypedNode getNode(StringRef ID) const {
144 IDToNodeMap::const_iterator It = NodeMap.find(ID);
145 if (It == NodeMap.end()) {
146 return ast_type_traits::DynTypedNode();
151 /// \brief Imposes an order on BoundNodesMaps.
152 bool operator<(const BoundNodesMap &Other) const {
153 return NodeMap < Other.NodeMap;
156 /// \brief A map from IDs to the bound nodes.
158 /// Note that we're using std::map here, as for memoization:
159 /// - we need a comparison operator
160 /// - we need an assignment operator
161 typedef std::map<std::string, ast_type_traits::DynTypedNode> IDToNodeMap;
163 const IDToNodeMap &getMap() const {
167 /// \brief Returns \c true if this \c BoundNodesMap can be compared, i.e. all
168 /// stored nodes have memoization data.
169 bool isComparable() const {
170 for (const auto &IDAndNode : NodeMap) {
171 if (!IDAndNode.second.getMemoizationData())
181 /// \brief Creates BoundNodesTree objects.
183 /// The tree builder is used during the matching process to insert the bound
184 /// nodes from the Id matcher.
185 class BoundNodesTreeBuilder {
187 /// \brief A visitor interface to visit all BoundNodes results for a
191 virtual ~Visitor() {}
193 /// \brief Called multiple times during a single call to VisitMatches(...).
195 /// 'BoundNodesView' contains the bound nodes for a single match.
196 virtual void visitMatch(const BoundNodes& BoundNodesView) = 0;
199 /// \brief Add a binding from an id to a node.
200 void setBinding(StringRef Id, const ast_type_traits::DynTypedNode &DynNode) {
201 if (Bindings.empty())
202 Bindings.emplace_back();
203 for (BoundNodesMap &Binding : Bindings)
204 Binding.addNode(Id, DynNode);
207 /// \brief Adds a branch in the tree.
208 void addMatch(const BoundNodesTreeBuilder &Bindings);
210 /// \brief Visits all matches that this BoundNodesTree represents.
212 /// The ownership of 'ResultVisitor' remains at the caller.
213 void visitMatches(Visitor* ResultVisitor);
215 template <typename ExcludePredicate>
216 bool removeBindings(const ExcludePredicate &Predicate) {
217 Bindings.erase(std::remove_if(Bindings.begin(), Bindings.end(), Predicate),
219 return !Bindings.empty();
222 /// \brief Imposes an order on BoundNodesTreeBuilders.
223 bool operator<(const BoundNodesTreeBuilder &Other) const {
224 return Bindings < Other.Bindings;
227 /// \brief Returns \c true if this \c BoundNodesTreeBuilder can be compared,
228 /// i.e. all stored node maps have memoization data.
229 bool isComparable() const {
230 for (const BoundNodesMap &NodesMap : Bindings) {
231 if (!NodesMap.isComparable())
238 SmallVector<BoundNodesMap, 16> Bindings;
241 class ASTMatchFinder;
243 /// \brief Generic interface for all matchers.
245 /// Used by the implementation of Matcher<T> and DynTypedMatcher.
246 /// In general, implement MatcherInterface<T> or SingleNodeMatcherInterface<T>
248 class DynMatcherInterface
249 : public llvm::ThreadSafeRefCountedBase<DynMatcherInterface> {
251 virtual ~DynMatcherInterface() {}
253 /// \brief Returns true if \p DynNode can be matched.
255 /// May bind \p DynNode to an ID via \p Builder, or recurse into
256 /// the AST via \p Finder.
257 virtual bool dynMatches(const ast_type_traits::DynTypedNode &DynNode,
258 ASTMatchFinder *Finder,
259 BoundNodesTreeBuilder *Builder) const = 0;
262 /// \brief Generic interface for matchers on an AST node of type T.
264 /// Implement this if your matcher may need to inspect the children or
265 /// descendants of the node or bind matched nodes to names. If you are
266 /// writing a simple matcher that only inspects properties of the
267 /// current node and doesn't care about its children or descendants,
268 /// implement SingleNodeMatcherInterface instead.
269 template <typename T>
270 class MatcherInterface : public DynMatcherInterface {
272 /// \brief Returns true if 'Node' can be matched.
274 /// May bind 'Node' to an ID via 'Builder', or recurse into
275 /// the AST via 'Finder'.
276 virtual bool matches(const T &Node,
277 ASTMatchFinder *Finder,
278 BoundNodesTreeBuilder *Builder) const = 0;
280 bool dynMatches(const ast_type_traits::DynTypedNode &DynNode,
281 ASTMatchFinder *Finder,
282 BoundNodesTreeBuilder *Builder) const override {
283 return matches(DynNode.getUnchecked<T>(), Finder, Builder);
287 /// \brief Interface for matchers that only evaluate properties on a single
289 template <typename T>
290 class SingleNodeMatcherInterface : public MatcherInterface<T> {
292 /// \brief Returns true if the matcher matches the provided node.
294 /// A subclass must implement this instead of Matches().
295 virtual bool matchesNode(const T &Node) const = 0;
298 /// Implements MatcherInterface::Matches.
299 bool matches(const T &Node,
300 ASTMatchFinder * /* Finder */,
301 BoundNodesTreeBuilder * /* Builder */) const override {
302 return matchesNode(Node);
306 template <typename> class Matcher;
308 /// \brief Matcher that works on a \c DynTypedNode.
310 /// It is constructed from a \c Matcher<T> object and redirects most calls to
311 /// underlying matcher.
312 /// It checks whether the \c DynTypedNode is convertible into the type of the
313 /// underlying matcher and then do the actual match on the actual node, or
314 /// return false if it is not convertible.
315 class DynTypedMatcher {
317 /// \brief Takes ownership of the provided implementation pointer.
318 template <typename T>
319 DynTypedMatcher(MatcherInterface<T> *Implementation)
321 SupportedKind(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()),
322 RestrictKind(SupportedKind), Implementation(Implementation) {}
324 /// \brief Construct from a variadic function.
325 enum VariadicOperator {
326 /// \brief Matches nodes for which all provided matchers match.
328 /// \brief Matches nodes for which at least one of the provided matchers
331 /// \brief Matches nodes for which at least one of the provided matchers
332 /// matches, but doesn't stop at the first match.
334 /// \brief Matches nodes that do not match the provided matcher.
336 /// Uses the variadic matcher interface, but fails if
337 /// InnerMatchers.size() != 1.
340 static DynTypedMatcher
341 constructVariadic(VariadicOperator Op,
342 ast_type_traits::ASTNodeKind SupportedKind,
343 std::vector<DynTypedMatcher> InnerMatchers);
345 /// \brief Get a "true" matcher for \p NodeKind.
347 /// It only checks that the node is of the right kind.
348 static DynTypedMatcher trueMatcher(ast_type_traits::ASTNodeKind NodeKind);
350 void setAllowBind(bool AB) { AllowBind = AB; }
352 /// \brief Check whether this matcher could ever match a node of kind \p Kind.
353 /// \return \c false if this matcher will never match such a node. Otherwise,
355 bool canMatchNodesOfKind(ast_type_traits::ASTNodeKind Kind) const;
357 /// \brief Return a matcher that points to the same implementation, but
358 /// restricts the node types for \p Kind.
359 DynTypedMatcher dynCastTo(const ast_type_traits::ASTNodeKind Kind) const;
361 /// \brief Returns true if the matcher matches the given \c DynNode.
362 bool matches(const ast_type_traits::DynTypedNode &DynNode,
363 ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const;
365 /// \brief Same as matches(), but skips the kind check.
367 /// It is faster, but the caller must ensure the node is valid for the
368 /// kind of this matcher.
369 bool matchesNoKindCheck(const ast_type_traits::DynTypedNode &DynNode,
370 ASTMatchFinder *Finder,
371 BoundNodesTreeBuilder *Builder) const;
373 /// \brief Bind the specified \p ID to the matcher.
374 /// \return A new matcher with the \p ID bound to it if this matcher supports
375 /// binding. Otherwise, returns an empty \c Optional<>.
376 llvm::Optional<DynTypedMatcher> tryBind(StringRef ID) const;
378 /// \brief Returns a unique \p ID for the matcher.
380 /// Casting a Matcher<T> to Matcher<U> creates a matcher that has the
381 /// same \c Implementation pointer, but different \c RestrictKind. We need to
382 /// include both in the ID to make it unique.
384 /// \c MatcherIDType supports operator< and provides strict weak ordering.
385 typedef std::pair<ast_type_traits::ASTNodeKind, uint64_t> MatcherIDType;
386 MatcherIDType getID() const {
387 /// FIXME: Document the requirements this imposes on matcher
388 /// implementations (no new() implementation_ during a Matches()).
389 return std::make_pair(RestrictKind,
390 reinterpret_cast<uint64_t>(Implementation.get()));
393 /// \brief Returns the type this matcher works on.
395 /// \c matches() will always return false unless the node passed is of this
396 /// or a derived type.
397 ast_type_traits::ASTNodeKind getSupportedKind() const {
398 return SupportedKind;
401 /// \brief Returns \c true if the passed \c DynTypedMatcher can be converted
402 /// to a \c Matcher<T>.
404 /// This method verifies that the underlying matcher in \c Other can process
405 /// nodes of types T.
406 template <typename T> bool canConvertTo() const {
407 return canConvertTo(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
409 bool canConvertTo(ast_type_traits::ASTNodeKind To) const;
411 /// \brief Construct a \c Matcher<T> interface around the dynamic matcher.
413 /// This method asserts that \c canConvertTo() is \c true. Callers
414 /// should call \c canConvertTo() first to make sure that \c this is
415 /// compatible with T.
416 template <typename T> Matcher<T> convertTo() const {
417 assert(canConvertTo<T>());
418 return unconditionalConvertTo<T>();
421 /// \brief Same as \c convertTo(), but does not check that the underlying
422 /// matcher can handle a value of T.
424 /// If it is not compatible, then this matcher will never match anything.
425 template <typename T> Matcher<T> unconditionalConvertTo() const;
428 DynTypedMatcher(ast_type_traits::ASTNodeKind SupportedKind,
429 ast_type_traits::ASTNodeKind RestrictKind,
430 IntrusiveRefCntPtr<DynMatcherInterface> Implementation)
432 SupportedKind(SupportedKind),
433 RestrictKind(RestrictKind),
434 Implementation(std::move(Implementation)) {}
437 ast_type_traits::ASTNodeKind SupportedKind;
438 /// \brief A potentially stricter node kind.
440 /// It allows to perform implicit and dynamic cast of matchers without
441 /// needing to change \c Implementation.
442 ast_type_traits::ASTNodeKind RestrictKind;
443 IntrusiveRefCntPtr<DynMatcherInterface> Implementation;
446 /// \brief Wrapper base class for a wrapping matcher.
448 /// This is just a container for a DynTypedMatcher that can be used as a base
449 /// class for another matcher.
450 template <typename T>
451 class WrapperMatcherInterface : public MatcherInterface<T> {
453 explicit WrapperMatcherInterface(DynTypedMatcher &&InnerMatcher)
454 : InnerMatcher(std::move(InnerMatcher)) {}
456 const DynTypedMatcher InnerMatcher;
459 /// \brief Wrapper of a MatcherInterface<T> *that allows copying.
461 /// A Matcher<Base> can be used anywhere a Matcher<Derived> is
462 /// required. This establishes an is-a relationship which is reverse
463 /// to the AST hierarchy. In other words, Matcher<T> is contravariant
464 /// with respect to T. The relationship is built via a type conversion
465 /// operator rather than a type hierarchy to be able to templatize the
466 /// type hierarchy instead of spelling it out.
467 template <typename T>
470 /// \brief Takes ownership of the provided implementation pointer.
471 explicit Matcher(MatcherInterface<T> *Implementation)
472 : Implementation(Implementation) {}
474 /// \brief Implicitly converts \c Other to a Matcher<T>.
476 /// Requires \c T to be derived from \c From.
477 template <typename From>
478 Matcher(const Matcher<From> &Other,
479 typename std::enable_if<std::is_base_of<From, T>::value &&
480 !std::is_same<From, T>::value>::type * = nullptr)
481 : Implementation(restrictMatcher(Other.Implementation)) {
482 assert(Implementation.getSupportedKind().isSame(
483 ast_type_traits::ASTNodeKind::getFromNodeKind<T>()));
486 /// \brief Implicitly converts \c Matcher<Type> to \c Matcher<QualType>.
488 /// The resulting matcher is not strict, i.e. ignores qualifiers.
489 template <typename TypeT>
490 Matcher(const Matcher<TypeT> &Other,
491 typename std::enable_if<
492 std::is_same<T, QualType>::value &&
493 std::is_same<TypeT, Type>::value>::type* = nullptr)
494 : Implementation(new TypeToQualType<TypeT>(Other)) {}
496 /// \brief Convert \c this into a \c Matcher<T> by applying dyn_cast<> to the
498 /// \c To must be a base class of \c T.
499 template <typename To>
500 Matcher<To> dynCastTo() const {
501 static_assert(std::is_base_of<To, T>::value, "Invalid dynCast call.");
502 return Matcher<To>(Implementation);
505 /// \brief Forwards the call to the underlying MatcherInterface<T> pointer.
506 bool matches(const T &Node,
507 ASTMatchFinder *Finder,
508 BoundNodesTreeBuilder *Builder) const {
509 return Implementation.matches(ast_type_traits::DynTypedNode::create(Node),
513 /// \brief Returns an ID that uniquely identifies the matcher.
514 DynTypedMatcher::MatcherIDType getID() const {
515 return Implementation.getID();
518 /// \brief Extract the dynamic matcher.
520 /// The returned matcher keeps the same restrictions as \c this and remembers
521 /// that it is meant to support nodes of type \c T.
522 operator DynTypedMatcher() const { return Implementation; }
524 /// \brief Allows the conversion of a \c Matcher<Type> to a \c
525 /// Matcher<QualType>.
527 /// Depending on the constructor argument, the matcher is either strict, i.e.
528 /// does only matches in the absence of qualifiers, or not, i.e. simply
529 /// ignores any qualifiers.
530 template <typename TypeT>
531 class TypeToQualType : public WrapperMatcherInterface<QualType> {
533 TypeToQualType(const Matcher<TypeT> &InnerMatcher)
534 : TypeToQualType::WrapperMatcherInterface(InnerMatcher) {}
536 bool matches(const QualType &Node, ASTMatchFinder *Finder,
537 BoundNodesTreeBuilder *Builder) const override {
540 return this->InnerMatcher.matches(
541 ast_type_traits::DynTypedNode::create(*Node), Finder, Builder);
546 // For Matcher<T> <=> Matcher<U> conversions.
547 template <typename U> friend class Matcher;
548 // For DynTypedMatcher::unconditionalConvertTo<T>.
549 friend class DynTypedMatcher;
551 static DynTypedMatcher restrictMatcher(const DynTypedMatcher &Other) {
552 return Other.dynCastTo(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
555 explicit Matcher(const DynTypedMatcher &Implementation)
556 : Implementation(restrictMatcher(Implementation)) {
557 assert(this->Implementation.getSupportedKind()
558 .isSame(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()));
561 DynTypedMatcher Implementation;
564 /// \brief A convenient helper for creating a Matcher<T> without specifying
565 /// the template type argument.
566 template <typename T>
567 inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) {
568 return Matcher<T>(Implementation);
571 /// \brief Specialization of the conversion functions for QualType.
573 /// This specialization provides the Matcher<Type>->Matcher<QualType>
574 /// conversion that the static API does.
576 inline Matcher<QualType> DynTypedMatcher::convertTo<QualType>() const {
577 assert(canConvertTo<QualType>());
578 const ast_type_traits::ASTNodeKind SourceKind = getSupportedKind();
579 if (SourceKind.isSame(
580 ast_type_traits::ASTNodeKind::getFromNodeKind<Type>())) {
581 // We support implicit conversion from Matcher<Type> to Matcher<QualType>
582 return unconditionalConvertTo<Type>();
584 return unconditionalConvertTo<QualType>();
587 /// \brief Finds the first node in a range that matches the given matcher.
588 template <typename MatcherT, typename IteratorT>
589 bool matchesFirstInRange(const MatcherT &Matcher, IteratorT Start,
590 IteratorT End, ASTMatchFinder *Finder,
591 BoundNodesTreeBuilder *Builder) {
592 for (IteratorT I = Start; I != End; ++I) {
593 BoundNodesTreeBuilder Result(*Builder);
594 if (Matcher.matches(*I, Finder, &Result)) {
595 *Builder = std::move(Result);
602 /// \brief Finds the first node in a pointer range that matches the given
604 template <typename MatcherT, typename IteratorT>
605 bool matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start,
606 IteratorT End, ASTMatchFinder *Finder,
607 BoundNodesTreeBuilder *Builder) {
608 for (IteratorT I = Start; I != End; ++I) {
609 BoundNodesTreeBuilder Result(*Builder);
610 if (Matcher.matches(**I, Finder, &Result)) {
611 *Builder = std::move(Result);
618 // Metafunction to determine if type T has a member called getDecl.
619 template <typename Ty>
624 template <typename Inner>
625 static yes& test(Inner *I, decltype(I->getDecl()) * = nullptr);
628 static no& test(...);
631 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
634 /// \brief Matches overloaded operators with a specific name.
636 /// The type argument ArgT is not used by this matcher but is used by
637 /// PolymorphicMatcherWithParam1 and should be StringRef.
638 template <typename T, typename ArgT>
639 class HasOverloadedOperatorNameMatcher : public SingleNodeMatcherInterface<T> {
640 static_assert(std::is_same<T, CXXOperatorCallExpr>::value ||
641 std::is_base_of<FunctionDecl, T>::value,
642 "unsupported class for matcher");
643 static_assert(std::is_same<ArgT, StringRef>::value,
644 "argument type must be StringRef");
647 explicit HasOverloadedOperatorNameMatcher(const StringRef Name)
648 : SingleNodeMatcherInterface<T>(), Name(Name) {}
650 bool matchesNode(const T &Node) const override {
651 return matchesSpecialized(Node);
656 /// \brief CXXOperatorCallExpr exist only for calls to overloaded operators
657 /// so this function returns true if the call is to an operator of the given
659 bool matchesSpecialized(const CXXOperatorCallExpr &Node) const {
660 return getOperatorSpelling(Node.getOperator()) == Name;
663 /// \brief Returns true only if CXXMethodDecl represents an overloaded
664 /// operator and has the given operator name.
665 bool matchesSpecialized(const FunctionDecl &Node) const {
666 return Node.isOverloadedOperator() &&
667 getOperatorSpelling(Node.getOverloadedOperator()) == Name;
673 /// \brief Matches named declarations with a specific name.
675 /// See \c hasName() and \c hasAnyName() in ASTMatchers.h for details.
676 class HasNameMatcher : public SingleNodeMatcherInterface<NamedDecl> {
678 explicit HasNameMatcher(std::vector<std::string> Names);
680 bool matchesNode(const NamedDecl &Node) const override;
683 /// \brief Unqualified match routine.
685 /// It is much faster than the full match, but it only works for unqualified
687 bool matchesNodeUnqualified(const NamedDecl &Node) const;
689 /// \brief Full match routine
691 /// Fast implementation for the simple case of a named declaration at
692 /// namespace or RecordDecl scope.
693 /// It is slower than matchesNodeUnqualified, but faster than
694 /// matchesNodeFullSlow.
695 bool matchesNodeFullFast(const NamedDecl &Node) const;
697 /// \brief Full match routine
699 /// It generates the fully qualified name of the declaration (which is
700 /// expensive) before trying to match.
701 /// It is slower but simple and works on all cases.
702 bool matchesNodeFullSlow(const NamedDecl &Node) const;
704 const bool UseUnqualifiedMatch;
705 const std::vector<std::string> Names;
708 /// \brief Trampoline function to use VariadicFunction<> to construct a
710 Matcher<NamedDecl> hasAnyNameFunc(ArrayRef<const StringRef *> NameRefs);
712 /// \brief Matches declarations for QualType and CallExpr.
714 /// Type argument DeclMatcherT is required by PolymorphicMatcherWithParam1 but
715 /// not actually used.
716 template <typename T, typename DeclMatcherT>
717 class HasDeclarationMatcher : public WrapperMatcherInterface<T> {
718 static_assert(std::is_same<DeclMatcherT, Matcher<Decl>>::value,
719 "instantiated with wrong types");
722 explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher)
723 : HasDeclarationMatcher::WrapperMatcherInterface(InnerMatcher) {}
725 bool matches(const T &Node, ASTMatchFinder *Finder,
726 BoundNodesTreeBuilder *Builder) const override {
727 return matchesSpecialized(Node, Finder, Builder);
731 /// \brief If getDecl exists as a member of U, returns whether the inner
732 /// matcher matches Node.getDecl().
733 template <typename U>
734 bool matchesSpecialized(
735 const U &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder,
736 typename std::enable_if<has_getDecl<U>::value, int>::type = 0) const {
737 return matchesDecl(Node.getDecl(), Finder, Builder);
740 /// \brief Extracts the TagDecl of a QualType and returns whether the inner
741 /// matcher matches on it.
742 bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder,
743 BoundNodesTreeBuilder *Builder) const {
747 if (auto *TD = Node->getAsTagDecl())
748 return matchesDecl(TD, Finder, Builder);
749 else if (auto *TT = Node->getAs<TypedefType>())
750 return matchesDecl(TT->getDecl(), Finder, Builder);
751 // Do not use getAs<TemplateTypeParmType> instead of the direct dyn_cast.
752 // Calling getAs will return the canonical type, but that type does not
753 // store a TemplateTypeParmDecl. We *need* the uncanonical type, if it is
754 // available, and using dyn_cast ensures that.
755 else if (auto *TTP = dyn_cast<TemplateTypeParmType>(Node.getTypePtr()))
756 return matchesDecl(TTP->getDecl(), Finder, Builder);
757 else if (auto *OCIT = Node->getAs<ObjCInterfaceType>())
758 return matchesDecl(OCIT->getDecl(), Finder, Builder);
759 else if (auto *UUT = Node->getAs<UnresolvedUsingType>())
760 return matchesDecl(UUT->getDecl(), Finder, Builder);
761 else if (auto *ICNT = Node->getAs<InjectedClassNameType>())
762 return matchesDecl(ICNT->getDecl(), Finder, Builder);
766 /// \brief Gets the TemplateDecl from a TemplateSpecializationType
767 /// and returns whether the inner matches on it.
768 bool matchesSpecialized(const TemplateSpecializationType &Node,
769 ASTMatchFinder *Finder,
770 BoundNodesTreeBuilder *Builder) const {
771 return matchesDecl(Node.getTemplateName().getAsTemplateDecl(),
775 /// \brief Extracts the Decl of the callee of a CallExpr and returns whether
776 /// the inner matcher matches on it.
777 bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder,
778 BoundNodesTreeBuilder *Builder) const {
779 return matchesDecl(Node.getCalleeDecl(), Finder, Builder);
782 /// \brief Extracts the Decl of the constructor call and returns whether the
783 /// inner matcher matches on it.
784 bool matchesSpecialized(const CXXConstructExpr &Node,
785 ASTMatchFinder *Finder,
786 BoundNodesTreeBuilder *Builder) const {
787 return matchesDecl(Node.getConstructor(), Finder, Builder);
790 /// \brief Extracts the operator new of the new call and returns whether the
791 /// inner matcher matches on it.
792 bool matchesSpecialized(const CXXNewExpr &Node,
793 ASTMatchFinder *Finder,
794 BoundNodesTreeBuilder *Builder) const {
795 return matchesDecl(Node.getOperatorNew(), Finder, Builder);
798 /// \brief Extracts the \c ValueDecl a \c MemberExpr refers to and returns
799 /// whether the inner matcher matches on it.
800 bool matchesSpecialized(const MemberExpr &Node,
801 ASTMatchFinder *Finder,
802 BoundNodesTreeBuilder *Builder) const {
803 return matchesDecl(Node.getMemberDecl(), Finder, Builder);
806 /// \brief Extracts the \c LabelDecl a \c AddrLabelExpr refers to and returns
807 /// whether the inner matcher matches on it.
808 bool matchesSpecialized(const AddrLabelExpr &Node,
809 ASTMatchFinder *Finder,
810 BoundNodesTreeBuilder *Builder) const {
811 return matchesDecl(Node.getLabel(), Finder, Builder);
814 /// \brief Returns whether the inner matcher \c Node. Returns false if \c Node
816 bool matchesDecl(const Decl *Node, ASTMatchFinder *Finder,
817 BoundNodesTreeBuilder *Builder) const {
818 return Node != nullptr &&
819 this->InnerMatcher.matches(
820 ast_type_traits::DynTypedNode::create(*Node), Finder, Builder);
824 /// \brief IsBaseType<T>::value is true if T is a "base" type in the AST
825 /// node class hierarchies.
826 template <typename T>
828 static const bool value =
829 std::is_same<T, Decl>::value ||
830 std::is_same<T, Stmt>::value ||
831 std::is_same<T, QualType>::value ||
832 std::is_same<T, Type>::value ||
833 std::is_same<T, TypeLoc>::value ||
834 std::is_same<T, NestedNameSpecifier>::value ||
835 std::is_same<T, NestedNameSpecifierLoc>::value ||
836 std::is_same<T, CXXCtorInitializer>::value;
838 template <typename T>
839 const bool IsBaseType<T>::value;
841 /// \brief Interface that allows matchers to traverse the AST.
842 /// FIXME: Find a better name.
844 /// This provides three entry methods for each base node type in the AST:
845 /// - \c matchesChildOf:
846 /// Matches a matcher on every child node of the given node. Returns true
847 /// if at least one child node could be matched.
848 /// - \c matchesDescendantOf:
849 /// Matches a matcher on all descendant nodes of the given node. Returns true
850 /// if at least one descendant matched.
851 /// - \c matchesAncestorOf:
852 /// Matches a matcher on all ancestors of the given node. Returns true if
853 /// at least one ancestor matched.
855 /// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal.
856 /// In the future, we want to implement this for all nodes for which it makes
857 /// sense. In the case of matchesAncestorOf, we'll want to implement it for
858 /// all nodes, as all nodes have ancestors.
859 class ASTMatchFinder {
861 /// \brief Defines how we descend a level in the AST when we pass
862 /// through expressions.
864 /// Will traverse any child nodes.
866 /// Will not traverse implicit casts and parentheses.
867 TK_IgnoreImplicitCastsAndParentheses
870 /// \brief Defines how bindings are processed on recursive matches.
872 /// Stop at the first match and only bind the first match.
874 /// Create results for all combinations of bindings that match.
878 /// \brief Defines which ancestors are considered for a match.
879 enum AncestorMatchMode {
882 /// Direct parent only.
886 virtual ~ASTMatchFinder() {}
888 /// \brief Returns true if the given class is directly or indirectly derived
889 /// from a base type matching \c base.
891 /// A class is considered to be also derived from itself.
892 virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
893 const Matcher<NamedDecl> &Base,
894 BoundNodesTreeBuilder *Builder) = 0;
896 template <typename T>
897 bool matchesChildOf(const T &Node,
898 const DynTypedMatcher &Matcher,
899 BoundNodesTreeBuilder *Builder,
900 TraversalKind Traverse,
902 static_assert(std::is_base_of<Decl, T>::value ||
903 std::is_base_of<Stmt, T>::value ||
904 std::is_base_of<NestedNameSpecifier, T>::value ||
905 std::is_base_of<NestedNameSpecifierLoc, T>::value ||
906 std::is_base_of<TypeLoc, T>::value ||
907 std::is_base_of<QualType, T>::value,
908 "unsupported type for recursive matching");
909 return matchesChildOf(ast_type_traits::DynTypedNode::create(Node),
910 Matcher, Builder, Traverse, Bind);
913 template <typename T>
914 bool matchesDescendantOf(const T &Node,
915 const DynTypedMatcher &Matcher,
916 BoundNodesTreeBuilder *Builder,
918 static_assert(std::is_base_of<Decl, T>::value ||
919 std::is_base_of<Stmt, T>::value ||
920 std::is_base_of<NestedNameSpecifier, T>::value ||
921 std::is_base_of<NestedNameSpecifierLoc, T>::value ||
922 std::is_base_of<TypeLoc, T>::value ||
923 std::is_base_of<QualType, T>::value,
924 "unsupported type for recursive matching");
925 return matchesDescendantOf(ast_type_traits::DynTypedNode::create(Node),
926 Matcher, Builder, Bind);
929 // FIXME: Implement support for BindKind.
930 template <typename T>
931 bool matchesAncestorOf(const T &Node,
932 const DynTypedMatcher &Matcher,
933 BoundNodesTreeBuilder *Builder,
934 AncestorMatchMode MatchMode) {
935 static_assert(std::is_base_of<Decl, T>::value ||
936 std::is_base_of<NestedNameSpecifierLoc, T>::value ||
937 std::is_base_of<Stmt, T>::value ||
938 std::is_base_of<TypeLoc, T>::value,
939 "type not allowed for recursive matching");
940 return matchesAncestorOf(ast_type_traits::DynTypedNode::create(Node),
941 Matcher, Builder, MatchMode);
944 virtual ASTContext &getASTContext() const = 0;
947 virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node,
948 const DynTypedMatcher &Matcher,
949 BoundNodesTreeBuilder *Builder,
950 TraversalKind Traverse,
953 virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node,
954 const DynTypedMatcher &Matcher,
955 BoundNodesTreeBuilder *Builder,
958 virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node,
959 const DynTypedMatcher &Matcher,
960 BoundNodesTreeBuilder *Builder,
961 AncestorMatchMode MatchMode) = 0;
964 /// \brief A type-list implementation.
966 /// A "linked list" of types, accessible by using the ::head and ::tail
968 template <typename... Ts> struct TypeList {}; // Empty sentinel type list.
970 template <typename T1, typename... Ts> struct TypeList<T1, Ts...> {
971 /// \brief The first type on the list.
974 /// \brief A sublist with the tail. ie everything but the head.
976 /// This type is used to do recursion. TypeList<>/EmptyTypeList indicates the
978 typedef TypeList<Ts...> tail;
981 /// \brief The empty type list.
982 typedef TypeList<> EmptyTypeList;
984 /// \brief Helper meta-function to determine if some type \c T is present or
985 /// a parent type in the list.
986 template <typename AnyTypeList, typename T>
987 struct TypeListContainsSuperOf {
988 static const bool value =
989 std::is_base_of<typename AnyTypeList::head, T>::value ||
990 TypeListContainsSuperOf<typename AnyTypeList::tail, T>::value;
992 template <typename T>
993 struct TypeListContainsSuperOf<EmptyTypeList, T> {
994 static const bool value = false;
997 /// \brief A "type list" that contains all types.
999 /// Useful for matchers like \c anything and \c unless.
1000 typedef TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc,
1001 QualType, Type, TypeLoc, CXXCtorInitializer> AllNodeBaseTypes;
1003 /// \brief Helper meta-function to extract the argument out of a function of
1006 /// See AST_POLYMORPHIC_SUPPORTED_TYPES for details.
1007 template <class T> struct ExtractFunctionArgMeta;
1008 template <class T> struct ExtractFunctionArgMeta<void(T)> {
1012 /// \brief Default type lists for ArgumentAdaptingMatcher matchers.
1013 typedef AllNodeBaseTypes AdaptativeDefaultFromTypes;
1014 typedef TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc,
1015 TypeLoc, QualType> AdaptativeDefaultToTypes;
1017 /// \brief All types that are supported by HasDeclarationMatcher above.
1018 typedef TypeList<CallExpr, CXXConstructExpr, CXXNewExpr, DeclRefExpr, EnumType,
1019 InjectedClassNameType, LabelStmt, AddrLabelExpr, MemberExpr,
1020 QualType, RecordType, TagType, TemplateSpecializationType,
1021 TemplateTypeParmType, TypedefType, UnresolvedUsingType>
1022 HasDeclarationSupportedTypes;
1024 /// \brief Converts a \c Matcher<T> to a matcher of desired type \c To by
1025 /// "adapting" a \c To into a \c T.
1027 /// The \c ArgumentAdapterT argument specifies how the adaptation is done.
1030 /// \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher);
1031 /// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher
1032 /// that is convertible into any matcher of type \c To by constructing
1033 /// \c HasMatcher<To, T>(InnerMatcher).
1035 /// If a matcher does not need knowledge about the inner type, prefer to use
1036 /// PolymorphicMatcherWithParam1.
1037 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
1038 typename FromTypes = AdaptativeDefaultFromTypes,
1039 typename ToTypes = AdaptativeDefaultToTypes>
1040 struct ArgumentAdaptingMatcherFunc {
1041 template <typename T> class Adaptor {
1043 explicit Adaptor(const Matcher<T> &InnerMatcher)
1044 : InnerMatcher(InnerMatcher) {}
1046 typedef ToTypes ReturnTypes;
1048 template <typename To> operator Matcher<To>() const {
1049 return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher));
1053 const Matcher<T> InnerMatcher;
1056 template <typename T>
1057 static Adaptor<T> create(const Matcher<T> &InnerMatcher) {
1058 return Adaptor<T>(InnerMatcher);
1061 template <typename T>
1062 Adaptor<T> operator()(const Matcher<T> &InnerMatcher) const {
1063 return create(InnerMatcher);
1067 /// \brief A PolymorphicMatcherWithParamN<MatcherT, P1, ..., PN> object can be
1068 /// created from N parameters p1, ..., pN (of type P1, ..., PN) and
1069 /// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN)
1070 /// can be constructed.
1073 /// - PolymorphicMatcherWithParam0<IsDefinitionMatcher>()
1074 /// creates an object that can be used as a Matcher<T> for any type T
1075 /// where an IsDefinitionMatcher<T>() can be constructed.
1076 /// - PolymorphicMatcherWithParam1<ValueEqualsMatcher, int>(42)
1077 /// creates an object that can be used as a Matcher<T> for any type T
1078 /// where a ValueEqualsMatcher<T, int>(42) can be constructed.
1079 template <template <typename T> class MatcherT,
1080 typename ReturnTypesF = void(AllNodeBaseTypes)>
1081 class PolymorphicMatcherWithParam0 {
1083 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
1084 template <typename T>
1085 operator Matcher<T>() const {
1086 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
1087 "right polymorphic conversion");
1088 return Matcher<T>(new MatcherT<T>());
1092 template <template <typename T, typename P1> class MatcherT,
1094 typename ReturnTypesF = void(AllNodeBaseTypes)>
1095 class PolymorphicMatcherWithParam1 {
1097 explicit PolymorphicMatcherWithParam1(const P1 &Param1)
1100 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
1102 template <typename T>
1103 operator Matcher<T>() const {
1104 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
1105 "right polymorphic conversion");
1106 return Matcher<T>(new MatcherT<T, P1>(Param1));
1113 template <template <typename T, typename P1, typename P2> class MatcherT,
1114 typename P1, typename P2,
1115 typename ReturnTypesF = void(AllNodeBaseTypes)>
1116 class PolymorphicMatcherWithParam2 {
1118 PolymorphicMatcherWithParam2(const P1 &Param1, const P2 &Param2)
1119 : Param1(Param1), Param2(Param2) {}
1121 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
1123 template <typename T>
1124 operator Matcher<T>() const {
1125 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
1126 "right polymorphic conversion");
1127 return Matcher<T>(new MatcherT<T, P1, P2>(Param1, Param2));
1135 /// \brief Matches any instance of the given NodeType.
1137 /// This is useful when a matcher syntactically requires a child matcher,
1138 /// but the context doesn't care. See for example: anything().
1141 typedef AllNodeBaseTypes ReturnTypes;
1143 template <typename T>
1144 operator Matcher<T>() const {
1145 return DynTypedMatcher::trueMatcher(
1146 ast_type_traits::ASTNodeKind::getFromNodeKind<T>())
1147 .template unconditionalConvertTo<T>();
1151 /// \brief A Matcher that allows binding the node it matches to an id.
1153 /// BindableMatcher provides a \a bind() method that allows binding the
1154 /// matched node to an id if the match was successful.
1155 template <typename T>
1156 class BindableMatcher : public Matcher<T> {
1158 explicit BindableMatcher(const Matcher<T> &M) : Matcher<T>(M) {}
1159 explicit BindableMatcher(MatcherInterface<T> *Implementation)
1160 : Matcher<T>(Implementation) {}
1162 /// \brief Returns a matcher that will bind the matched node on a match.
1164 /// The returned matcher is equivalent to this matcher, but will
1165 /// bind the matched node on a match.
1166 Matcher<T> bind(StringRef ID) const {
1167 return DynTypedMatcher(*this)
1169 ->template unconditionalConvertTo<T>();
1172 /// \brief Same as Matcher<T>'s conversion operator, but enables binding on
1173 /// the returned matcher.
1174 operator DynTypedMatcher() const {
1175 DynTypedMatcher Result = static_cast<const Matcher<T>&>(*this);
1176 Result.setAllowBind(true);
1181 /// \brief Matches nodes of type T that have child nodes of type ChildT for
1182 /// which a specified child matcher matches.
1184 /// ChildT must be an AST base type.
1185 template <typename T, typename ChildT>
1186 class HasMatcher : public WrapperMatcherInterface<T> {
1189 explicit HasMatcher(const Matcher<ChildT> &ChildMatcher)
1190 : HasMatcher::WrapperMatcherInterface(ChildMatcher) {}
1192 bool matches(const T &Node, ASTMatchFinder *Finder,
1193 BoundNodesTreeBuilder *Builder) const override {
1194 return Finder->matchesChildOf(Node, this->InnerMatcher, Builder,
1195 ASTMatchFinder::TK_AsIs,
1196 ASTMatchFinder::BK_First);
1200 /// \brief Matches nodes of type T that have child nodes of type ChildT for
1201 /// which a specified child matcher matches. ChildT must be an AST base
1203 /// As opposed to the HasMatcher, the ForEachMatcher will produce a match
1204 /// for each child that matches.
1205 template <typename T, typename ChildT>
1206 class ForEachMatcher : public WrapperMatcherInterface<T> {
1207 static_assert(IsBaseType<ChildT>::value,
1208 "for each only accepts base type matcher");
1211 explicit ForEachMatcher(const Matcher<ChildT> &ChildMatcher)
1212 : ForEachMatcher::WrapperMatcherInterface(ChildMatcher) {}
1214 bool matches(const T& Node, ASTMatchFinder* Finder,
1215 BoundNodesTreeBuilder* Builder) const override {
1216 return Finder->matchesChildOf(
1217 Node, this->InnerMatcher, Builder,
1218 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
1219 ASTMatchFinder::BK_All);
1223 /// \brief VariadicOperatorMatcher related types.
1226 /// \brief Polymorphic matcher object that uses a \c
1227 /// DynTypedMatcher::VariadicOperator operator.
1229 /// Input matchers can have any type (including other polymorphic matcher
1230 /// types), and the actual Matcher<T> is generated on demand with an implicit
1231 /// coversion operator.
1232 template <typename... Ps> class VariadicOperatorMatcher {
1234 VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op, Ps &&... Params)
1235 : Op(Op), Params(std::forward<Ps>(Params)...) {}
1237 template <typename T> operator Matcher<T>() const {
1238 return DynTypedMatcher::constructVariadic(
1239 Op, ast_type_traits::ASTNodeKind::getFromNodeKind<T>(),
1240 getMatchers<T>(llvm::index_sequence_for<Ps...>()))
1241 .template unconditionalConvertTo<T>();
1245 // Helper method to unpack the tuple into a vector.
1246 template <typename T, std::size_t... Is>
1247 std::vector<DynTypedMatcher> getMatchers(llvm::index_sequence<Is...>) const {
1248 return {Matcher<T>(std::get<Is>(Params))...};
1251 const DynTypedMatcher::VariadicOperator Op;
1252 std::tuple<Ps...> Params;
1255 /// \brief Overloaded function object to generate VariadicOperatorMatcher
1256 /// objects from arbitrary matchers.
1257 template <unsigned MinCount, unsigned MaxCount>
1258 struct VariadicOperatorMatcherFunc {
1259 DynTypedMatcher::VariadicOperator Op;
1261 template <typename... Ms>
1262 VariadicOperatorMatcher<Ms...> operator()(Ms &&... Ps) const {
1263 static_assert(MinCount <= sizeof...(Ms) && sizeof...(Ms) <= MaxCount,
1264 "invalid number of parameters for variadic matcher");
1265 return VariadicOperatorMatcher<Ms...>(Op, std::forward<Ms>(Ps)...);
1271 template <typename T>
1272 inline Matcher<T> DynTypedMatcher::unconditionalConvertTo() const {
1273 return Matcher<T>(*this);
1276 /// \brief Creates a Matcher<T> that matches if all inner matchers match.
1277 template<typename T>
1278 BindableMatcher<T> makeAllOfComposite(
1279 ArrayRef<const Matcher<T> *> InnerMatchers) {
1280 // For the size() == 0 case, we return a "true" matcher.
1281 if (InnerMatchers.size() == 0) {
1282 return BindableMatcher<T>(TrueMatcher());
1284 // For the size() == 1 case, we simply return that one matcher.
1285 // No need to wrap it in a variadic operation.
1286 if (InnerMatchers.size() == 1) {
1287 return BindableMatcher<T>(*InnerMatchers[0]);
1290 typedef llvm::pointee_iterator<const Matcher<T> *const *> PI;
1291 std::vector<DynTypedMatcher> DynMatchers(PI(InnerMatchers.begin()),
1292 PI(InnerMatchers.end()));
1293 return BindableMatcher<T>(
1294 DynTypedMatcher::constructVariadic(
1295 DynTypedMatcher::VO_AllOf,
1296 ast_type_traits::ASTNodeKind::getFromNodeKind<T>(),
1297 std::move(DynMatchers))
1298 .template unconditionalConvertTo<T>());
1301 /// \brief Creates a Matcher<T> that matches if
1302 /// T is dyn_cast'able into InnerT and all inner matchers match.
1304 /// Returns BindableMatcher, as matchers that use dyn_cast have
1305 /// the same object both to match on and to run submatchers on,
1306 /// so there is no ambiguity with what gets bound.
1307 template<typename T, typename InnerT>
1308 BindableMatcher<T> makeDynCastAllOfComposite(
1309 ArrayRef<const Matcher<InnerT> *> InnerMatchers) {
1310 return BindableMatcher<T>(
1311 makeAllOfComposite(InnerMatchers).template dynCastTo<T>());
1314 /// \brief Matches nodes of type T that have at least one descendant node of
1315 /// type DescendantT for which the given inner matcher matches.
1317 /// DescendantT must be an AST base type.
1318 template <typename T, typename DescendantT>
1319 class HasDescendantMatcher : public WrapperMatcherInterface<T> {
1320 static_assert(IsBaseType<DescendantT>::value,
1321 "has descendant only accepts base type matcher");
1324 explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher)
1325 : HasDescendantMatcher::WrapperMatcherInterface(DescendantMatcher) {}
1327 bool matches(const T &Node, ASTMatchFinder *Finder,
1328 BoundNodesTreeBuilder *Builder) const override {
1329 return Finder->matchesDescendantOf(Node, this->InnerMatcher, Builder,
1330 ASTMatchFinder::BK_First);
1334 /// \brief Matches nodes of type \c T that have a parent node of type \c ParentT
1335 /// for which the given inner matcher matches.
1337 /// \c ParentT must be an AST base type.
1338 template <typename T, typename ParentT>
1339 class HasParentMatcher : public WrapperMatcherInterface<T> {
1340 static_assert(IsBaseType<ParentT>::value,
1341 "has parent only accepts base type matcher");
1344 explicit HasParentMatcher(const Matcher<ParentT> &ParentMatcher)
1345 : HasParentMatcher::WrapperMatcherInterface(ParentMatcher) {}
1347 bool matches(const T &Node, ASTMatchFinder *Finder,
1348 BoundNodesTreeBuilder *Builder) const override {
1349 return Finder->matchesAncestorOf(Node, this->InnerMatcher, Builder,
1350 ASTMatchFinder::AMM_ParentOnly);
1354 /// \brief Matches nodes of type \c T that have at least one ancestor node of
1355 /// type \c AncestorT for which the given inner matcher matches.
1357 /// \c AncestorT must be an AST base type.
1358 template <typename T, typename AncestorT>
1359 class HasAncestorMatcher : public WrapperMatcherInterface<T> {
1360 static_assert(IsBaseType<AncestorT>::value,
1361 "has ancestor only accepts base type matcher");
1364 explicit HasAncestorMatcher(const Matcher<AncestorT> &AncestorMatcher)
1365 : HasAncestorMatcher::WrapperMatcherInterface(AncestorMatcher) {}
1367 bool matches(const T &Node, ASTMatchFinder *Finder,
1368 BoundNodesTreeBuilder *Builder) const override {
1369 return Finder->matchesAncestorOf(Node, this->InnerMatcher, Builder,
1370 ASTMatchFinder::AMM_All);
1374 /// \brief Matches nodes of type T that have at least one descendant node of
1375 /// type DescendantT for which the given inner matcher matches.
1377 /// DescendantT must be an AST base type.
1378 /// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match
1379 /// for each descendant node that matches instead of only for the first.
1380 template <typename T, typename DescendantT>
1381 class ForEachDescendantMatcher : public WrapperMatcherInterface<T> {
1382 static_assert(IsBaseType<DescendantT>::value,
1383 "for each descendant only accepts base type matcher");
1386 explicit ForEachDescendantMatcher(
1387 const Matcher<DescendantT> &DescendantMatcher)
1388 : ForEachDescendantMatcher::WrapperMatcherInterface(DescendantMatcher) {}
1390 bool matches(const T &Node, ASTMatchFinder *Finder,
1391 BoundNodesTreeBuilder *Builder) const override {
1392 return Finder->matchesDescendantOf(Node, this->InnerMatcher, Builder,
1393 ASTMatchFinder::BK_All);
1397 /// \brief Matches on nodes that have a getValue() method if getValue() equals
1398 /// the value the ValueEqualsMatcher was constructed with.
1399 template <typename T, typename ValueT>
1400 class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> {
1401 static_assert(std::is_base_of<CharacterLiteral, T>::value ||
1402 std::is_base_of<CXXBoolLiteralExpr, T>::value ||
1403 std::is_base_of<FloatingLiteral, T>::value ||
1404 std::is_base_of<IntegerLiteral, T>::value,
1405 "the node must have a getValue method");
1408 explicit ValueEqualsMatcher(const ValueT &ExpectedValue)
1409 : ExpectedValue(ExpectedValue) {}
1411 bool matchesNode(const T &Node) const override {
1412 return Node.getValue() == ExpectedValue;
1416 const ValueT ExpectedValue;
1419 /// \brief Template specializations to easily write matchers for floating point
1422 inline bool ValueEqualsMatcher<FloatingLiteral, double>::matchesNode(
1423 const FloatingLiteral &Node) const {
1424 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle())
1425 return Node.getValue().convertToFloat() == ExpectedValue;
1426 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble())
1427 return Node.getValue().convertToDouble() == ExpectedValue;
1431 inline bool ValueEqualsMatcher<FloatingLiteral, float>::matchesNode(
1432 const FloatingLiteral &Node) const {
1433 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle())
1434 return Node.getValue().convertToFloat() == ExpectedValue;
1435 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble())
1436 return Node.getValue().convertToDouble() == ExpectedValue;
1440 inline bool ValueEqualsMatcher<FloatingLiteral, llvm::APFloat>::matchesNode(
1441 const FloatingLiteral &Node) const {
1442 return ExpectedValue.compare(Node.getValue()) == llvm::APFloat::cmpEqual;
1445 /// \brief A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a
1446 /// variadic functor that takes a number of Matcher<TargetT> and returns a
1447 /// Matcher<SourceT> that matches TargetT nodes that are matched by all of the
1448 /// given matchers, if SourceT can be dynamically casted into TargetT.
1451 /// const VariadicDynCastAllOfMatcher<
1452 /// Decl, CXXRecordDecl> record;
1453 /// Creates a functor record(...) that creates a Matcher<Decl> given
1454 /// a variable number of arguments of type Matcher<CXXRecordDecl>.
1455 /// The returned matcher matches if the given Decl can by dynamically
1456 /// casted to CXXRecordDecl and all given matchers match.
1457 template <typename SourceT, typename TargetT>
1458 class VariadicDynCastAllOfMatcher
1459 : public VariadicFunction<BindableMatcher<SourceT>, Matcher<TargetT>,
1460 makeDynCastAllOfComposite<SourceT, TargetT>> {
1462 VariadicDynCastAllOfMatcher() {}
1465 /// \brief A \c VariadicAllOfMatcher<T> object is a variadic functor that takes
1466 /// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T
1467 /// nodes that are matched by all of the given matchers.
1470 /// const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
1471 /// Creates a functor nestedNameSpecifier(...) that creates a
1472 /// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type
1473 /// \c Matcher<NestedNameSpecifier>.
1474 /// The returned matcher matches if all given matchers match.
1475 template <typename T>
1476 class VariadicAllOfMatcher
1477 : public VariadicFunction<BindableMatcher<T>, Matcher<T>,
1478 makeAllOfComposite<T>> {
1480 VariadicAllOfMatcher() {}
1483 /// \brief Matches nodes of type \c TLoc for which the inner
1484 /// \c Matcher<T> matches.
1485 template <typename TLoc, typename T>
1486 class LocMatcher : public WrapperMatcherInterface<TLoc> {
1488 explicit LocMatcher(const Matcher<T> &InnerMatcher)
1489 : LocMatcher::WrapperMatcherInterface(InnerMatcher) {}
1491 bool matches(const TLoc &Node, ASTMatchFinder *Finder,
1492 BoundNodesTreeBuilder *Builder) const override {
1495 return this->InnerMatcher.matches(extract(Node), Finder, Builder);
1499 static ast_type_traits::DynTypedNode
1500 extract(const NestedNameSpecifierLoc &Loc) {
1501 return ast_type_traits::DynTypedNode::create(*Loc.getNestedNameSpecifier());
1505 /// \brief Matches \c TypeLocs based on an inner matcher matching a certain
1508 /// Used to implement the \c loc() matcher.
1509 class TypeLocTypeMatcher : public WrapperMatcherInterface<TypeLoc> {
1511 explicit TypeLocTypeMatcher(const Matcher<QualType> &InnerMatcher)
1512 : TypeLocTypeMatcher::WrapperMatcherInterface(InnerMatcher) {}
1514 bool matches(const TypeLoc &Node, ASTMatchFinder *Finder,
1515 BoundNodesTreeBuilder *Builder) const override {
1518 return this->InnerMatcher.matches(
1519 ast_type_traits::DynTypedNode::create(Node.getType()), Finder, Builder);
1523 /// \brief Matches nodes of type \c T for which the inner matcher matches on a
1524 /// another node of type \c T that can be reached using a given traverse
1526 template <typename T>
1527 class TypeTraverseMatcher : public WrapperMatcherInterface<T> {
1529 explicit TypeTraverseMatcher(const Matcher<QualType> &InnerMatcher,
1530 QualType (T::*TraverseFunction)() const)
1531 : TypeTraverseMatcher::WrapperMatcherInterface(InnerMatcher),
1532 TraverseFunction(TraverseFunction) {}
1534 bool matches(const T &Node, ASTMatchFinder *Finder,
1535 BoundNodesTreeBuilder *Builder) const override {
1536 QualType NextNode = (Node.*TraverseFunction)();
1537 if (NextNode.isNull())
1539 return this->InnerMatcher.matches(
1540 ast_type_traits::DynTypedNode::create(NextNode), Finder, Builder);
1544 QualType (T::*TraverseFunction)() const;
1547 /// \brief Matches nodes of type \c T in a ..Loc hierarchy, for which the inner
1548 /// matcher matches on a another node of type \c T that can be reached using a
1549 /// given traverse function.
1550 template <typename T>
1551 class TypeLocTraverseMatcher : public WrapperMatcherInterface<T> {
1553 explicit TypeLocTraverseMatcher(const Matcher<TypeLoc> &InnerMatcher,
1554 TypeLoc (T::*TraverseFunction)() const)
1555 : TypeLocTraverseMatcher::WrapperMatcherInterface(InnerMatcher),
1556 TraverseFunction(TraverseFunction) {}
1558 bool matches(const T &Node, ASTMatchFinder *Finder,
1559 BoundNodesTreeBuilder *Builder) const override {
1560 TypeLoc NextNode = (Node.*TraverseFunction)();
1563 return this->InnerMatcher.matches(
1564 ast_type_traits::DynTypedNode::create(NextNode), Finder, Builder);
1568 TypeLoc (T::*TraverseFunction)() const;
1571 /// \brief Converts a \c Matcher<InnerT> to a \c Matcher<OuterT>, where
1572 /// \c OuterT is any type that is supported by \c Getter.
1574 /// \code Getter<OuterT>::value() \endcode returns a
1575 /// \code InnerTBase (OuterT::*)() \endcode, which is used to adapt a \c OuterT
1576 /// object into a \c InnerT
1577 template <typename InnerTBase,
1578 template <typename OuterT> class Getter,
1579 template <typename OuterT> class MatcherImpl,
1580 typename ReturnTypesF>
1581 class TypeTraversePolymorphicMatcher {
1583 typedef TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl,
1585 static Self create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers);
1588 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
1590 explicit TypeTraversePolymorphicMatcher(
1591 ArrayRef<const Matcher<InnerTBase> *> InnerMatchers)
1592 : InnerMatcher(makeAllOfComposite(InnerMatchers)) {}
1594 template <typename OuterT> operator Matcher<OuterT>() const {
1595 return Matcher<OuterT>(
1596 new MatcherImpl<OuterT>(InnerMatcher, Getter<OuterT>::value()));
1600 : public VariadicFunction<Self, Matcher<InnerTBase>, &Self::create> {
1605 const Matcher<InnerTBase> InnerMatcher;
1608 /// \brief A simple memoizer of T(*)() functions.
1610 /// It will call the passed 'Func' template parameter at most once.
1611 /// Used to support AST_MATCHER_FUNCTION() macro.
1612 template <typename Matcher, Matcher (*Func)()> class MemoizedMatcher {
1614 Wrapper() : M(Func()) {}
1619 static const Matcher &getInstance() {
1620 static llvm::ManagedStatic<Wrapper> Instance;
1625 // Define the create() method out of line to silence a GCC warning about
1626 // the struct "Func" having greater visibility than its base, which comes from
1627 // using the flag -fvisibility-inlines-hidden.
1628 template <typename InnerTBase, template <typename OuterT> class Getter,
1629 template <typename OuterT> class MatcherImpl, typename ReturnTypesF>
1630 TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl, ReturnTypesF>
1631 TypeTraversePolymorphicMatcher<
1632 InnerTBase, Getter, MatcherImpl,
1633 ReturnTypesF>::create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers) {
1634 return Self(InnerMatchers);
1637 // FIXME: unify ClassTemplateSpecializationDecl and TemplateSpecializationType's
1638 // APIs for accessing the template argument list.
1639 inline ArrayRef<TemplateArgument>
1640 getTemplateSpecializationArgs(const ClassTemplateSpecializationDecl &D) {
1641 return D.getTemplateArgs().asArray();
1644 inline ArrayRef<TemplateArgument>
1645 getTemplateSpecializationArgs(const TemplateSpecializationType &T) {
1646 return llvm::makeArrayRef(T.getArgs(), T.getNumArgs());
1649 inline ArrayRef<TemplateArgument>
1650 getTemplateSpecializationArgs(const FunctionDecl &FD) {
1651 if (const auto* TemplateArgs = FD.getTemplateSpecializationArgs())
1652 return TemplateArgs->asArray();
1653 return ArrayRef<TemplateArgument>();
1656 struct NotEqualsBoundNodePredicate {
1657 bool operator()(const internal::BoundNodesMap &Nodes) const {
1658 return Nodes.getNode(ID) != Node;
1661 ast_type_traits::DynTypedNode Node;
1664 template <typename Ty>
1665 struct GetBodyMatcher {
1666 static const Stmt *get(const Ty &Node) {
1667 return Node.getBody();
1672 inline const Stmt *GetBodyMatcher<FunctionDecl>::get(const FunctionDecl &Node) {
1673 return Node.doesThisDeclarationHaveABody() ? Node.getBody() : nullptr;
1676 template <typename Ty>
1677 struct HasSizeMatcher {
1678 static bool hasSize(const Ty &Node, unsigned int N) {
1679 return Node.getSize() == N;
1684 inline bool HasSizeMatcher<StringLiteral>::hasSize(
1685 const StringLiteral &Node, unsigned int N) {
1686 return Node.getLength() == N;
1689 template <typename Ty>
1690 struct GetSourceExpressionMatcher {
1691 static const Expr *get(const Ty &Node) {
1692 return Node.getSubExpr();
1697 inline const Expr *GetSourceExpressionMatcher<OpaqueValueExpr>::get(
1698 const OpaqueValueExpr &Node) {
1699 return Node.getSourceExpr();
1702 template <typename Ty>
1703 struct CompoundStmtMatcher {
1704 static const CompoundStmt *get(const Ty &Node) {
1710 inline const CompoundStmt *
1711 CompoundStmtMatcher<StmtExpr>::get(const StmtExpr &Node) {
1712 return Node.getSubStmt();
1716 } // end namespace internal
1717 } // end namespace ast_matchers
1718 } // end namespace clang
1720 #endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERSINTERNAL_H