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/Optional.h"
50 #include "llvm/ADT/VariadicFunction.h"
51 #include "llvm/Support/ManagedStatic.h"
57 namespace ast_matchers {
63 /// \brief Internal version of BoundNodes. Holds all the bound nodes.
66 /// \brief Adds \c Node to the map with key \c ID.
68 /// The node's base type should be in NodeBaseType or it will be unaccessible.
69 void addNode(StringRef ID, const ast_type_traits::DynTypedNode& DynNode) {
70 NodeMap[ID] = DynNode;
73 /// \brief Returns the AST node bound to \c ID.
75 /// Returns NULL if there was no node bound to \c ID or if there is a node but
76 /// it cannot be converted to the specified type.
78 const T *getNodeAs(StringRef ID) const {
79 IDToNodeMap::const_iterator It = NodeMap.find(ID);
80 if (It == NodeMap.end()) {
83 return It->second.get<T>();
86 ast_type_traits::DynTypedNode getNode(StringRef ID) const {
87 IDToNodeMap::const_iterator It = NodeMap.find(ID);
88 if (It == NodeMap.end()) {
89 return ast_type_traits::DynTypedNode();
94 /// \brief Imposes an order on BoundNodesMaps.
95 bool operator<(const BoundNodesMap &Other) const {
96 return NodeMap < Other.NodeMap;
99 /// \brief A map from IDs to the bound nodes.
101 /// Note that we're using std::map here, as for memoization:
102 /// - we need a comparison operator
103 /// - we need an assignment operator
104 typedef std::map<std::string, ast_type_traits::DynTypedNode> IDToNodeMap;
106 const IDToNodeMap &getMap() const {
110 /// \brief Returns \c true if this \c BoundNodesMap can be compared, i.e. all
111 /// stored nodes have memoization data.
112 bool isComparable() const {
113 for (const auto &IDAndNode : NodeMap) {
114 if (!IDAndNode.second.getMemoizationData())
124 /// \brief Creates BoundNodesTree objects.
126 /// The tree builder is used during the matching process to insert the bound
127 /// nodes from the Id matcher.
128 class BoundNodesTreeBuilder {
130 /// \brief A visitor interface to visit all BoundNodes results for a
134 virtual ~Visitor() {}
136 /// \brief Called multiple times during a single call to VisitMatches(...).
138 /// 'BoundNodesView' contains the bound nodes for a single match.
139 virtual void visitMatch(const BoundNodes& BoundNodesView) = 0;
142 /// \brief Add a binding from an id to a node.
143 void setBinding(const std::string &Id,
144 const ast_type_traits::DynTypedNode &DynNode) {
145 if (Bindings.empty())
146 Bindings.emplace_back();
147 for (BoundNodesMap &Binding : Bindings)
148 Binding.addNode(Id, DynNode);
151 /// \brief Adds a branch in the tree.
152 void addMatch(const BoundNodesTreeBuilder &Bindings);
154 /// \brief Visits all matches that this BoundNodesTree represents.
156 /// The ownership of 'ResultVisitor' remains at the caller.
157 void visitMatches(Visitor* ResultVisitor);
159 template <typename ExcludePredicate>
160 bool removeBindings(const ExcludePredicate &Predicate) {
161 Bindings.erase(std::remove_if(Bindings.begin(), Bindings.end(), Predicate),
163 return !Bindings.empty();
166 /// \brief Imposes an order on BoundNodesTreeBuilders.
167 bool operator<(const BoundNodesTreeBuilder &Other) const {
168 return Bindings < Other.Bindings;
171 /// \brief Returns \c true if this \c BoundNodesTreeBuilder can be compared,
172 /// i.e. all stored node maps have memoization data.
173 bool isComparable() const {
174 for (const BoundNodesMap &NodesMap : Bindings) {
175 if (!NodesMap.isComparable())
182 SmallVector<BoundNodesMap, 16> Bindings;
185 class ASTMatchFinder;
187 /// \brief Generic interface for all matchers.
189 /// Used by the implementation of Matcher<T> and DynTypedMatcher.
190 /// In general, implement MatcherInterface<T> or SingleNodeMatcherInterface<T>
192 class DynMatcherInterface : public RefCountedBaseVPTR {
194 /// \brief Returns true if \p DynNode can be matched.
196 /// May bind \p DynNode to an ID via \p Builder, or recurse into
197 /// the AST via \p Finder.
198 virtual bool dynMatches(const ast_type_traits::DynTypedNode &DynNode,
199 ASTMatchFinder *Finder,
200 BoundNodesTreeBuilder *Builder) const = 0;
203 /// \brief Generic interface for matchers on an AST node of type T.
205 /// Implement this if your matcher may need to inspect the children or
206 /// descendants of the node or bind matched nodes to names. If you are
207 /// writing a simple matcher that only inspects properties of the
208 /// current node and doesn't care about its children or descendants,
209 /// implement SingleNodeMatcherInterface instead.
210 template <typename T>
211 class MatcherInterface : public DynMatcherInterface {
213 ~MatcherInterface() override {}
215 /// \brief Returns true if 'Node' can be matched.
217 /// May bind 'Node' to an ID via 'Builder', or recurse into
218 /// the AST via 'Finder'.
219 virtual bool matches(const T &Node,
220 ASTMatchFinder *Finder,
221 BoundNodesTreeBuilder *Builder) const = 0;
223 bool dynMatches(const ast_type_traits::DynTypedNode &DynNode,
224 ASTMatchFinder *Finder,
225 BoundNodesTreeBuilder *Builder) const override {
226 return matches(DynNode.getUnchecked<T>(), Finder, Builder);
230 /// \brief Interface for matchers that only evaluate properties on a single
232 template <typename T>
233 class SingleNodeMatcherInterface : public MatcherInterface<T> {
235 /// \brief Returns true if the matcher matches the provided node.
237 /// A subclass must implement this instead of Matches().
238 virtual bool matchesNode(const T &Node) const = 0;
241 /// Implements MatcherInterface::Matches.
242 bool matches(const T &Node,
243 ASTMatchFinder * /* Finder */,
244 BoundNodesTreeBuilder * /* Builder */) const override {
245 return matchesNode(Node);
249 template <typename> class Matcher;
251 /// \brief Matcher that works on a \c DynTypedNode.
253 /// It is constructed from a \c Matcher<T> object and redirects most calls to
254 /// underlying matcher.
255 /// It checks whether the \c DynTypedNode is convertible into the type of the
256 /// underlying matcher and then do the actual match on the actual node, or
257 /// return false if it is not convertible.
258 class DynTypedMatcher {
260 /// \brief Takes ownership of the provided implementation pointer.
261 template <typename T>
262 DynTypedMatcher(MatcherInterface<T> *Implementation)
264 SupportedKind(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()),
265 RestrictKind(SupportedKind), Implementation(Implementation) {}
267 /// \brief Construct from a variadic function.
268 enum VariadicOperator {
269 /// \brief Matches nodes for which all provided matchers match.
271 /// \brief Matches nodes for which at least one of the provided matchers
274 /// \brief Matches nodes for which at least one of the provided matchers
275 /// matches, but doesn't stop at the first match.
277 /// \brief Matches nodes that do not match the provided matcher.
279 /// Uses the variadic matcher interface, but fails if
280 /// InnerMatchers.size() != 1.
283 static DynTypedMatcher
284 constructVariadic(VariadicOperator Op,
285 std::vector<DynTypedMatcher> InnerMatchers);
287 /// \brief Get a "true" matcher for \p NodeKind.
289 /// It only checks that the node is of the right kind.
290 static DynTypedMatcher trueMatcher(ast_type_traits::ASTNodeKind NodeKind);
292 void setAllowBind(bool AB) { AllowBind = AB; }
294 /// \brief Check whether this matcher could ever match a node of kind \p Kind.
295 /// \return \c false if this matcher will never match such a node. Otherwise,
297 bool canMatchNodesOfKind(ast_type_traits::ASTNodeKind Kind) const;
299 /// \brief Return a matcher that points to the same implementation, but
300 /// restricts the node types for \p Kind.
301 DynTypedMatcher dynCastTo(const ast_type_traits::ASTNodeKind Kind) const;
303 /// \brief Returns true if the matcher matches the given \c DynNode.
304 bool matches(const ast_type_traits::DynTypedNode &DynNode,
305 ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const;
307 /// \brief Same as matches(), but skips the kind check.
309 /// It is faster, but the caller must ensure the node is valid for the
310 /// kind of this matcher.
311 bool matchesNoKindCheck(const ast_type_traits::DynTypedNode &DynNode,
312 ASTMatchFinder *Finder,
313 BoundNodesTreeBuilder *Builder) const;
315 /// \brief Bind the specified \p ID to the matcher.
316 /// \return A new matcher with the \p ID bound to it if this matcher supports
317 /// binding. Otherwise, returns an empty \c Optional<>.
318 llvm::Optional<DynTypedMatcher> tryBind(StringRef ID) const;
320 /// \brief Returns a unique \p ID for the matcher.
322 /// Casting a Matcher<T> to Matcher<U> creates a matcher that has the
323 /// same \c Implementation pointer, but different \c RestrictKind. We need to
324 /// include both in the ID to make it unique.
326 /// \c MatcherIDType supports operator< and provides strict weak ordering.
327 typedef std::pair<ast_type_traits::ASTNodeKind, uint64_t> MatcherIDType;
328 MatcherIDType getID() const {
329 /// FIXME: Document the requirements this imposes on matcher
330 /// implementations (no new() implementation_ during a Matches()).
331 return std::make_pair(RestrictKind,
332 reinterpret_cast<uint64_t>(Implementation.get()));
335 /// \brief Returns the type this matcher works on.
337 /// \c matches() will always return false unless the node passed is of this
338 /// or a derived type.
339 ast_type_traits::ASTNodeKind getSupportedKind() const {
340 return SupportedKind;
343 /// \brief Returns \c true if the passed \c DynTypedMatcher can be converted
344 /// to a \c Matcher<T>.
346 /// This method verifies that the underlying matcher in \c Other can process
347 /// nodes of types T.
348 template <typename T> bool canConvertTo() const {
349 return canConvertTo(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
351 bool canConvertTo(ast_type_traits::ASTNodeKind To) const;
353 /// \brief Construct a \c Matcher<T> interface around the dynamic matcher.
355 /// This method asserts that \c canConvertTo() is \c true. Callers
356 /// should call \c canConvertTo() first to make sure that \c this is
357 /// compatible with T.
358 template <typename T> Matcher<T> convertTo() const {
359 assert(canConvertTo<T>());
360 return unconditionalConvertTo<T>();
363 /// \brief Same as \c convertTo(), but does not check that the underlying
364 /// matcher can handle a value of T.
366 /// If it is not compatible, then this matcher will never match anything.
367 template <typename T> Matcher<T> unconditionalConvertTo() const;
370 DynTypedMatcher(ast_type_traits::ASTNodeKind SupportedKind,
371 ast_type_traits::ASTNodeKind RestrictKind,
372 IntrusiveRefCntPtr<DynMatcherInterface> Implementation)
374 SupportedKind(SupportedKind),
375 RestrictKind(RestrictKind),
376 Implementation(std::move(Implementation)) {}
379 ast_type_traits::ASTNodeKind SupportedKind;
380 /// \brief A potentially stricter node kind.
382 /// It allows to perform implicit and dynamic cast of matchers without
383 /// needing to change \c Implementation.
384 ast_type_traits::ASTNodeKind RestrictKind;
385 IntrusiveRefCntPtr<DynMatcherInterface> Implementation;
388 /// \brief Wrapper base class for a wrapping matcher.
390 /// This is just a container for a DynTypedMatcher that can be used as a base
391 /// class for another matcher.
392 template <typename T>
393 class WrapperMatcherInterface : public MatcherInterface<T> {
395 explicit WrapperMatcherInterface(DynTypedMatcher &&InnerMatcher)
396 : InnerMatcher(std::move(InnerMatcher)) {}
398 const DynTypedMatcher InnerMatcher;
401 /// \brief Wrapper of a MatcherInterface<T> *that allows copying.
403 /// A Matcher<Base> can be used anywhere a Matcher<Derived> is
404 /// required. This establishes an is-a relationship which is reverse
405 /// to the AST hierarchy. In other words, Matcher<T> is contravariant
406 /// with respect to T. The relationship is built via a type conversion
407 /// operator rather than a type hierarchy to be able to templatize the
408 /// type hierarchy instead of spelling it out.
409 template <typename T>
412 /// \brief Takes ownership of the provided implementation pointer.
413 explicit Matcher(MatcherInterface<T> *Implementation)
414 : Implementation(Implementation) {}
416 /// \brief Implicitly converts \c Other to a Matcher<T>.
418 /// Requires \c T to be derived from \c From.
419 template <typename From>
420 Matcher(const Matcher<From> &Other,
421 typename std::enable_if<std::is_base_of<From, T>::value &&
422 !std::is_same<From, T>::value>::type * = 0)
423 : Implementation(restrictMatcher(Other.Implementation)) {
424 assert(Implementation.getSupportedKind().isSame(
425 ast_type_traits::ASTNodeKind::getFromNodeKind<T>()));
428 /// \brief Implicitly converts \c Matcher<Type> to \c Matcher<QualType>.
430 /// The resulting matcher is not strict, i.e. ignores qualifiers.
431 template <typename TypeT>
432 Matcher(const Matcher<TypeT> &Other,
433 typename std::enable_if<
434 std::is_same<T, QualType>::value &&
435 std::is_same<TypeT, Type>::value>::type* = 0)
436 : Implementation(new TypeToQualType<TypeT>(Other)) {}
438 /// \brief Convert \c this into a \c Matcher<T> by applying dyn_cast<> to the
440 /// \c To must be a base class of \c T.
441 template <typename To>
442 Matcher<To> dynCastTo() const {
443 static_assert(std::is_base_of<To, T>::value, "Invalid dynCast call.");
444 return Matcher<To>(Implementation);
447 /// \brief Forwards the call to the underlying MatcherInterface<T> pointer.
448 bool matches(const T &Node,
449 ASTMatchFinder *Finder,
450 BoundNodesTreeBuilder *Builder) const {
451 return Implementation.matches(ast_type_traits::DynTypedNode::create(Node),
455 /// \brief Returns an ID that uniquely identifies the matcher.
456 DynTypedMatcher::MatcherIDType getID() const {
457 return Implementation.getID();
460 /// \brief Extract the dynamic matcher.
462 /// The returned matcher keeps the same restrictions as \c this and remembers
463 /// that it is meant to support nodes of type \c T.
464 operator DynTypedMatcher() const { return Implementation; }
466 /// \brief Allows the conversion of a \c Matcher<Type> to a \c
467 /// Matcher<QualType>.
469 /// Depending on the constructor argument, the matcher is either strict, i.e.
470 /// does only matches in the absence of qualifiers, or not, i.e. simply
471 /// ignores any qualifiers.
472 template <typename TypeT>
473 class TypeToQualType : public WrapperMatcherInterface<QualType> {
475 TypeToQualType(const Matcher<TypeT> &InnerMatcher)
476 : TypeToQualType::WrapperMatcherInterface(InnerMatcher) {}
478 bool matches(const QualType &Node, ASTMatchFinder *Finder,
479 BoundNodesTreeBuilder *Builder) const override {
482 return this->InnerMatcher.matches(
483 ast_type_traits::DynTypedNode::create(*Node), Finder, Builder);
488 // For Matcher<T> <=> Matcher<U> conversions.
489 template <typename U> friend class Matcher;
490 // For DynTypedMatcher::unconditionalConvertTo<T>.
491 friend class DynTypedMatcher;
493 static DynTypedMatcher restrictMatcher(const DynTypedMatcher &Other) {
494 return Other.dynCastTo(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
497 explicit Matcher(const DynTypedMatcher &Implementation)
498 : Implementation(restrictMatcher(Implementation)) {
499 assert(this->Implementation.getSupportedKind()
500 .isSame(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()));
503 DynTypedMatcher Implementation;
506 /// \brief A convenient helper for creating a Matcher<T> without specifying
507 /// the template type argument.
508 template <typename T>
509 inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) {
510 return Matcher<T>(Implementation);
513 /// \brief Specialization of the conversion functions for QualType.
515 /// This specialization provides the Matcher<Type>->Matcher<QualType>
516 /// conversion that the static API does.
518 inline Matcher<QualType> DynTypedMatcher::convertTo<QualType>() const {
519 assert(canConvertTo<QualType>());
520 const ast_type_traits::ASTNodeKind SourceKind = getSupportedKind();
521 if (SourceKind.isSame(
522 ast_type_traits::ASTNodeKind::getFromNodeKind<Type>())) {
523 // We support implicit conversion from Matcher<Type> to Matcher<QualType>
524 return unconditionalConvertTo<Type>();
526 return unconditionalConvertTo<QualType>();
529 /// \brief Finds the first node in a range that matches the given matcher.
530 template <typename MatcherT, typename IteratorT>
531 bool matchesFirstInRange(const MatcherT &Matcher, IteratorT Start,
532 IteratorT End, ASTMatchFinder *Finder,
533 BoundNodesTreeBuilder *Builder) {
534 for (IteratorT I = Start; I != End; ++I) {
535 BoundNodesTreeBuilder Result(*Builder);
536 if (Matcher.matches(*I, Finder, &Result)) {
537 *Builder = std::move(Result);
544 /// \brief Finds the first node in a pointer range that matches the given
546 template <typename MatcherT, typename IteratorT>
547 bool matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start,
548 IteratorT End, ASTMatchFinder *Finder,
549 BoundNodesTreeBuilder *Builder) {
550 for (IteratorT I = Start; I != End; ++I) {
551 BoundNodesTreeBuilder Result(*Builder);
552 if (Matcher.matches(**I, Finder, &Result)) {
553 *Builder = std::move(Result);
560 /// \brief Metafunction to determine if type T has a member called getDecl.
561 template <typename T> struct has_getDecl {
562 struct Default { int getDecl; };
563 struct Derived : T, Default { };
565 template<typename C, C> struct CheckT;
567 // If T::getDecl exists, an ambiguity arises and CheckT will
568 // not be instantiable. This makes f(...) the only available
571 static char (&f(CheckT<int Default::*, &C::getDecl>*))[1];
572 template<typename C> static char (&f(...))[2];
574 static bool const value = sizeof(f<Derived>(nullptr)) == 2;
577 /// \brief Matches overloaded operators with a specific name.
579 /// The type argument ArgT is not used by this matcher but is used by
580 /// PolymorphicMatcherWithParam1 and should be StringRef.
581 template <typename T, typename ArgT>
582 class HasOverloadedOperatorNameMatcher : public SingleNodeMatcherInterface<T> {
583 static_assert(std::is_same<T, CXXOperatorCallExpr>::value ||
584 std::is_base_of<FunctionDecl, T>::value,
585 "unsupported class for matcher");
586 static_assert(std::is_same<ArgT, StringRef>::value,
587 "argument type must be StringRef");
590 explicit HasOverloadedOperatorNameMatcher(const StringRef Name)
591 : SingleNodeMatcherInterface<T>(), Name(Name) {}
593 bool matchesNode(const T &Node) const override {
594 return matchesSpecialized(Node);
599 /// \brief CXXOperatorCallExpr exist only for calls to overloaded operators
600 /// so this function returns true if the call is to an operator of the given
602 bool matchesSpecialized(const CXXOperatorCallExpr &Node) const {
603 return getOperatorSpelling(Node.getOperator()) == Name;
606 /// \brief Returns true only if CXXMethodDecl represents an overloaded
607 /// operator and has the given operator name.
608 bool matchesSpecialized(const FunctionDecl &Node) const {
609 return Node.isOverloadedOperator() &&
610 getOperatorSpelling(Node.getOverloadedOperator()) == Name;
616 /// \brief Matches named declarations with a specific name.
618 /// See \c hasName() in ASTMatchers.h for details.
619 class HasNameMatcher : public SingleNodeMatcherInterface<NamedDecl> {
621 explicit HasNameMatcher(StringRef Name);
623 bool matchesNode(const NamedDecl &Node) const override;
626 /// \brief Unqualified match routine.
628 /// It is much faster than the full match, but it only works for unqualified
630 bool matchesNodeUnqualified(const NamedDecl &Node) const;
632 /// \brief Full match routine
634 /// It generates the fully qualified name of the declaration (which is
635 /// expensive) before trying to match.
636 /// It is slower but simple and works on all cases.
637 bool matchesNodeFull(const NamedDecl &Node) const;
639 const bool UseUnqualifiedMatch;
640 const std::string Name;
643 /// \brief Matches declarations for QualType and CallExpr.
645 /// Type argument DeclMatcherT is required by PolymorphicMatcherWithParam1 but
646 /// not actually used.
647 template <typename T, typename DeclMatcherT>
648 class HasDeclarationMatcher : public WrapperMatcherInterface<T> {
649 static_assert(std::is_same<DeclMatcherT, Matcher<Decl>>::value,
650 "instantiated with wrong types");
653 explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher)
654 : HasDeclarationMatcher::WrapperMatcherInterface(InnerMatcher) {}
656 bool matches(const T &Node, ASTMatchFinder *Finder,
657 BoundNodesTreeBuilder *Builder) const override {
658 return matchesSpecialized(Node, Finder, Builder);
662 /// \brief If getDecl exists as a member of U, returns whether the inner
663 /// matcher matches Node.getDecl().
664 template <typename U>
665 bool matchesSpecialized(
666 const U &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder,
667 typename std::enable_if<has_getDecl<U>::value, int>::type = 0) const {
668 return matchesDecl(Node.getDecl(), Finder, Builder);
671 /// \brief Extracts the CXXRecordDecl or EnumDecl of a QualType and returns
672 /// whether the inner matcher matches on it.
673 bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder,
674 BoundNodesTreeBuilder *Builder) const {
675 /// FIXME: Add other ways to convert...
678 if (const EnumType *AsEnum = dyn_cast<EnumType>(Node.getTypePtr()))
679 return matchesDecl(AsEnum->getDecl(), Finder, Builder);
680 return matchesDecl(Node->getAsCXXRecordDecl(), Finder, Builder);
683 /// \brief Gets the TemplateDecl from a TemplateSpecializationType
684 /// and returns whether the inner matches on it.
685 bool matchesSpecialized(const TemplateSpecializationType &Node,
686 ASTMatchFinder *Finder,
687 BoundNodesTreeBuilder *Builder) const {
688 return matchesDecl(Node.getTemplateName().getAsTemplateDecl(),
692 /// \brief Extracts the Decl of the callee of a CallExpr and returns whether
693 /// the inner matcher matches on it.
694 bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder,
695 BoundNodesTreeBuilder *Builder) const {
696 return matchesDecl(Node.getCalleeDecl(), Finder, Builder);
699 /// \brief Extracts the Decl of the constructor call and returns whether the
700 /// inner matcher matches on it.
701 bool matchesSpecialized(const CXXConstructExpr &Node,
702 ASTMatchFinder *Finder,
703 BoundNodesTreeBuilder *Builder) const {
704 return matchesDecl(Node.getConstructor(), Finder, Builder);
707 /// \brief Extracts the \c ValueDecl a \c MemberExpr refers to and returns
708 /// whether the inner matcher matches on it.
709 bool matchesSpecialized(const MemberExpr &Node,
710 ASTMatchFinder *Finder,
711 BoundNodesTreeBuilder *Builder) const {
712 return matchesDecl(Node.getMemberDecl(), Finder, Builder);
715 /// \brief Returns whether the inner matcher \c Node. Returns false if \c Node
717 bool matchesDecl(const Decl *Node, ASTMatchFinder *Finder,
718 BoundNodesTreeBuilder *Builder) const {
719 return Node != nullptr &&
720 this->InnerMatcher.matches(
721 ast_type_traits::DynTypedNode::create(*Node), Finder, Builder);
725 /// \brief IsBaseType<T>::value is true if T is a "base" type in the AST
726 /// node class hierarchies.
727 template <typename T>
729 static const bool value =
730 std::is_same<T, Decl>::value ||
731 std::is_same<T, Stmt>::value ||
732 std::is_same<T, QualType>::value ||
733 std::is_same<T, Type>::value ||
734 std::is_same<T, TypeLoc>::value ||
735 std::is_same<T, NestedNameSpecifier>::value ||
736 std::is_same<T, NestedNameSpecifierLoc>::value ||
737 std::is_same<T, CXXCtorInitializer>::value;
739 template <typename T>
740 const bool IsBaseType<T>::value;
742 /// \brief Interface that allows matchers to traverse the AST.
743 /// FIXME: Find a better name.
745 /// This provides three entry methods for each base node type in the AST:
746 /// - \c matchesChildOf:
747 /// Matches a matcher on every child node of the given node. Returns true
748 /// if at least one child node could be matched.
749 /// - \c matchesDescendantOf:
750 /// Matches a matcher on all descendant nodes of the given node. Returns true
751 /// if at least one descendant matched.
752 /// - \c matchesAncestorOf:
753 /// Matches a matcher on all ancestors of the given node. Returns true if
754 /// at least one ancestor matched.
756 /// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal.
757 /// In the future, we wan to implement this for all nodes for which it makes
758 /// sense. In the case of matchesAncestorOf, we'll want to implement it for
759 /// all nodes, as all nodes have ancestors.
760 class ASTMatchFinder {
762 /// \brief Defines how we descend a level in the AST when we pass
763 /// through expressions.
765 /// Will traverse any child nodes.
767 /// Will not traverse implicit casts and parentheses.
768 TK_IgnoreImplicitCastsAndParentheses
771 /// \brief Defines how bindings are processed on recursive matches.
773 /// Stop at the first match and only bind the first match.
775 /// Create results for all combinations of bindings that match.
779 /// \brief Defines which ancestors are considered for a match.
780 enum AncestorMatchMode {
783 /// Direct parent only.
787 virtual ~ASTMatchFinder() {}
789 /// \brief Returns true if the given class is directly or indirectly derived
790 /// from a base type matching \c base.
792 /// A class is considered to be also derived from itself.
793 virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
794 const Matcher<NamedDecl> &Base,
795 BoundNodesTreeBuilder *Builder) = 0;
797 template <typename T>
798 bool matchesChildOf(const T &Node,
799 const DynTypedMatcher &Matcher,
800 BoundNodesTreeBuilder *Builder,
801 TraversalKind Traverse,
803 static_assert(std::is_base_of<Decl, T>::value ||
804 std::is_base_of<Stmt, T>::value ||
805 std::is_base_of<NestedNameSpecifier, T>::value ||
806 std::is_base_of<NestedNameSpecifierLoc, T>::value ||
807 std::is_base_of<TypeLoc, T>::value ||
808 std::is_base_of<QualType, T>::value,
809 "unsupported type for recursive matching");
810 return matchesChildOf(ast_type_traits::DynTypedNode::create(Node),
811 Matcher, Builder, Traverse, Bind);
814 template <typename T>
815 bool matchesDescendantOf(const T &Node,
816 const DynTypedMatcher &Matcher,
817 BoundNodesTreeBuilder *Builder,
819 static_assert(std::is_base_of<Decl, T>::value ||
820 std::is_base_of<Stmt, T>::value ||
821 std::is_base_of<NestedNameSpecifier, T>::value ||
822 std::is_base_of<NestedNameSpecifierLoc, T>::value ||
823 std::is_base_of<TypeLoc, T>::value ||
824 std::is_base_of<QualType, T>::value,
825 "unsupported type for recursive matching");
826 return matchesDescendantOf(ast_type_traits::DynTypedNode::create(Node),
827 Matcher, Builder, Bind);
830 // FIXME: Implement support for BindKind.
831 template <typename T>
832 bool matchesAncestorOf(const T &Node,
833 const DynTypedMatcher &Matcher,
834 BoundNodesTreeBuilder *Builder,
835 AncestorMatchMode MatchMode) {
836 static_assert(std::is_base_of<Decl, T>::value ||
837 std::is_base_of<Stmt, T>::value,
838 "only Decl or Stmt allowed for recursive matching");
839 return matchesAncestorOf(ast_type_traits::DynTypedNode::create(Node),
840 Matcher, Builder, MatchMode);
843 virtual ASTContext &getASTContext() const = 0;
846 virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node,
847 const DynTypedMatcher &Matcher,
848 BoundNodesTreeBuilder *Builder,
849 TraversalKind Traverse,
852 virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node,
853 const DynTypedMatcher &Matcher,
854 BoundNodesTreeBuilder *Builder,
857 virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node,
858 const DynTypedMatcher &Matcher,
859 BoundNodesTreeBuilder *Builder,
860 AncestorMatchMode MatchMode) = 0;
863 /// \brief A type-list implementation.
865 /// A "linked list" of types, accessible by using the ::head and ::tail
867 template <typename... Ts> struct TypeList {}; // Empty sentinel type list.
869 template <typename T1, typename... Ts> struct TypeList<T1, Ts...> {
870 /// \brief The first type on the list.
873 /// \brief A sublist with the tail. ie everything but the head.
875 /// This type is used to do recursion. TypeList<>/EmptyTypeList indicates the
877 typedef TypeList<Ts...> tail;
880 /// \brief The empty type list.
881 typedef TypeList<> EmptyTypeList;
883 /// \brief Helper meta-function to determine if some type \c T is present or
884 /// a parent type in the list.
885 template <typename AnyTypeList, typename T>
886 struct TypeListContainsSuperOf {
887 static const bool value =
888 std::is_base_of<typename AnyTypeList::head, T>::value ||
889 TypeListContainsSuperOf<typename AnyTypeList::tail, T>::value;
891 template <typename T>
892 struct TypeListContainsSuperOf<EmptyTypeList, T> {
893 static const bool value = false;
896 /// \brief A "type list" that contains all types.
898 /// Useful for matchers like \c anything and \c unless.
899 typedef TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc,
900 QualType, Type, TypeLoc, CXXCtorInitializer> AllNodeBaseTypes;
902 /// \brief Helper meta-function to extract the argument out of a function of
905 /// See AST_POLYMORPHIC_SUPPORTED_TYPES for details.
906 template <class T> struct ExtractFunctionArgMeta;
907 template <class T> struct ExtractFunctionArgMeta<void(T)> {
911 /// \brief Default type lists for ArgumentAdaptingMatcher matchers.
912 typedef AllNodeBaseTypes AdaptativeDefaultFromTypes;
913 typedef TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc,
914 TypeLoc, QualType> AdaptativeDefaultToTypes;
916 /// \brief All types that are supported by HasDeclarationMatcher above.
917 typedef TypeList<CallExpr, CXXConstructExpr, DeclRefExpr, EnumType,
918 InjectedClassNameType, LabelStmt, MemberExpr, QualType,
919 RecordType, TagType, TemplateSpecializationType,
920 TemplateTypeParmType, TypedefType,
921 UnresolvedUsingType> HasDeclarationSupportedTypes;
923 /// \brief Converts a \c Matcher<T> to a matcher of desired type \c To by
924 /// "adapting" a \c To into a \c T.
926 /// The \c ArgumentAdapterT argument specifies how the adaptation is done.
929 /// \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher);
930 /// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher
931 /// that is convertible into any matcher of type \c To by constructing
932 /// \c HasMatcher<To, T>(InnerMatcher).
934 /// If a matcher does not need knowledge about the inner type, prefer to use
935 /// PolymorphicMatcherWithParam1.
936 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
937 typename FromTypes = AdaptativeDefaultFromTypes,
938 typename ToTypes = AdaptativeDefaultToTypes>
939 struct ArgumentAdaptingMatcherFunc {
940 template <typename T> class Adaptor {
942 explicit Adaptor(const Matcher<T> &InnerMatcher)
943 : InnerMatcher(InnerMatcher) {}
945 typedef ToTypes ReturnTypes;
947 template <typename To> operator Matcher<To>() const {
948 return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher));
952 const Matcher<T> InnerMatcher;
955 template <typename T>
956 static Adaptor<T> create(const Matcher<T> &InnerMatcher) {
957 return Adaptor<T>(InnerMatcher);
960 template <typename T>
961 Adaptor<T> operator()(const Matcher<T> &InnerMatcher) const {
962 return create(InnerMatcher);
966 /// \brief A PolymorphicMatcherWithParamN<MatcherT, P1, ..., PN> object can be
967 /// created from N parameters p1, ..., pN (of type P1, ..., PN) and
968 /// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN)
969 /// can be constructed.
972 /// - PolymorphicMatcherWithParam0<IsDefinitionMatcher>()
973 /// creates an object that can be used as a Matcher<T> for any type T
974 /// where an IsDefinitionMatcher<T>() can be constructed.
975 /// - PolymorphicMatcherWithParam1<ValueEqualsMatcher, int>(42)
976 /// creates an object that can be used as a Matcher<T> for any type T
977 /// where a ValueEqualsMatcher<T, int>(42) can be constructed.
978 template <template <typename T> class MatcherT,
979 typename ReturnTypesF = void(AllNodeBaseTypes)>
980 class PolymorphicMatcherWithParam0 {
982 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
983 template <typename T>
984 operator Matcher<T>() const {
985 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
986 "right polymorphic conversion");
987 return Matcher<T>(new MatcherT<T>());
991 template <template <typename T, typename P1> class MatcherT,
993 typename ReturnTypesF = void(AllNodeBaseTypes)>
994 class PolymorphicMatcherWithParam1 {
996 explicit PolymorphicMatcherWithParam1(const P1 &Param1)
999 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
1001 template <typename T>
1002 operator Matcher<T>() const {
1003 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
1004 "right polymorphic conversion");
1005 return Matcher<T>(new MatcherT<T, P1>(Param1));
1012 template <template <typename T, typename P1, typename P2> class MatcherT,
1013 typename P1, typename P2,
1014 typename ReturnTypesF = void(AllNodeBaseTypes)>
1015 class PolymorphicMatcherWithParam2 {
1017 PolymorphicMatcherWithParam2(const P1 &Param1, const P2 &Param2)
1018 : Param1(Param1), Param2(Param2) {}
1020 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
1022 template <typename T>
1023 operator Matcher<T>() const {
1024 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
1025 "right polymorphic conversion");
1026 return Matcher<T>(new MatcherT<T, P1, P2>(Param1, Param2));
1034 /// \brief Matches any instance of the given NodeType.
1036 /// This is useful when a matcher syntactically requires a child matcher,
1037 /// but the context doesn't care. See for example: anything().
1040 typedef AllNodeBaseTypes ReturnTypes;
1042 template <typename T>
1043 operator Matcher<T>() const {
1044 return DynTypedMatcher::trueMatcher(
1045 ast_type_traits::ASTNodeKind::getFromNodeKind<T>())
1046 .template unconditionalConvertTo<T>();
1050 /// \brief A Matcher that allows binding the node it matches to an id.
1052 /// BindableMatcher provides a \a bind() method that allows binding the
1053 /// matched node to an id if the match was successful.
1054 template <typename T>
1055 class BindableMatcher : public Matcher<T> {
1057 explicit BindableMatcher(const Matcher<T> &M) : Matcher<T>(M) {}
1058 explicit BindableMatcher(MatcherInterface<T> *Implementation)
1059 : Matcher<T>(Implementation) {}
1061 /// \brief Returns a matcher that will bind the matched node on a match.
1063 /// The returned matcher is equivalent to this matcher, but will
1064 /// bind the matched node on a match.
1065 Matcher<T> bind(StringRef ID) const {
1066 return DynTypedMatcher(*this)
1068 ->template unconditionalConvertTo<T>();
1071 /// \brief Same as Matcher<T>'s conversion operator, but enables binding on
1072 /// the returned matcher.
1073 operator DynTypedMatcher() const {
1074 DynTypedMatcher Result = static_cast<const Matcher<T>&>(*this);
1075 Result.setAllowBind(true);
1080 /// \brief Matches nodes of type T that have child nodes of type ChildT for
1081 /// which a specified child matcher matches.
1083 /// ChildT must be an AST base type.
1084 template <typename T, typename ChildT>
1085 class HasMatcher : public WrapperMatcherInterface<T> {
1086 static_assert(IsBaseType<ChildT>::value,
1087 "has only accepts base type matcher");
1090 explicit HasMatcher(const Matcher<ChildT> &ChildMatcher)
1091 : HasMatcher::WrapperMatcherInterface(ChildMatcher) {}
1093 bool matches(const T &Node, ASTMatchFinder *Finder,
1094 BoundNodesTreeBuilder *Builder) const override {
1095 return Finder->matchesChildOf(
1096 Node, this->InnerMatcher, Builder,
1097 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
1098 ASTMatchFinder::BK_First);
1102 /// \brief Matches nodes of type T that have child nodes of type ChildT for
1103 /// which a specified child matcher matches. ChildT must be an AST base
1105 /// As opposed to the HasMatcher, the ForEachMatcher will produce a match
1106 /// for each child that matches.
1107 template <typename T, typename ChildT>
1108 class ForEachMatcher : public WrapperMatcherInterface<T> {
1109 static_assert(IsBaseType<ChildT>::value,
1110 "for each only accepts base type matcher");
1113 explicit ForEachMatcher(const Matcher<ChildT> &ChildMatcher)
1114 : ForEachMatcher::WrapperMatcherInterface(ChildMatcher) {}
1116 bool matches(const T& Node, ASTMatchFinder* Finder,
1117 BoundNodesTreeBuilder* Builder) const override {
1118 return Finder->matchesChildOf(
1119 Node, this->InnerMatcher, Builder,
1120 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
1121 ASTMatchFinder::BK_All);
1125 /// \brief VariadicOperatorMatcher related types.
1128 /// \brief Polymorphic matcher object that uses a \c
1129 /// DynTypedMatcher::VariadicOperator operator.
1131 /// Input matchers can have any type (including other polymorphic matcher
1132 /// types), and the actual Matcher<T> is generated on demand with an implicit
1133 /// coversion operator.
1134 template <typename... Ps> class VariadicOperatorMatcher {
1136 VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op, Ps &&... Params)
1137 : Op(Op), Params(std::forward<Ps>(Params)...) {}
1139 template <typename T> operator Matcher<T>() const {
1140 return DynTypedMatcher::constructVariadic(
1141 Op, getMatchers<T>(llvm::index_sequence_for<Ps...>()))
1142 .template unconditionalConvertTo<T>();
1146 // Helper method to unpack the tuple into a vector.
1147 template <typename T, std::size_t... Is>
1148 std::vector<DynTypedMatcher> getMatchers(llvm::index_sequence<Is...>) const {
1149 return {Matcher<T>(std::get<Is>(Params))...};
1152 const DynTypedMatcher::VariadicOperator Op;
1153 std::tuple<Ps...> Params;
1156 /// \brief Overloaded function object to generate VariadicOperatorMatcher
1157 /// objects from arbitrary matchers.
1158 template <unsigned MinCount, unsigned MaxCount>
1159 struct VariadicOperatorMatcherFunc {
1160 DynTypedMatcher::VariadicOperator Op;
1162 template <typename... Ms>
1163 VariadicOperatorMatcher<Ms...> operator()(Ms &&... Ps) const {
1164 static_assert(MinCount <= sizeof...(Ms) && sizeof...(Ms) <= MaxCount,
1165 "invalid number of parameters for variadic matcher");
1166 return VariadicOperatorMatcher<Ms...>(Op, std::forward<Ms>(Ps)...);
1172 template <typename T>
1173 inline Matcher<T> DynTypedMatcher::unconditionalConvertTo() const {
1174 return Matcher<T>(*this);
1177 /// \brief Creates a Matcher<T> that matches if all inner matchers match.
1178 template<typename T>
1179 BindableMatcher<T> makeAllOfComposite(
1180 ArrayRef<const Matcher<T> *> InnerMatchers) {
1181 // For the size() == 0 case, we return a "true" matcher.
1182 if (InnerMatchers.size() == 0) {
1183 return BindableMatcher<T>(TrueMatcher());
1185 // For the size() == 1 case, we simply return that one matcher.
1186 // No need to wrap it in a variadic operation.
1187 if (InnerMatchers.size() == 1) {
1188 return BindableMatcher<T>(*InnerMatchers[0]);
1191 typedef llvm::pointee_iterator<const Matcher<T> *const *> PI;
1192 std::vector<DynTypedMatcher> DynMatchers(PI(InnerMatchers.begin()),
1193 PI(InnerMatchers.end()));
1194 return BindableMatcher<T>(
1195 DynTypedMatcher::constructVariadic(DynTypedMatcher::VO_AllOf,
1196 std::move(DynMatchers))
1197 .template unconditionalConvertTo<T>());
1200 /// \brief Creates a Matcher<T> that matches if
1201 /// T is dyn_cast'able into InnerT and all inner matchers match.
1203 /// Returns BindableMatcher, as matchers that use dyn_cast have
1204 /// the same object both to match on and to run submatchers on,
1205 /// so there is no ambiguity with what gets bound.
1206 template<typename T, typename InnerT>
1207 BindableMatcher<T> makeDynCastAllOfComposite(
1208 ArrayRef<const Matcher<InnerT> *> InnerMatchers) {
1209 return BindableMatcher<T>(
1210 makeAllOfComposite(InnerMatchers).template dynCastTo<T>());
1213 /// \brief Matches nodes of type T that have at least one descendant node of
1214 /// type DescendantT for which the given inner matcher matches.
1216 /// DescendantT must be an AST base type.
1217 template <typename T, typename DescendantT>
1218 class HasDescendantMatcher : public WrapperMatcherInterface<T> {
1219 static_assert(IsBaseType<DescendantT>::value,
1220 "has descendant only accepts base type matcher");
1223 explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher)
1224 : HasDescendantMatcher::WrapperMatcherInterface(DescendantMatcher) {}
1226 bool matches(const T &Node, ASTMatchFinder *Finder,
1227 BoundNodesTreeBuilder *Builder) const override {
1228 return Finder->matchesDescendantOf(Node, this->InnerMatcher, Builder,
1229 ASTMatchFinder::BK_First);
1233 /// \brief Matches nodes of type \c T that have a parent node of type \c ParentT
1234 /// for which the given inner matcher matches.
1236 /// \c ParentT must be an AST base type.
1237 template <typename T, typename ParentT>
1238 class HasParentMatcher : public WrapperMatcherInterface<T> {
1239 static_assert(IsBaseType<ParentT>::value,
1240 "has parent only accepts base type matcher");
1243 explicit HasParentMatcher(const Matcher<ParentT> &ParentMatcher)
1244 : HasParentMatcher::WrapperMatcherInterface(ParentMatcher) {}
1246 bool matches(const T &Node, ASTMatchFinder *Finder,
1247 BoundNodesTreeBuilder *Builder) const override {
1248 return Finder->matchesAncestorOf(Node, this->InnerMatcher, Builder,
1249 ASTMatchFinder::AMM_ParentOnly);
1253 /// \brief Matches nodes of type \c T that have at least one ancestor node of
1254 /// type \c AncestorT for which the given inner matcher matches.
1256 /// \c AncestorT must be an AST base type.
1257 template <typename T, typename AncestorT>
1258 class HasAncestorMatcher : public WrapperMatcherInterface<T> {
1259 static_assert(IsBaseType<AncestorT>::value,
1260 "has ancestor only accepts base type matcher");
1263 explicit HasAncestorMatcher(const Matcher<AncestorT> &AncestorMatcher)
1264 : HasAncestorMatcher::WrapperMatcherInterface(AncestorMatcher) {}
1266 bool matches(const T &Node, ASTMatchFinder *Finder,
1267 BoundNodesTreeBuilder *Builder) const override {
1268 return Finder->matchesAncestorOf(Node, this->InnerMatcher, Builder,
1269 ASTMatchFinder::AMM_All);
1273 /// \brief Matches nodes of type T that have at least one descendant node of
1274 /// type DescendantT for which the given inner matcher matches.
1276 /// DescendantT must be an AST base type.
1277 /// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match
1278 /// for each descendant node that matches instead of only for the first.
1279 template <typename T, typename DescendantT>
1280 class ForEachDescendantMatcher : public WrapperMatcherInterface<T> {
1281 static_assert(IsBaseType<DescendantT>::value,
1282 "for each descendant only accepts base type matcher");
1285 explicit ForEachDescendantMatcher(
1286 const Matcher<DescendantT> &DescendantMatcher)
1287 : ForEachDescendantMatcher::WrapperMatcherInterface(DescendantMatcher) {}
1289 bool matches(const T &Node, ASTMatchFinder *Finder,
1290 BoundNodesTreeBuilder *Builder) const override {
1291 return Finder->matchesDescendantOf(Node, this->InnerMatcher, Builder,
1292 ASTMatchFinder::BK_All);
1296 /// \brief Matches on nodes that have a getValue() method if getValue() equals
1297 /// the value the ValueEqualsMatcher was constructed with.
1298 template <typename T, typename ValueT>
1299 class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> {
1300 static_assert(std::is_base_of<CharacterLiteral, T>::value ||
1301 std::is_base_of<CXXBoolLiteralExpr, T>::value ||
1302 std::is_base_of<FloatingLiteral, T>::value ||
1303 std::is_base_of<IntegerLiteral, T>::value,
1304 "the node must have a getValue method");
1307 explicit ValueEqualsMatcher(const ValueT &ExpectedValue)
1308 : ExpectedValue(ExpectedValue) {}
1310 bool matchesNode(const T &Node) const override {
1311 return Node.getValue() == ExpectedValue;
1315 const ValueT ExpectedValue;
1318 /// \brief Template specializations to easily write matchers for floating point
1321 inline bool ValueEqualsMatcher<FloatingLiteral, double>::matchesNode(
1322 const FloatingLiteral &Node) const {
1323 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle)
1324 return Node.getValue().convertToFloat() == ExpectedValue;
1325 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble)
1326 return Node.getValue().convertToDouble() == ExpectedValue;
1330 inline bool ValueEqualsMatcher<FloatingLiteral, float>::matchesNode(
1331 const FloatingLiteral &Node) const {
1332 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle)
1333 return Node.getValue().convertToFloat() == ExpectedValue;
1334 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble)
1335 return Node.getValue().convertToDouble() == ExpectedValue;
1339 inline bool ValueEqualsMatcher<FloatingLiteral, llvm::APFloat>::matchesNode(
1340 const FloatingLiteral &Node) const {
1341 return ExpectedValue.compare(Node.getValue()) == llvm::APFloat::cmpEqual;
1344 /// \brief A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a
1345 /// variadic functor that takes a number of Matcher<TargetT> and returns a
1346 /// Matcher<SourceT> that matches TargetT nodes that are matched by all of the
1347 /// given matchers, if SourceT can be dynamically casted into TargetT.
1350 /// const VariadicDynCastAllOfMatcher<
1351 /// Decl, CXXRecordDecl> record;
1352 /// Creates a functor record(...) that creates a Matcher<Decl> given
1353 /// a variable number of arguments of type Matcher<CXXRecordDecl>.
1354 /// The returned matcher matches if the given Decl can by dynamically
1355 /// casted to CXXRecordDecl and all given matchers match.
1356 template <typename SourceT, typename TargetT>
1357 class VariadicDynCastAllOfMatcher
1358 : public llvm::VariadicFunction<
1359 BindableMatcher<SourceT>, Matcher<TargetT>,
1360 makeDynCastAllOfComposite<SourceT, TargetT> > {
1362 VariadicDynCastAllOfMatcher() {}
1365 /// \brief A \c VariadicAllOfMatcher<T> object is a variadic functor that takes
1366 /// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T
1367 /// nodes that are matched by all of the given matchers.
1370 /// const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
1371 /// Creates a functor nestedNameSpecifier(...) that creates a
1372 /// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type
1373 /// \c Matcher<NestedNameSpecifier>.
1374 /// The returned matcher matches if all given matchers match.
1375 template <typename T>
1376 class VariadicAllOfMatcher : public llvm::VariadicFunction<
1377 BindableMatcher<T>, Matcher<T>,
1378 makeAllOfComposite<T> > {
1380 VariadicAllOfMatcher() {}
1383 /// \brief Matches nodes of type \c TLoc for which the inner
1384 /// \c Matcher<T> matches.
1385 template <typename TLoc, typename T>
1386 class LocMatcher : public WrapperMatcherInterface<TLoc> {
1388 explicit LocMatcher(const Matcher<T> &InnerMatcher)
1389 : LocMatcher::WrapperMatcherInterface(InnerMatcher) {}
1391 bool matches(const TLoc &Node, ASTMatchFinder *Finder,
1392 BoundNodesTreeBuilder *Builder) const override {
1395 return this->InnerMatcher.matches(extract(Node), Finder, Builder);
1399 static ast_type_traits::DynTypedNode
1400 extract(const NestedNameSpecifierLoc &Loc) {
1401 return ast_type_traits::DynTypedNode::create(*Loc.getNestedNameSpecifier());
1405 /// \brief Matches \c TypeLocs based on an inner matcher matching a certain
1408 /// Used to implement the \c loc() matcher.
1409 class TypeLocTypeMatcher : public WrapperMatcherInterface<TypeLoc> {
1411 explicit TypeLocTypeMatcher(const Matcher<QualType> &InnerMatcher)
1412 : TypeLocTypeMatcher::WrapperMatcherInterface(InnerMatcher) {}
1414 bool matches(const TypeLoc &Node, ASTMatchFinder *Finder,
1415 BoundNodesTreeBuilder *Builder) const override {
1418 return this->InnerMatcher.matches(
1419 ast_type_traits::DynTypedNode::create(Node.getType()), Finder, Builder);
1423 /// \brief Matches nodes of type \c T for which the inner matcher matches on a
1424 /// another node of type \c T that can be reached using a given traverse
1426 template <typename T>
1427 class TypeTraverseMatcher : public WrapperMatcherInterface<T> {
1429 explicit TypeTraverseMatcher(const Matcher<QualType> &InnerMatcher,
1430 QualType (T::*TraverseFunction)() const)
1431 : TypeTraverseMatcher::WrapperMatcherInterface(InnerMatcher),
1432 TraverseFunction(TraverseFunction) {}
1434 bool matches(const T &Node, ASTMatchFinder *Finder,
1435 BoundNodesTreeBuilder *Builder) const override {
1436 QualType NextNode = (Node.*TraverseFunction)();
1437 if (NextNode.isNull())
1439 return this->InnerMatcher.matches(
1440 ast_type_traits::DynTypedNode::create(NextNode), Finder, Builder);
1444 QualType (T::*TraverseFunction)() const;
1447 /// \brief Matches nodes of type \c T in a ..Loc hierarchy, for which the inner
1448 /// matcher matches on a another node of type \c T that can be reached using a
1449 /// given traverse function.
1450 template <typename T>
1451 class TypeLocTraverseMatcher : public WrapperMatcherInterface<T> {
1453 explicit TypeLocTraverseMatcher(const Matcher<TypeLoc> &InnerMatcher,
1454 TypeLoc (T::*TraverseFunction)() const)
1455 : TypeLocTraverseMatcher::WrapperMatcherInterface(InnerMatcher),
1456 TraverseFunction(TraverseFunction) {}
1458 bool matches(const T &Node, ASTMatchFinder *Finder,
1459 BoundNodesTreeBuilder *Builder) const override {
1460 TypeLoc NextNode = (Node.*TraverseFunction)();
1463 return this->InnerMatcher.matches(
1464 ast_type_traits::DynTypedNode::create(NextNode), Finder, Builder);
1468 TypeLoc (T::*TraverseFunction)() const;
1471 /// \brief Converts a \c Matcher<InnerT> to a \c Matcher<OuterT>, where
1472 /// \c OuterT is any type that is supported by \c Getter.
1474 /// \code Getter<OuterT>::value() \endcode returns a
1475 /// \code InnerTBase (OuterT::*)() \endcode, which is used to adapt a \c OuterT
1476 /// object into a \c InnerT
1477 template <typename InnerTBase,
1478 template <typename OuterT> class Getter,
1479 template <typename OuterT> class MatcherImpl,
1480 typename ReturnTypesF>
1481 class TypeTraversePolymorphicMatcher {
1483 typedef TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl,
1485 static Self create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers);
1488 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
1490 explicit TypeTraversePolymorphicMatcher(
1491 ArrayRef<const Matcher<InnerTBase> *> InnerMatchers)
1492 : InnerMatcher(makeAllOfComposite(InnerMatchers)) {}
1494 template <typename OuterT> operator Matcher<OuterT>() const {
1495 return Matcher<OuterT>(
1496 new MatcherImpl<OuterT>(InnerMatcher, Getter<OuterT>::value()));
1499 struct Func : public llvm::VariadicFunction<Self, Matcher<InnerTBase>,
1505 const Matcher<InnerTBase> InnerMatcher;
1508 /// \brief A simple memoizer of T(*)() functions.
1510 /// It will call the passed 'Func' template parameter at most once.
1511 /// Used to support AST_MATCHER_FUNCTION() macro.
1512 template <typename Matcher, Matcher (*Func)()> class MemoizedMatcher {
1514 Wrapper() : M(Func()) {}
1519 static const Matcher &getInstance() {
1520 static llvm::ManagedStatic<Wrapper> Instance;
1525 // Define the create() method out of line to silence a GCC warning about
1526 // the struct "Func" having greater visibility than its base, which comes from
1527 // using the flag -fvisibility-inlines-hidden.
1528 template <typename InnerTBase, template <typename OuterT> class Getter,
1529 template <typename OuterT> class MatcherImpl, typename ReturnTypesF>
1530 TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl, ReturnTypesF>
1531 TypeTraversePolymorphicMatcher<
1532 InnerTBase, Getter, MatcherImpl,
1533 ReturnTypesF>::create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers) {
1534 return Self(InnerMatchers);
1537 // FIXME: unify ClassTemplateSpecializationDecl and TemplateSpecializationType's
1538 // APIs for accessing the template argument list.
1539 inline ArrayRef<TemplateArgument>
1540 getTemplateSpecializationArgs(const ClassTemplateSpecializationDecl &D) {
1541 return D.getTemplateArgs().asArray();
1544 inline ArrayRef<TemplateArgument>
1545 getTemplateSpecializationArgs(const TemplateSpecializationType &T) {
1546 return llvm::makeArrayRef(T.getArgs(), T.getNumArgs());
1549 struct NotEqualsBoundNodePredicate {
1550 bool operator()(const internal::BoundNodesMap &Nodes) const {
1551 return Nodes.getNode(ID) != Node;
1554 ast_type_traits::DynTypedNode Node;
1557 } // end namespace internal
1558 } // end namespace ast_matchers
1559 } // end namespace clang