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(StringRef Id, const ast_type_traits::DynTypedNode &DynNode) {
144 if (Bindings.empty())
145 Bindings.emplace_back();
146 for (BoundNodesMap &Binding : Bindings)
147 Binding.addNode(Id, DynNode);
150 /// \brief Adds a branch in the tree.
151 void addMatch(const BoundNodesTreeBuilder &Bindings);
153 /// \brief Visits all matches that this BoundNodesTree represents.
155 /// The ownership of 'ResultVisitor' remains at the caller.
156 void visitMatches(Visitor* ResultVisitor);
158 template <typename ExcludePredicate>
159 bool removeBindings(const ExcludePredicate &Predicate) {
160 Bindings.erase(std::remove_if(Bindings.begin(), Bindings.end(), Predicate),
162 return !Bindings.empty();
165 /// \brief Imposes an order on BoundNodesTreeBuilders.
166 bool operator<(const BoundNodesTreeBuilder &Other) const {
167 return Bindings < Other.Bindings;
170 /// \brief Returns \c true if this \c BoundNodesTreeBuilder can be compared,
171 /// i.e. all stored node maps have memoization data.
172 bool isComparable() const {
173 for (const BoundNodesMap &NodesMap : Bindings) {
174 if (!NodesMap.isComparable())
181 SmallVector<BoundNodesMap, 16> Bindings;
184 class ASTMatchFinder;
186 /// \brief Generic interface for all matchers.
188 /// Used by the implementation of Matcher<T> and DynTypedMatcher.
189 /// In general, implement MatcherInterface<T> or SingleNodeMatcherInterface<T>
191 class DynMatcherInterface : public RefCountedBaseVPTR {
193 /// \brief Returns true if \p DynNode can be matched.
195 /// May bind \p DynNode to an ID via \p Builder, or recurse into
196 /// the AST via \p Finder.
197 virtual bool dynMatches(const ast_type_traits::DynTypedNode &DynNode,
198 ASTMatchFinder *Finder,
199 BoundNodesTreeBuilder *Builder) const = 0;
202 /// \brief Generic interface for matchers on an AST node of type T.
204 /// Implement this if your matcher may need to inspect the children or
205 /// descendants of the node or bind matched nodes to names. If you are
206 /// writing a simple matcher that only inspects properties of the
207 /// current node and doesn't care about its children or descendants,
208 /// implement SingleNodeMatcherInterface instead.
209 template <typename T>
210 class MatcherInterface : public DynMatcherInterface {
212 ~MatcherInterface() override {}
214 /// \brief Returns true if 'Node' can be matched.
216 /// May bind 'Node' to an ID via 'Builder', or recurse into
217 /// the AST via 'Finder'.
218 virtual bool matches(const T &Node,
219 ASTMatchFinder *Finder,
220 BoundNodesTreeBuilder *Builder) const = 0;
222 bool dynMatches(const ast_type_traits::DynTypedNode &DynNode,
223 ASTMatchFinder *Finder,
224 BoundNodesTreeBuilder *Builder) const override {
225 return matches(DynNode.getUnchecked<T>(), Finder, Builder);
229 /// \brief Interface for matchers that only evaluate properties on a single
231 template <typename T>
232 class SingleNodeMatcherInterface : public MatcherInterface<T> {
234 /// \brief Returns true if the matcher matches the provided node.
236 /// A subclass must implement this instead of Matches().
237 virtual bool matchesNode(const T &Node) const = 0;
240 /// Implements MatcherInterface::Matches.
241 bool matches(const T &Node,
242 ASTMatchFinder * /* Finder */,
243 BoundNodesTreeBuilder * /* Builder */) const override {
244 return matchesNode(Node);
248 template <typename> class Matcher;
250 /// \brief Matcher that works on a \c DynTypedNode.
252 /// It is constructed from a \c Matcher<T> object and redirects most calls to
253 /// underlying matcher.
254 /// It checks whether the \c DynTypedNode is convertible into the type of the
255 /// underlying matcher and then do the actual match on the actual node, or
256 /// return false if it is not convertible.
257 class DynTypedMatcher {
259 /// \brief Takes ownership of the provided implementation pointer.
260 template <typename T>
261 DynTypedMatcher(MatcherInterface<T> *Implementation)
263 SupportedKind(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()),
264 RestrictKind(SupportedKind), Implementation(Implementation) {}
266 /// \brief Construct from a variadic function.
267 enum VariadicOperator {
268 /// \brief Matches nodes for which all provided matchers match.
270 /// \brief Matches nodes for which at least one of the provided matchers
273 /// \brief Matches nodes for which at least one of the provided matchers
274 /// matches, but doesn't stop at the first match.
276 /// \brief Matches nodes that do not match the provided matcher.
278 /// Uses the variadic matcher interface, but fails if
279 /// InnerMatchers.size() != 1.
282 static DynTypedMatcher
283 constructVariadic(VariadicOperator Op,
284 std::vector<DynTypedMatcher> InnerMatchers);
286 /// \brief Get a "true" matcher for \p NodeKind.
288 /// It only checks that the node is of the right kind.
289 static DynTypedMatcher trueMatcher(ast_type_traits::ASTNodeKind NodeKind);
291 void setAllowBind(bool AB) { AllowBind = AB; }
293 /// \brief Check whether this matcher could ever match a node of kind \p Kind.
294 /// \return \c false if this matcher will never match such a node. Otherwise,
296 bool canMatchNodesOfKind(ast_type_traits::ASTNodeKind Kind) const;
298 /// \brief Return a matcher that points to the same implementation, but
299 /// restricts the node types for \p Kind.
300 DynTypedMatcher dynCastTo(const ast_type_traits::ASTNodeKind Kind) const;
302 /// \brief Returns true if the matcher matches the given \c DynNode.
303 bool matches(const ast_type_traits::DynTypedNode &DynNode,
304 ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const;
306 /// \brief Same as matches(), but skips the kind check.
308 /// It is faster, but the caller must ensure the node is valid for the
309 /// kind of this matcher.
310 bool matchesNoKindCheck(const ast_type_traits::DynTypedNode &DynNode,
311 ASTMatchFinder *Finder,
312 BoundNodesTreeBuilder *Builder) const;
314 /// \brief Bind the specified \p ID to the matcher.
315 /// \return A new matcher with the \p ID bound to it if this matcher supports
316 /// binding. Otherwise, returns an empty \c Optional<>.
317 llvm::Optional<DynTypedMatcher> tryBind(StringRef ID) const;
319 /// \brief Returns a unique \p ID for the matcher.
321 /// Casting a Matcher<T> to Matcher<U> creates a matcher that has the
322 /// same \c Implementation pointer, but different \c RestrictKind. We need to
323 /// include both in the ID to make it unique.
325 /// \c MatcherIDType supports operator< and provides strict weak ordering.
326 typedef std::pair<ast_type_traits::ASTNodeKind, uint64_t> MatcherIDType;
327 MatcherIDType getID() const {
328 /// FIXME: Document the requirements this imposes on matcher
329 /// implementations (no new() implementation_ during a Matches()).
330 return std::make_pair(RestrictKind,
331 reinterpret_cast<uint64_t>(Implementation.get()));
334 /// \brief Returns the type this matcher works on.
336 /// \c matches() will always return false unless the node passed is of this
337 /// or a derived type.
338 ast_type_traits::ASTNodeKind getSupportedKind() const {
339 return SupportedKind;
342 /// \brief Returns \c true if the passed \c DynTypedMatcher can be converted
343 /// to a \c Matcher<T>.
345 /// This method verifies that the underlying matcher in \c Other can process
346 /// nodes of types T.
347 template <typename T> bool canConvertTo() const {
348 return canConvertTo(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
350 bool canConvertTo(ast_type_traits::ASTNodeKind To) const;
352 /// \brief Construct a \c Matcher<T> interface around the dynamic matcher.
354 /// This method asserts that \c canConvertTo() is \c true. Callers
355 /// should call \c canConvertTo() first to make sure that \c this is
356 /// compatible with T.
357 template <typename T> Matcher<T> convertTo() const {
358 assert(canConvertTo<T>());
359 return unconditionalConvertTo<T>();
362 /// \brief Same as \c convertTo(), but does not check that the underlying
363 /// matcher can handle a value of T.
365 /// If it is not compatible, then this matcher will never match anything.
366 template <typename T> Matcher<T> unconditionalConvertTo() const;
369 DynTypedMatcher(ast_type_traits::ASTNodeKind SupportedKind,
370 ast_type_traits::ASTNodeKind RestrictKind,
371 IntrusiveRefCntPtr<DynMatcherInterface> Implementation)
373 SupportedKind(SupportedKind),
374 RestrictKind(RestrictKind),
375 Implementation(std::move(Implementation)) {}
378 ast_type_traits::ASTNodeKind SupportedKind;
379 /// \brief A potentially stricter node kind.
381 /// It allows to perform implicit and dynamic cast of matchers without
382 /// needing to change \c Implementation.
383 ast_type_traits::ASTNodeKind RestrictKind;
384 IntrusiveRefCntPtr<DynMatcherInterface> Implementation;
387 /// \brief Wrapper base class for a wrapping matcher.
389 /// This is just a container for a DynTypedMatcher that can be used as a base
390 /// class for another matcher.
391 template <typename T>
392 class WrapperMatcherInterface : public MatcherInterface<T> {
394 explicit WrapperMatcherInterface(DynTypedMatcher &&InnerMatcher)
395 : InnerMatcher(std::move(InnerMatcher)) {}
397 const DynTypedMatcher InnerMatcher;
400 /// \brief Wrapper of a MatcherInterface<T> *that allows copying.
402 /// A Matcher<Base> can be used anywhere a Matcher<Derived> is
403 /// required. This establishes an is-a relationship which is reverse
404 /// to the AST hierarchy. In other words, Matcher<T> is contravariant
405 /// with respect to T. The relationship is built via a type conversion
406 /// operator rather than a type hierarchy to be able to templatize the
407 /// type hierarchy instead of spelling it out.
408 template <typename T>
411 /// \brief Takes ownership of the provided implementation pointer.
412 explicit Matcher(MatcherInterface<T> *Implementation)
413 : Implementation(Implementation) {}
415 /// \brief Implicitly converts \c Other to a Matcher<T>.
417 /// Requires \c T to be derived from \c From.
418 template <typename From>
419 Matcher(const Matcher<From> &Other,
420 typename std::enable_if<std::is_base_of<From, T>::value &&
421 !std::is_same<From, T>::value>::type * = 0)
422 : Implementation(restrictMatcher(Other.Implementation)) {
423 assert(Implementation.getSupportedKind().isSame(
424 ast_type_traits::ASTNodeKind::getFromNodeKind<T>()));
427 /// \brief Implicitly converts \c Matcher<Type> to \c Matcher<QualType>.
429 /// The resulting matcher is not strict, i.e. ignores qualifiers.
430 template <typename TypeT>
431 Matcher(const Matcher<TypeT> &Other,
432 typename std::enable_if<
433 std::is_same<T, QualType>::value &&
434 std::is_same<TypeT, Type>::value>::type* = 0)
435 : Implementation(new TypeToQualType<TypeT>(Other)) {}
437 /// \brief Convert \c this into a \c Matcher<T> by applying dyn_cast<> to the
439 /// \c To must be a base class of \c T.
440 template <typename To>
441 Matcher<To> dynCastTo() const {
442 static_assert(std::is_base_of<To, T>::value, "Invalid dynCast call.");
443 return Matcher<To>(Implementation);
446 /// \brief Forwards the call to the underlying MatcherInterface<T> pointer.
447 bool matches(const T &Node,
448 ASTMatchFinder *Finder,
449 BoundNodesTreeBuilder *Builder) const {
450 return Implementation.matches(ast_type_traits::DynTypedNode::create(Node),
454 /// \brief Returns an ID that uniquely identifies the matcher.
455 DynTypedMatcher::MatcherIDType getID() const {
456 return Implementation.getID();
459 /// \brief Extract the dynamic matcher.
461 /// The returned matcher keeps the same restrictions as \c this and remembers
462 /// that it is meant to support nodes of type \c T.
463 operator DynTypedMatcher() const { return Implementation; }
465 /// \brief Allows the conversion of a \c Matcher<Type> to a \c
466 /// Matcher<QualType>.
468 /// Depending on the constructor argument, the matcher is either strict, i.e.
469 /// does only matches in the absence of qualifiers, or not, i.e. simply
470 /// ignores any qualifiers.
471 template <typename TypeT>
472 class TypeToQualType : public WrapperMatcherInterface<QualType> {
474 TypeToQualType(const Matcher<TypeT> &InnerMatcher)
475 : TypeToQualType::WrapperMatcherInterface(InnerMatcher) {}
477 bool matches(const QualType &Node, ASTMatchFinder *Finder,
478 BoundNodesTreeBuilder *Builder) const override {
481 return this->InnerMatcher.matches(
482 ast_type_traits::DynTypedNode::create(*Node), Finder, Builder);
487 // For Matcher<T> <=> Matcher<U> conversions.
488 template <typename U> friend class Matcher;
489 // For DynTypedMatcher::unconditionalConvertTo<T>.
490 friend class DynTypedMatcher;
492 static DynTypedMatcher restrictMatcher(const DynTypedMatcher &Other) {
493 return Other.dynCastTo(ast_type_traits::ASTNodeKind::getFromNodeKind<T>());
496 explicit Matcher(const DynTypedMatcher &Implementation)
497 : Implementation(restrictMatcher(Implementation)) {
498 assert(this->Implementation.getSupportedKind()
499 .isSame(ast_type_traits::ASTNodeKind::getFromNodeKind<T>()));
502 DynTypedMatcher Implementation;
505 /// \brief A convenient helper for creating a Matcher<T> without specifying
506 /// the template type argument.
507 template <typename T>
508 inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) {
509 return Matcher<T>(Implementation);
512 /// \brief Specialization of the conversion functions for QualType.
514 /// This specialization provides the Matcher<Type>->Matcher<QualType>
515 /// conversion that the static API does.
517 inline Matcher<QualType> DynTypedMatcher::convertTo<QualType>() const {
518 assert(canConvertTo<QualType>());
519 const ast_type_traits::ASTNodeKind SourceKind = getSupportedKind();
520 if (SourceKind.isSame(
521 ast_type_traits::ASTNodeKind::getFromNodeKind<Type>())) {
522 // We support implicit conversion from Matcher<Type> to Matcher<QualType>
523 return unconditionalConvertTo<Type>();
525 return unconditionalConvertTo<QualType>();
528 /// \brief Finds the first node in a range that matches the given matcher.
529 template <typename MatcherT, typename IteratorT>
530 bool matchesFirstInRange(const MatcherT &Matcher, IteratorT Start,
531 IteratorT End, ASTMatchFinder *Finder,
532 BoundNodesTreeBuilder *Builder) {
533 for (IteratorT I = Start; I != End; ++I) {
534 BoundNodesTreeBuilder Result(*Builder);
535 if (Matcher.matches(*I, Finder, &Result)) {
536 *Builder = std::move(Result);
543 /// \brief Finds the first node in a pointer range that matches the given
545 template <typename MatcherT, typename IteratorT>
546 bool matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start,
547 IteratorT End, ASTMatchFinder *Finder,
548 BoundNodesTreeBuilder *Builder) {
549 for (IteratorT I = Start; I != End; ++I) {
550 BoundNodesTreeBuilder Result(*Builder);
551 if (Matcher.matches(**I, Finder, &Result)) {
552 *Builder = std::move(Result);
559 /// \brief Metafunction to determine if type T has a member called getDecl.
560 template <typename T> struct has_getDecl {
561 struct Default { int getDecl; };
562 struct Derived : T, Default { };
564 template<typename C, C> struct CheckT;
566 // If T::getDecl exists, an ambiguity arises and CheckT will
567 // not be instantiable. This makes f(...) the only available
570 static char (&f(CheckT<int Default::*, &C::getDecl>*))[1];
571 template<typename C> static char (&f(...))[2];
573 static bool const value = sizeof(f<Derived>(nullptr)) == 2;
576 /// \brief Matches overloaded operators with a specific name.
578 /// The type argument ArgT is not used by this matcher but is used by
579 /// PolymorphicMatcherWithParam1 and should be StringRef.
580 template <typename T, typename ArgT>
581 class HasOverloadedOperatorNameMatcher : public SingleNodeMatcherInterface<T> {
582 static_assert(std::is_same<T, CXXOperatorCallExpr>::value ||
583 std::is_base_of<FunctionDecl, T>::value,
584 "unsupported class for matcher");
585 static_assert(std::is_same<ArgT, StringRef>::value,
586 "argument type must be StringRef");
589 explicit HasOverloadedOperatorNameMatcher(const StringRef Name)
590 : SingleNodeMatcherInterface<T>(), Name(Name) {}
592 bool matchesNode(const T &Node) const override {
593 return matchesSpecialized(Node);
598 /// \brief CXXOperatorCallExpr exist only for calls to overloaded operators
599 /// so this function returns true if the call is to an operator of the given
601 bool matchesSpecialized(const CXXOperatorCallExpr &Node) const {
602 return getOperatorSpelling(Node.getOperator()) == Name;
605 /// \brief Returns true only if CXXMethodDecl represents an overloaded
606 /// operator and has the given operator name.
607 bool matchesSpecialized(const FunctionDecl &Node) const {
608 return Node.isOverloadedOperator() &&
609 getOperatorSpelling(Node.getOverloadedOperator()) == Name;
615 /// \brief Matches named declarations with a specific name.
617 /// See \c hasName() in ASTMatchers.h for details.
618 class HasNameMatcher : public SingleNodeMatcherInterface<NamedDecl> {
620 explicit HasNameMatcher(StringRef Name);
622 bool matchesNode(const NamedDecl &Node) const override;
625 /// \brief Unqualified match routine.
627 /// It is much faster than the full match, but it only works for unqualified
629 bool matchesNodeUnqualified(const NamedDecl &Node) const;
631 /// \brief Full match routine
633 /// It generates the fully qualified name of the declaration (which is
634 /// expensive) before trying to match.
635 /// It is slower but simple and works on all cases.
636 bool matchesNodeFull(const NamedDecl &Node) const;
638 const bool UseUnqualifiedMatch;
639 const std::string Name;
642 /// \brief Matches declarations for QualType and CallExpr.
644 /// Type argument DeclMatcherT is required by PolymorphicMatcherWithParam1 but
645 /// not actually used.
646 template <typename T, typename DeclMatcherT>
647 class HasDeclarationMatcher : public WrapperMatcherInterface<T> {
648 static_assert(std::is_same<DeclMatcherT, Matcher<Decl>>::value,
649 "instantiated with wrong types");
652 explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher)
653 : HasDeclarationMatcher::WrapperMatcherInterface(InnerMatcher) {}
655 bool matches(const T &Node, ASTMatchFinder *Finder,
656 BoundNodesTreeBuilder *Builder) const override {
657 return matchesSpecialized(Node, Finder, Builder);
661 /// \brief If getDecl exists as a member of U, returns whether the inner
662 /// matcher matches Node.getDecl().
663 template <typename U>
664 bool matchesSpecialized(
665 const U &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder,
666 typename std::enable_if<has_getDecl<U>::value, int>::type = 0) const {
667 return matchesDecl(Node.getDecl(), Finder, Builder);
670 /// \brief Extracts the CXXRecordDecl or EnumDecl of a QualType and returns
671 /// whether the inner matcher matches on it.
672 bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder,
673 BoundNodesTreeBuilder *Builder) const {
674 /// FIXME: Add other ways to convert...
677 if (const EnumType *AsEnum = dyn_cast<EnumType>(Node.getTypePtr()))
678 return matchesDecl(AsEnum->getDecl(), Finder, Builder);
679 return matchesDecl(Node->getAsCXXRecordDecl(), Finder, Builder);
682 /// \brief Gets the TemplateDecl from a TemplateSpecializationType
683 /// and returns whether the inner matches on it.
684 bool matchesSpecialized(const TemplateSpecializationType &Node,
685 ASTMatchFinder *Finder,
686 BoundNodesTreeBuilder *Builder) const {
687 return matchesDecl(Node.getTemplateName().getAsTemplateDecl(),
691 /// \brief Extracts the Decl of the callee of a CallExpr and returns whether
692 /// the inner matcher matches on it.
693 bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder,
694 BoundNodesTreeBuilder *Builder) const {
695 return matchesDecl(Node.getCalleeDecl(), Finder, Builder);
698 /// \brief Extracts the Decl of the constructor call and returns whether the
699 /// inner matcher matches on it.
700 bool matchesSpecialized(const CXXConstructExpr &Node,
701 ASTMatchFinder *Finder,
702 BoundNodesTreeBuilder *Builder) const {
703 return matchesDecl(Node.getConstructor(), Finder, Builder);
706 /// \brief Extracts the \c ValueDecl a \c MemberExpr refers to and returns
707 /// whether the inner matcher matches on it.
708 bool matchesSpecialized(const MemberExpr &Node,
709 ASTMatchFinder *Finder,
710 BoundNodesTreeBuilder *Builder) const {
711 return matchesDecl(Node.getMemberDecl(), Finder, Builder);
714 /// \brief Returns whether the inner matcher \c Node. Returns false if \c Node
716 bool matchesDecl(const Decl *Node, ASTMatchFinder *Finder,
717 BoundNodesTreeBuilder *Builder) const {
718 return Node != nullptr &&
719 this->InnerMatcher.matches(
720 ast_type_traits::DynTypedNode::create(*Node), Finder, Builder);
724 /// \brief IsBaseType<T>::value is true if T is a "base" type in the AST
725 /// node class hierarchies.
726 template <typename T>
728 static const bool value =
729 std::is_same<T, Decl>::value ||
730 std::is_same<T, Stmt>::value ||
731 std::is_same<T, QualType>::value ||
732 std::is_same<T, Type>::value ||
733 std::is_same<T, TypeLoc>::value ||
734 std::is_same<T, NestedNameSpecifier>::value ||
735 std::is_same<T, NestedNameSpecifierLoc>::value ||
736 std::is_same<T, CXXCtorInitializer>::value;
738 template <typename T>
739 const bool IsBaseType<T>::value;
741 /// \brief Interface that allows matchers to traverse the AST.
742 /// FIXME: Find a better name.
744 /// This provides three entry methods for each base node type in the AST:
745 /// - \c matchesChildOf:
746 /// Matches a matcher on every child node of the given node. Returns true
747 /// if at least one child node could be matched.
748 /// - \c matchesDescendantOf:
749 /// Matches a matcher on all descendant nodes of the given node. Returns true
750 /// if at least one descendant matched.
751 /// - \c matchesAncestorOf:
752 /// Matches a matcher on all ancestors of the given node. Returns true if
753 /// at least one ancestor matched.
755 /// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal.
756 /// In the future, we wan to implement this for all nodes for which it makes
757 /// sense. In the case of matchesAncestorOf, we'll want to implement it for
758 /// all nodes, as all nodes have ancestors.
759 class ASTMatchFinder {
761 /// \brief Defines how we descend a level in the AST when we pass
762 /// through expressions.
764 /// Will traverse any child nodes.
766 /// Will not traverse implicit casts and parentheses.
767 TK_IgnoreImplicitCastsAndParentheses
770 /// \brief Defines how bindings are processed on recursive matches.
772 /// Stop at the first match and only bind the first match.
774 /// Create results for all combinations of bindings that match.
778 /// \brief Defines which ancestors are considered for a match.
779 enum AncestorMatchMode {
782 /// Direct parent only.
786 virtual ~ASTMatchFinder() {}
788 /// \brief Returns true if the given class is directly or indirectly derived
789 /// from a base type matching \c base.
791 /// A class is considered to be also derived from itself.
792 virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
793 const Matcher<NamedDecl> &Base,
794 BoundNodesTreeBuilder *Builder) = 0;
796 template <typename T>
797 bool matchesChildOf(const T &Node,
798 const DynTypedMatcher &Matcher,
799 BoundNodesTreeBuilder *Builder,
800 TraversalKind Traverse,
802 static_assert(std::is_base_of<Decl, T>::value ||
803 std::is_base_of<Stmt, T>::value ||
804 std::is_base_of<NestedNameSpecifier, T>::value ||
805 std::is_base_of<NestedNameSpecifierLoc, T>::value ||
806 std::is_base_of<TypeLoc, T>::value ||
807 std::is_base_of<QualType, T>::value,
808 "unsupported type for recursive matching");
809 return matchesChildOf(ast_type_traits::DynTypedNode::create(Node),
810 Matcher, Builder, Traverse, Bind);
813 template <typename T>
814 bool matchesDescendantOf(const T &Node,
815 const DynTypedMatcher &Matcher,
816 BoundNodesTreeBuilder *Builder,
818 static_assert(std::is_base_of<Decl, T>::value ||
819 std::is_base_of<Stmt, T>::value ||
820 std::is_base_of<NestedNameSpecifier, T>::value ||
821 std::is_base_of<NestedNameSpecifierLoc, T>::value ||
822 std::is_base_of<TypeLoc, T>::value ||
823 std::is_base_of<QualType, T>::value,
824 "unsupported type for recursive matching");
825 return matchesDescendantOf(ast_type_traits::DynTypedNode::create(Node),
826 Matcher, Builder, Bind);
829 // FIXME: Implement support for BindKind.
830 template <typename T>
831 bool matchesAncestorOf(const T &Node,
832 const DynTypedMatcher &Matcher,
833 BoundNodesTreeBuilder *Builder,
834 AncestorMatchMode MatchMode) {
835 static_assert(std::is_base_of<Decl, T>::value ||
836 std::is_base_of<Stmt, T>::value,
837 "only Decl or Stmt allowed for recursive matching");
838 return matchesAncestorOf(ast_type_traits::DynTypedNode::create(Node),
839 Matcher, Builder, MatchMode);
842 virtual ASTContext &getASTContext() const = 0;
845 virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node,
846 const DynTypedMatcher &Matcher,
847 BoundNodesTreeBuilder *Builder,
848 TraversalKind Traverse,
851 virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node,
852 const DynTypedMatcher &Matcher,
853 BoundNodesTreeBuilder *Builder,
856 virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node,
857 const DynTypedMatcher &Matcher,
858 BoundNodesTreeBuilder *Builder,
859 AncestorMatchMode MatchMode) = 0;
862 /// \brief A type-list implementation.
864 /// A "linked list" of types, accessible by using the ::head and ::tail
866 template <typename... Ts> struct TypeList {}; // Empty sentinel type list.
868 template <typename T1, typename... Ts> struct TypeList<T1, Ts...> {
869 /// \brief The first type on the list.
872 /// \brief A sublist with the tail. ie everything but the head.
874 /// This type is used to do recursion. TypeList<>/EmptyTypeList indicates the
876 typedef TypeList<Ts...> tail;
879 /// \brief The empty type list.
880 typedef TypeList<> EmptyTypeList;
882 /// \brief Helper meta-function to determine if some type \c T is present or
883 /// a parent type in the list.
884 template <typename AnyTypeList, typename T>
885 struct TypeListContainsSuperOf {
886 static const bool value =
887 std::is_base_of<typename AnyTypeList::head, T>::value ||
888 TypeListContainsSuperOf<typename AnyTypeList::tail, T>::value;
890 template <typename T>
891 struct TypeListContainsSuperOf<EmptyTypeList, T> {
892 static const bool value = false;
895 /// \brief A "type list" that contains all types.
897 /// Useful for matchers like \c anything and \c unless.
898 typedef TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc,
899 QualType, Type, TypeLoc, CXXCtorInitializer> AllNodeBaseTypes;
901 /// \brief Helper meta-function to extract the argument out of a function of
904 /// See AST_POLYMORPHIC_SUPPORTED_TYPES for details.
905 template <class T> struct ExtractFunctionArgMeta;
906 template <class T> struct ExtractFunctionArgMeta<void(T)> {
910 /// \brief Default type lists for ArgumentAdaptingMatcher matchers.
911 typedef AllNodeBaseTypes AdaptativeDefaultFromTypes;
912 typedef TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc,
913 TypeLoc, QualType> AdaptativeDefaultToTypes;
915 /// \brief All types that are supported by HasDeclarationMatcher above.
916 typedef TypeList<CallExpr, CXXConstructExpr, DeclRefExpr, EnumType,
917 InjectedClassNameType, LabelStmt, MemberExpr, QualType,
918 RecordType, TagType, TemplateSpecializationType,
919 TemplateTypeParmType, TypedefType,
920 UnresolvedUsingType> HasDeclarationSupportedTypes;
922 /// \brief Converts a \c Matcher<T> to a matcher of desired type \c To by
923 /// "adapting" a \c To into a \c T.
925 /// The \c ArgumentAdapterT argument specifies how the adaptation is done.
928 /// \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher);
929 /// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher
930 /// that is convertible into any matcher of type \c To by constructing
931 /// \c HasMatcher<To, T>(InnerMatcher).
933 /// If a matcher does not need knowledge about the inner type, prefer to use
934 /// PolymorphicMatcherWithParam1.
935 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
936 typename FromTypes = AdaptativeDefaultFromTypes,
937 typename ToTypes = AdaptativeDefaultToTypes>
938 struct ArgumentAdaptingMatcherFunc {
939 template <typename T> class Adaptor {
941 explicit Adaptor(const Matcher<T> &InnerMatcher)
942 : InnerMatcher(InnerMatcher) {}
944 typedef ToTypes ReturnTypes;
946 template <typename To> operator Matcher<To>() const {
947 return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher));
951 const Matcher<T> InnerMatcher;
954 template <typename T>
955 static Adaptor<T> create(const Matcher<T> &InnerMatcher) {
956 return Adaptor<T>(InnerMatcher);
959 template <typename T>
960 Adaptor<T> operator()(const Matcher<T> &InnerMatcher) const {
961 return create(InnerMatcher);
965 /// \brief A PolymorphicMatcherWithParamN<MatcherT, P1, ..., PN> object can be
966 /// created from N parameters p1, ..., pN (of type P1, ..., PN) and
967 /// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN)
968 /// can be constructed.
971 /// - PolymorphicMatcherWithParam0<IsDefinitionMatcher>()
972 /// creates an object that can be used as a Matcher<T> for any type T
973 /// where an IsDefinitionMatcher<T>() can be constructed.
974 /// - PolymorphicMatcherWithParam1<ValueEqualsMatcher, int>(42)
975 /// creates an object that can be used as a Matcher<T> for any type T
976 /// where a ValueEqualsMatcher<T, int>(42) can be constructed.
977 template <template <typename T> class MatcherT,
978 typename ReturnTypesF = void(AllNodeBaseTypes)>
979 class PolymorphicMatcherWithParam0 {
981 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
982 template <typename T>
983 operator Matcher<T>() const {
984 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
985 "right polymorphic conversion");
986 return Matcher<T>(new MatcherT<T>());
990 template <template <typename T, typename P1> class MatcherT,
992 typename ReturnTypesF = void(AllNodeBaseTypes)>
993 class PolymorphicMatcherWithParam1 {
995 explicit PolymorphicMatcherWithParam1(const P1 &Param1)
998 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
1000 template <typename T>
1001 operator Matcher<T>() const {
1002 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
1003 "right polymorphic conversion");
1004 return Matcher<T>(new MatcherT<T, P1>(Param1));
1011 template <template <typename T, typename P1, typename P2> class MatcherT,
1012 typename P1, typename P2,
1013 typename ReturnTypesF = void(AllNodeBaseTypes)>
1014 class PolymorphicMatcherWithParam2 {
1016 PolymorphicMatcherWithParam2(const P1 &Param1, const P2 &Param2)
1017 : Param1(Param1), Param2(Param2) {}
1019 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
1021 template <typename T>
1022 operator Matcher<T>() const {
1023 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
1024 "right polymorphic conversion");
1025 return Matcher<T>(new MatcherT<T, P1, P2>(Param1, Param2));
1033 /// \brief Matches any instance of the given NodeType.
1035 /// This is useful when a matcher syntactically requires a child matcher,
1036 /// but the context doesn't care. See for example: anything().
1039 typedef AllNodeBaseTypes ReturnTypes;
1041 template <typename T>
1042 operator Matcher<T>() const {
1043 return DynTypedMatcher::trueMatcher(
1044 ast_type_traits::ASTNodeKind::getFromNodeKind<T>())
1045 .template unconditionalConvertTo<T>();
1049 /// \brief A Matcher that allows binding the node it matches to an id.
1051 /// BindableMatcher provides a \a bind() method that allows binding the
1052 /// matched node to an id if the match was successful.
1053 template <typename T>
1054 class BindableMatcher : public Matcher<T> {
1056 explicit BindableMatcher(const Matcher<T> &M) : Matcher<T>(M) {}
1057 explicit BindableMatcher(MatcherInterface<T> *Implementation)
1058 : Matcher<T>(Implementation) {}
1060 /// \brief Returns a matcher that will bind the matched node on a match.
1062 /// The returned matcher is equivalent to this matcher, but will
1063 /// bind the matched node on a match.
1064 Matcher<T> bind(StringRef ID) const {
1065 return DynTypedMatcher(*this)
1067 ->template unconditionalConvertTo<T>();
1070 /// \brief Same as Matcher<T>'s conversion operator, but enables binding on
1071 /// the returned matcher.
1072 operator DynTypedMatcher() const {
1073 DynTypedMatcher Result = static_cast<const Matcher<T>&>(*this);
1074 Result.setAllowBind(true);
1079 /// \brief Matches nodes of type T that have child nodes of type ChildT for
1080 /// which a specified child matcher matches.
1082 /// ChildT must be an AST base type.
1083 template <typename T, typename ChildT>
1084 class HasMatcher : public WrapperMatcherInterface<T> {
1085 static_assert(IsBaseType<ChildT>::value,
1086 "has only accepts base type matcher");
1089 explicit HasMatcher(const Matcher<ChildT> &ChildMatcher)
1090 : HasMatcher::WrapperMatcherInterface(ChildMatcher) {}
1092 bool matches(const T &Node, ASTMatchFinder *Finder,
1093 BoundNodesTreeBuilder *Builder) const override {
1094 return Finder->matchesChildOf(
1095 Node, this->InnerMatcher, Builder,
1096 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
1097 ASTMatchFinder::BK_First);
1101 /// \brief Matches nodes of type T that have child nodes of type ChildT for
1102 /// which a specified child matcher matches. ChildT must be an AST base
1104 /// As opposed to the HasMatcher, the ForEachMatcher will produce a match
1105 /// for each child that matches.
1106 template <typename T, typename ChildT>
1107 class ForEachMatcher : public WrapperMatcherInterface<T> {
1108 static_assert(IsBaseType<ChildT>::value,
1109 "for each only accepts base type matcher");
1112 explicit ForEachMatcher(const Matcher<ChildT> &ChildMatcher)
1113 : ForEachMatcher::WrapperMatcherInterface(ChildMatcher) {}
1115 bool matches(const T& Node, ASTMatchFinder* Finder,
1116 BoundNodesTreeBuilder* Builder) const override {
1117 return Finder->matchesChildOf(
1118 Node, this->InnerMatcher, Builder,
1119 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
1120 ASTMatchFinder::BK_All);
1124 /// \brief VariadicOperatorMatcher related types.
1127 /// \brief Polymorphic matcher object that uses a \c
1128 /// DynTypedMatcher::VariadicOperator operator.
1130 /// Input matchers can have any type (including other polymorphic matcher
1131 /// types), and the actual Matcher<T> is generated on demand with an implicit
1132 /// coversion operator.
1133 template <typename... Ps> class VariadicOperatorMatcher {
1135 VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op, Ps &&... Params)
1136 : Op(Op), Params(std::forward<Ps>(Params)...) {}
1138 template <typename T> operator Matcher<T>() const {
1139 return DynTypedMatcher::constructVariadic(
1140 Op, getMatchers<T>(llvm::index_sequence_for<Ps...>()))
1141 .template unconditionalConvertTo<T>();
1145 // Helper method to unpack the tuple into a vector.
1146 template <typename T, std::size_t... Is>
1147 std::vector<DynTypedMatcher> getMatchers(llvm::index_sequence<Is...>) const {
1148 return {Matcher<T>(std::get<Is>(Params))...};
1151 const DynTypedMatcher::VariadicOperator Op;
1152 std::tuple<Ps...> Params;
1155 /// \brief Overloaded function object to generate VariadicOperatorMatcher
1156 /// objects from arbitrary matchers.
1157 template <unsigned MinCount, unsigned MaxCount>
1158 struct VariadicOperatorMatcherFunc {
1159 DynTypedMatcher::VariadicOperator Op;
1161 template <typename... Ms>
1162 VariadicOperatorMatcher<Ms...> operator()(Ms &&... Ps) const {
1163 static_assert(MinCount <= sizeof...(Ms) && sizeof...(Ms) <= MaxCount,
1164 "invalid number of parameters for variadic matcher");
1165 return VariadicOperatorMatcher<Ms...>(Op, std::forward<Ms>(Ps)...);
1171 template <typename T>
1172 inline Matcher<T> DynTypedMatcher::unconditionalConvertTo() const {
1173 return Matcher<T>(*this);
1176 /// \brief Creates a Matcher<T> that matches if all inner matchers match.
1177 template<typename T>
1178 BindableMatcher<T> makeAllOfComposite(
1179 ArrayRef<const Matcher<T> *> InnerMatchers) {
1180 // For the size() == 0 case, we return a "true" matcher.
1181 if (InnerMatchers.size() == 0) {
1182 return BindableMatcher<T>(TrueMatcher());
1184 // For the size() == 1 case, we simply return that one matcher.
1185 // No need to wrap it in a variadic operation.
1186 if (InnerMatchers.size() == 1) {
1187 return BindableMatcher<T>(*InnerMatchers[0]);
1190 typedef llvm::pointee_iterator<const Matcher<T> *const *> PI;
1191 std::vector<DynTypedMatcher> DynMatchers(PI(InnerMatchers.begin()),
1192 PI(InnerMatchers.end()));
1193 return BindableMatcher<T>(
1194 DynTypedMatcher::constructVariadic(DynTypedMatcher::VO_AllOf,
1195 std::move(DynMatchers))
1196 .template unconditionalConvertTo<T>());
1199 /// \brief Creates a Matcher<T> that matches if
1200 /// T is dyn_cast'able into InnerT and all inner matchers match.
1202 /// Returns BindableMatcher, as matchers that use dyn_cast have
1203 /// the same object both to match on and to run submatchers on,
1204 /// so there is no ambiguity with what gets bound.
1205 template<typename T, typename InnerT>
1206 BindableMatcher<T> makeDynCastAllOfComposite(
1207 ArrayRef<const Matcher<InnerT> *> InnerMatchers) {
1208 return BindableMatcher<T>(
1209 makeAllOfComposite(InnerMatchers).template dynCastTo<T>());
1212 /// \brief Matches nodes of type T that have at least one descendant node of
1213 /// type DescendantT for which the given inner matcher matches.
1215 /// DescendantT must be an AST base type.
1216 template <typename T, typename DescendantT>
1217 class HasDescendantMatcher : public WrapperMatcherInterface<T> {
1218 static_assert(IsBaseType<DescendantT>::value,
1219 "has descendant only accepts base type matcher");
1222 explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher)
1223 : HasDescendantMatcher::WrapperMatcherInterface(DescendantMatcher) {}
1225 bool matches(const T &Node, ASTMatchFinder *Finder,
1226 BoundNodesTreeBuilder *Builder) const override {
1227 return Finder->matchesDescendantOf(Node, this->InnerMatcher, Builder,
1228 ASTMatchFinder::BK_First);
1232 /// \brief Matches nodes of type \c T that have a parent node of type \c ParentT
1233 /// for which the given inner matcher matches.
1235 /// \c ParentT must be an AST base type.
1236 template <typename T, typename ParentT>
1237 class HasParentMatcher : public WrapperMatcherInterface<T> {
1238 static_assert(IsBaseType<ParentT>::value,
1239 "has parent only accepts base type matcher");
1242 explicit HasParentMatcher(const Matcher<ParentT> &ParentMatcher)
1243 : HasParentMatcher::WrapperMatcherInterface(ParentMatcher) {}
1245 bool matches(const T &Node, ASTMatchFinder *Finder,
1246 BoundNodesTreeBuilder *Builder) const override {
1247 return Finder->matchesAncestorOf(Node, this->InnerMatcher, Builder,
1248 ASTMatchFinder::AMM_ParentOnly);
1252 /// \brief Matches nodes of type \c T that have at least one ancestor node of
1253 /// type \c AncestorT for which the given inner matcher matches.
1255 /// \c AncestorT must be an AST base type.
1256 template <typename T, typename AncestorT>
1257 class HasAncestorMatcher : public WrapperMatcherInterface<T> {
1258 static_assert(IsBaseType<AncestorT>::value,
1259 "has ancestor only accepts base type matcher");
1262 explicit HasAncestorMatcher(const Matcher<AncestorT> &AncestorMatcher)
1263 : HasAncestorMatcher::WrapperMatcherInterface(AncestorMatcher) {}
1265 bool matches(const T &Node, ASTMatchFinder *Finder,
1266 BoundNodesTreeBuilder *Builder) const override {
1267 return Finder->matchesAncestorOf(Node, this->InnerMatcher, Builder,
1268 ASTMatchFinder::AMM_All);
1272 /// \brief Matches nodes of type T that have at least one descendant node of
1273 /// type DescendantT for which the given inner matcher matches.
1275 /// DescendantT must be an AST base type.
1276 /// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match
1277 /// for each descendant node that matches instead of only for the first.
1278 template <typename T, typename DescendantT>
1279 class ForEachDescendantMatcher : public WrapperMatcherInterface<T> {
1280 static_assert(IsBaseType<DescendantT>::value,
1281 "for each descendant only accepts base type matcher");
1284 explicit ForEachDescendantMatcher(
1285 const Matcher<DescendantT> &DescendantMatcher)
1286 : ForEachDescendantMatcher::WrapperMatcherInterface(DescendantMatcher) {}
1288 bool matches(const T &Node, ASTMatchFinder *Finder,
1289 BoundNodesTreeBuilder *Builder) const override {
1290 return Finder->matchesDescendantOf(Node, this->InnerMatcher, Builder,
1291 ASTMatchFinder::BK_All);
1295 /// \brief Matches on nodes that have a getValue() method if getValue() equals
1296 /// the value the ValueEqualsMatcher was constructed with.
1297 template <typename T, typename ValueT>
1298 class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> {
1299 static_assert(std::is_base_of<CharacterLiteral, T>::value ||
1300 std::is_base_of<CXXBoolLiteralExpr, T>::value ||
1301 std::is_base_of<FloatingLiteral, T>::value ||
1302 std::is_base_of<IntegerLiteral, T>::value,
1303 "the node must have a getValue method");
1306 explicit ValueEqualsMatcher(const ValueT &ExpectedValue)
1307 : ExpectedValue(ExpectedValue) {}
1309 bool matchesNode(const T &Node) const override {
1310 return Node.getValue() == ExpectedValue;
1314 const ValueT ExpectedValue;
1317 /// \brief Template specializations to easily write matchers for floating point
1320 inline bool ValueEqualsMatcher<FloatingLiteral, double>::matchesNode(
1321 const FloatingLiteral &Node) const {
1322 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle)
1323 return Node.getValue().convertToFloat() == ExpectedValue;
1324 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble)
1325 return Node.getValue().convertToDouble() == ExpectedValue;
1329 inline bool ValueEqualsMatcher<FloatingLiteral, float>::matchesNode(
1330 const FloatingLiteral &Node) const {
1331 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle)
1332 return Node.getValue().convertToFloat() == ExpectedValue;
1333 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble)
1334 return Node.getValue().convertToDouble() == ExpectedValue;
1338 inline bool ValueEqualsMatcher<FloatingLiteral, llvm::APFloat>::matchesNode(
1339 const FloatingLiteral &Node) const {
1340 return ExpectedValue.compare(Node.getValue()) == llvm::APFloat::cmpEqual;
1343 /// \brief A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a
1344 /// variadic functor that takes a number of Matcher<TargetT> and returns a
1345 /// Matcher<SourceT> that matches TargetT nodes that are matched by all of the
1346 /// given matchers, if SourceT can be dynamically casted into TargetT.
1349 /// const VariadicDynCastAllOfMatcher<
1350 /// Decl, CXXRecordDecl> record;
1351 /// Creates a functor record(...) that creates a Matcher<Decl> given
1352 /// a variable number of arguments of type Matcher<CXXRecordDecl>.
1353 /// The returned matcher matches if the given Decl can by dynamically
1354 /// casted to CXXRecordDecl and all given matchers match.
1355 template <typename SourceT, typename TargetT>
1356 class VariadicDynCastAllOfMatcher
1357 : public llvm::VariadicFunction<
1358 BindableMatcher<SourceT>, Matcher<TargetT>,
1359 makeDynCastAllOfComposite<SourceT, TargetT> > {
1361 VariadicDynCastAllOfMatcher() {}
1364 /// \brief A \c VariadicAllOfMatcher<T> object is a variadic functor that takes
1365 /// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T
1366 /// nodes that are matched by all of the given matchers.
1369 /// const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
1370 /// Creates a functor nestedNameSpecifier(...) that creates a
1371 /// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type
1372 /// \c Matcher<NestedNameSpecifier>.
1373 /// The returned matcher matches if all given matchers match.
1374 template <typename T>
1375 class VariadicAllOfMatcher : public llvm::VariadicFunction<
1376 BindableMatcher<T>, Matcher<T>,
1377 makeAllOfComposite<T> > {
1379 VariadicAllOfMatcher() {}
1382 /// \brief Matches nodes of type \c TLoc for which the inner
1383 /// \c Matcher<T> matches.
1384 template <typename TLoc, typename T>
1385 class LocMatcher : public WrapperMatcherInterface<TLoc> {
1387 explicit LocMatcher(const Matcher<T> &InnerMatcher)
1388 : LocMatcher::WrapperMatcherInterface(InnerMatcher) {}
1390 bool matches(const TLoc &Node, ASTMatchFinder *Finder,
1391 BoundNodesTreeBuilder *Builder) const override {
1394 return this->InnerMatcher.matches(extract(Node), Finder, Builder);
1398 static ast_type_traits::DynTypedNode
1399 extract(const NestedNameSpecifierLoc &Loc) {
1400 return ast_type_traits::DynTypedNode::create(*Loc.getNestedNameSpecifier());
1404 /// \brief Matches \c TypeLocs based on an inner matcher matching a certain
1407 /// Used to implement the \c loc() matcher.
1408 class TypeLocTypeMatcher : public WrapperMatcherInterface<TypeLoc> {
1410 explicit TypeLocTypeMatcher(const Matcher<QualType> &InnerMatcher)
1411 : TypeLocTypeMatcher::WrapperMatcherInterface(InnerMatcher) {}
1413 bool matches(const TypeLoc &Node, ASTMatchFinder *Finder,
1414 BoundNodesTreeBuilder *Builder) const override {
1417 return this->InnerMatcher.matches(
1418 ast_type_traits::DynTypedNode::create(Node.getType()), Finder, Builder);
1422 /// \brief Matches nodes of type \c T for which the inner matcher matches on a
1423 /// another node of type \c T that can be reached using a given traverse
1425 template <typename T>
1426 class TypeTraverseMatcher : public WrapperMatcherInterface<T> {
1428 explicit TypeTraverseMatcher(const Matcher<QualType> &InnerMatcher,
1429 QualType (T::*TraverseFunction)() const)
1430 : TypeTraverseMatcher::WrapperMatcherInterface(InnerMatcher),
1431 TraverseFunction(TraverseFunction) {}
1433 bool matches(const T &Node, ASTMatchFinder *Finder,
1434 BoundNodesTreeBuilder *Builder) const override {
1435 QualType NextNode = (Node.*TraverseFunction)();
1436 if (NextNode.isNull())
1438 return this->InnerMatcher.matches(
1439 ast_type_traits::DynTypedNode::create(NextNode), Finder, Builder);
1443 QualType (T::*TraverseFunction)() const;
1446 /// \brief Matches nodes of type \c T in a ..Loc hierarchy, for which the inner
1447 /// matcher matches on a another node of type \c T that can be reached using a
1448 /// given traverse function.
1449 template <typename T>
1450 class TypeLocTraverseMatcher : public WrapperMatcherInterface<T> {
1452 explicit TypeLocTraverseMatcher(const Matcher<TypeLoc> &InnerMatcher,
1453 TypeLoc (T::*TraverseFunction)() const)
1454 : TypeLocTraverseMatcher::WrapperMatcherInterface(InnerMatcher),
1455 TraverseFunction(TraverseFunction) {}
1457 bool matches(const T &Node, ASTMatchFinder *Finder,
1458 BoundNodesTreeBuilder *Builder) const override {
1459 TypeLoc NextNode = (Node.*TraverseFunction)();
1462 return this->InnerMatcher.matches(
1463 ast_type_traits::DynTypedNode::create(NextNode), Finder, Builder);
1467 TypeLoc (T::*TraverseFunction)() const;
1470 /// \brief Converts a \c Matcher<InnerT> to a \c Matcher<OuterT>, where
1471 /// \c OuterT is any type that is supported by \c Getter.
1473 /// \code Getter<OuterT>::value() \endcode returns a
1474 /// \code InnerTBase (OuterT::*)() \endcode, which is used to adapt a \c OuterT
1475 /// object into a \c InnerT
1476 template <typename InnerTBase,
1477 template <typename OuterT> class Getter,
1478 template <typename OuterT> class MatcherImpl,
1479 typename ReturnTypesF>
1480 class TypeTraversePolymorphicMatcher {
1482 typedef TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl,
1484 static Self create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers);
1487 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes;
1489 explicit TypeTraversePolymorphicMatcher(
1490 ArrayRef<const Matcher<InnerTBase> *> InnerMatchers)
1491 : InnerMatcher(makeAllOfComposite(InnerMatchers)) {}
1493 template <typename OuterT> operator Matcher<OuterT>() const {
1494 return Matcher<OuterT>(
1495 new MatcherImpl<OuterT>(InnerMatcher, Getter<OuterT>::value()));
1498 struct Func : public llvm::VariadicFunction<Self, Matcher<InnerTBase>,
1504 const Matcher<InnerTBase> InnerMatcher;
1507 /// \brief A simple memoizer of T(*)() functions.
1509 /// It will call the passed 'Func' template parameter at most once.
1510 /// Used to support AST_MATCHER_FUNCTION() macro.
1511 template <typename Matcher, Matcher (*Func)()> class MemoizedMatcher {
1513 Wrapper() : M(Func()) {}
1518 static const Matcher &getInstance() {
1519 static llvm::ManagedStatic<Wrapper> Instance;
1524 // Define the create() method out of line to silence a GCC warning about
1525 // the struct "Func" having greater visibility than its base, which comes from
1526 // using the flag -fvisibility-inlines-hidden.
1527 template <typename InnerTBase, template <typename OuterT> class Getter,
1528 template <typename OuterT> class MatcherImpl, typename ReturnTypesF>
1529 TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl, ReturnTypesF>
1530 TypeTraversePolymorphicMatcher<
1531 InnerTBase, Getter, MatcherImpl,
1532 ReturnTypesF>::create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers) {
1533 return Self(InnerMatchers);
1536 // FIXME: unify ClassTemplateSpecializationDecl and TemplateSpecializationType's
1537 // APIs for accessing the template argument list.
1538 inline ArrayRef<TemplateArgument>
1539 getTemplateSpecializationArgs(const ClassTemplateSpecializationDecl &D) {
1540 return D.getTemplateArgs().asArray();
1543 inline ArrayRef<TemplateArgument>
1544 getTemplateSpecializationArgs(const TemplateSpecializationType &T) {
1545 return llvm::makeArrayRef(T.getArgs(), T.getNumArgs());
1548 struct NotEqualsBoundNodePredicate {
1549 bool operator()(const internal::BoundNodesMap &Nodes) const {
1550 return Nodes.getNode(ID) != Node;
1553 ast_type_traits::DynTypedNode Node;
1556 } // end namespace internal
1557 } // end namespace ast_matchers
1558 } // end namespace clang