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_AST_MATCHERS_AST_MATCHERS_INTERNAL_H
36 #define LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H
38 #include "clang/AST/ASTTypeTraits.h"
39 #include "clang/AST/DeclCXX.h"
40 #include "clang/AST/Decl.h"
41 #include "clang/AST/ExprCXX.h"
42 #include "clang/AST/StmtCXX.h"
43 #include "clang/AST/Stmt.h"
44 #include "clang/AST/Type.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/type_traits.h"
52 namespace ast_matchers {
54 /// FIXME: Move into the llvm support library.
55 template <bool> struct CompileAssert {};
56 #define TOOLING_COMPILE_ASSERT(Expr, Msg) \
57 typedef CompileAssert<(bool(Expr))> Msg[bool(Expr) ? 1 : -1]
63 class BoundNodesTreeBuilder;
64 /// \brief Internal version of BoundNodes. Holds all the bound nodes.
67 /// \brief Adds \c Node to the map with key \c ID.
69 /// The node's base type should be in NodeBaseType or it will be unaccessible.
71 void addNode(StringRef ID, const T* Node) {
72 NodeMap[ID] = ast_type_traits::DynTypedNode::create(*Node);
74 void addNode(StringRef ID, ast_type_traits::DynTypedNode Node) {
78 /// \brief Returns the AST node bound to \c ID.
80 /// Returns NULL if there was no node bound to \c ID or if there is a node but
81 /// it cannot be converted to the specified type.
83 const T *getNodeAs(StringRef ID) const {
84 IDToNodeMap::const_iterator It = NodeMap.find(ID);
85 if (It == NodeMap.end()) {
88 return It->second.get<T>();
91 /// \brief Copies all ID/Node pairs to BoundNodesTreeBuilder \c Builder.
92 void copyTo(BoundNodesTreeBuilder *Builder) const;
94 /// \brief Copies all ID/Node pairs to BoundNodesMap \c Other.
95 void copyTo(BoundNodesMap *Other) const;
98 /// \brief A map from IDs to the bound nodes.
99 typedef std::map<std::string, ast_type_traits::DynTypedNode> IDToNodeMap;
104 /// \brief A tree of bound nodes in match results.
106 /// If a match can contain multiple matches on the same node with different
107 /// matching subexpressions, BoundNodesTree contains a branch for each of
108 /// those matching subexpressions.
110 /// BoundNodesTree's are created during the matching process; when a match
111 /// is found, we iterate over the tree and create a BoundNodes object containing
112 /// the union of all bound nodes on the path from the root to a each leaf.
113 class BoundNodesTree {
115 /// \brief A visitor interface to visit all BoundNodes results for a
119 virtual ~Visitor() {}
121 /// \brief Called multiple times during a single call to VisitMatches(...).
123 /// 'BoundNodesView' contains the bound nodes for a single match.
124 virtual void visitMatch(const BoundNodes& BoundNodesView) = 0;
129 /// \brief Create a BoundNodesTree from pre-filled maps of bindings.
130 BoundNodesTree(const BoundNodesMap& Bindings,
131 const std::vector<BoundNodesTree> RecursiveBindings);
133 /// \brief Adds all bound nodes to \c Builder.
134 void copyTo(BoundNodesTreeBuilder* Builder) const;
136 /// \brief Visits all matches that this BoundNodesTree represents.
138 /// The ownership of 'ResultVisitor' remains at the caller.
139 void visitMatches(Visitor* ResultVisitor);
142 void visitMatchesRecursively(
143 Visitor* ResultVistior,
144 const BoundNodesMap& AggregatedBindings);
146 // FIXME: Find out whether we want to use different data structures here -
147 // first benchmarks indicate that it doesn't matter though.
149 BoundNodesMap Bindings;
151 std::vector<BoundNodesTree> RecursiveBindings;
154 /// \brief Creates BoundNodesTree objects.
156 /// The tree builder is used during the matching process to insert the bound
157 /// nodes from the Id matcher.
158 class BoundNodesTreeBuilder {
160 BoundNodesTreeBuilder();
162 /// \brief Add a binding from an id to a node.
163 template <typename T>
164 void setBinding(const std::string &Id, const T *Node) {
165 Bindings.addNode(Id, Node);
167 void setBinding(const std::string &Id, ast_type_traits::DynTypedNode Node) {
168 Bindings.addNode(Id, Node);
171 /// \brief Adds a branch in the tree.
172 void addMatch(const BoundNodesTree& Bindings);
174 /// \brief Returns a BoundNodes object containing all current bindings.
175 BoundNodesTree build() const;
178 BoundNodesTreeBuilder(const BoundNodesTreeBuilder &) LLVM_DELETED_FUNCTION;
179 void operator=(const BoundNodesTreeBuilder &) LLVM_DELETED_FUNCTION;
181 BoundNodesMap Bindings;
183 std::vector<BoundNodesTree> RecursiveBindings;
186 class ASTMatchFinder;
188 /// \brief Generic interface for matchers on an AST node of type T.
190 /// Implement this if your matcher may need to inspect the children or
191 /// descendants of the node or bind matched nodes to names. If you are
192 /// writing a simple matcher that only inspects properties of the
193 /// current node and doesn't care about its children or descendants,
194 /// implement SingleNodeMatcherInterface instead.
195 template <typename T>
196 class MatcherInterface : public RefCountedBaseVPTR {
198 virtual ~MatcherInterface() {}
200 /// \brief Returns true if 'Node' can be matched.
202 /// May bind 'Node' to an ID via 'Builder', or recurse into
203 /// the AST via 'Finder'.
204 virtual bool matches(const T &Node,
205 ASTMatchFinder *Finder,
206 BoundNodesTreeBuilder *Builder) const = 0;
209 /// \brief Interface for matchers that only evaluate properties on a single
211 template <typename T>
212 class SingleNodeMatcherInterface : public MatcherInterface<T> {
214 /// \brief Returns true if the matcher matches the provided node.
216 /// A subclass must implement this instead of Matches().
217 virtual bool matchesNode(const T &Node) const = 0;
220 /// Implements MatcherInterface::Matches.
221 virtual bool matches(const T &Node,
222 ASTMatchFinder * /* Finder */,
223 BoundNodesTreeBuilder * /* Builder */) const {
224 return matchesNode(Node);
228 /// \brief Base class for all matchers that works on a \c DynTypedNode.
230 /// Matcher implementations will check whether the \c DynTypedNode is
231 /// convertible into the respecitve types and then do the actual match
232 /// on the actual node, or return false if it is not convertible.
233 class DynTypedMatcher {
235 virtual ~DynTypedMatcher() {}
237 /// \brief Returns true if the matcher matches the given \c DynNode.
238 virtual bool matches(const ast_type_traits::DynTypedNode DynNode,
239 ASTMatchFinder *Finder,
240 BoundNodesTreeBuilder *Builder) const = 0;
242 /// \brief Returns a unique ID for the matcher.
243 virtual uint64_t getID() const = 0;
246 /// \brief Wrapper of a MatcherInterface<T> *that allows copying.
248 /// A Matcher<Base> can be used anywhere a Matcher<Derived> is
249 /// required. This establishes an is-a relationship which is reverse
250 /// to the AST hierarchy. In other words, Matcher<T> is contravariant
251 /// with respect to T. The relationship is built via a type conversion
252 /// operator rather than a type hierarchy to be able to templatize the
253 /// type hierarchy instead of spelling it out.
254 template <typename T>
255 class Matcher : public DynTypedMatcher {
257 /// \brief Takes ownership of the provided implementation pointer.
258 explicit Matcher(MatcherInterface<T> *Implementation)
259 : Implementation(Implementation) {}
261 /// \brief Implicitly converts \c Other to a Matcher<T>.
263 /// Requires \c T to be derived from \c From.
264 template <typename From>
265 Matcher(const Matcher<From> &Other,
266 typename llvm::enable_if_c<
267 llvm::is_base_of<From, T>::value &&
268 !llvm::is_same<From, T>::value >::type* = 0)
269 : Implementation(new ImplicitCastMatcher<From>(Other)) {}
271 /// \brief Implicitly converts \c Matcher<Type> to \c Matcher<QualType>.
273 /// The resulting matcher is not strict, i.e. ignores qualifiers.
274 template <typename TypeT>
275 Matcher(const Matcher<TypeT> &Other,
276 typename llvm::enable_if_c<
277 llvm::is_same<T, QualType>::value &&
278 llvm::is_same<TypeT, Type>::value >::type* = 0)
279 : Implementation(new TypeToQualType<TypeT>(Other)) {}
281 /// \brief Forwards the call to the underlying MatcherInterface<T> pointer.
282 bool matches(const T &Node,
283 ASTMatchFinder *Finder,
284 BoundNodesTreeBuilder *Builder) const {
285 return Implementation->matches(Node, Finder, Builder);
288 /// \brief Returns an ID that uniquely identifies the matcher.
289 uint64_t getID() const {
290 /// FIXME: Document the requirements this imposes on matcher
291 /// implementations (no new() implementation_ during a Matches()).
292 return reinterpret_cast<uint64_t>(Implementation.getPtr());
295 /// \brief Returns whether the matcher matches on the given \c DynNode.
296 virtual bool matches(const ast_type_traits::DynTypedNode DynNode,
297 ASTMatchFinder *Finder,
298 BoundNodesTreeBuilder *Builder) const {
299 const T *Node = DynNode.get<T>();
300 if (!Node) return false;
301 return matches(*Node, Finder, Builder);
304 /// \brief Allows the conversion of a \c Matcher<Type> to a \c
305 /// Matcher<QualType>.
307 /// Depending on the constructor argument, the matcher is either strict, i.e.
308 /// does only matches in the absence of qualifiers, or not, i.e. simply
309 /// ignores any qualifiers.
310 template <typename TypeT>
311 class TypeToQualType : public MatcherInterface<QualType> {
313 TypeToQualType(const Matcher<TypeT> &InnerMatcher)
314 : InnerMatcher(InnerMatcher) {}
316 virtual bool matches(const QualType &Node,
317 ASTMatchFinder *Finder,
318 BoundNodesTreeBuilder *Builder) const {
321 return InnerMatcher.matches(*Node, Finder, Builder);
324 const Matcher<TypeT> InnerMatcher;
328 /// \brief Allows conversion from Matcher<Base> to Matcher<T> if T
329 /// is derived from Base.
330 template <typename Base>
331 class ImplicitCastMatcher : public MatcherInterface<T> {
333 explicit ImplicitCastMatcher(const Matcher<Base> &From)
336 virtual bool matches(const T &Node,
337 ASTMatchFinder *Finder,
338 BoundNodesTreeBuilder *Builder) const {
339 return From.matches(Node, Finder, Builder);
343 const Matcher<Base> From;
346 IntrusiveRefCntPtr< MatcherInterface<T> > Implementation;
349 /// \brief A convenient helper for creating a Matcher<T> without specifying
350 /// the template type argument.
351 template <typename T>
352 inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) {
353 return Matcher<T>(Implementation);
356 /// \brief Metafunction to determine if type T has a member called getDecl.
357 template <typename T> struct has_getDecl {
358 struct Default { int getDecl; };
359 struct Derived : T, Default { };
361 template<typename C, C> struct CheckT;
363 // If T::getDecl exists, an ambiguity arises and CheckT will
364 // not be instantiable. This makes f(...) the only available
367 static char (&f(CheckT<int Default::*, &C::getDecl>*))[1];
368 template<typename C> static char (&f(...))[2];
370 static bool const value = sizeof(f<Derived>(0)) == 2;
373 /// \brief Matches overloaded operators with a specific name.
375 /// The type argument ArgT is not used by this matcher but is used by
376 /// PolymorphicMatcherWithParam1 and should be StringRef.
377 template <typename T, typename ArgT>
378 class HasOverloadedOperatorNameMatcher : public SingleNodeMatcherInterface<T> {
379 TOOLING_COMPILE_ASSERT((llvm::is_same<T, CXXOperatorCallExpr>::value ||
380 llvm::is_same<T, CXXMethodDecl>::value),
381 unsupported_class_for_matcher);
382 TOOLING_COMPILE_ASSERT((llvm::is_same<ArgT, StringRef>::value),
383 argument_type_must_be_StringRef);
385 explicit HasOverloadedOperatorNameMatcher(const StringRef Name)
386 : SingleNodeMatcherInterface<T>(), Name(Name) {}
388 virtual bool matchesNode(const T &Node) const LLVM_OVERRIDE {
389 return matchesSpecialized(Node);
394 /// \brief CXXOperatorCallExpr exist only for calls to overloaded operators
395 /// so this function returns true if the call is to an operator of the given
397 bool matchesSpecialized(const CXXOperatorCallExpr &Node) const {
398 return getOperatorSpelling(Node.getOperator()) == Name;
401 /// \brief Returns true only if CXXMethodDecl represents an overloaded
402 /// operator and has the given operator name.
403 bool matchesSpecialized(const CXXMethodDecl &Node) const {
404 return Node.isOverloadedOperator() &&
405 getOperatorSpelling(Node.getOverloadedOperator()) == Name;
411 /// \brief Matches declarations for QualType and CallExpr.
413 /// Type argument DeclMatcherT is required by PolymorphicMatcherWithParam1 but
414 /// not actually used.
415 template <typename T, typename DeclMatcherT>
416 class HasDeclarationMatcher : public MatcherInterface<T> {
417 TOOLING_COMPILE_ASSERT((llvm::is_same< DeclMatcherT,
418 Matcher<Decl> >::value),
419 instantiated_with_wrong_types);
421 explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher)
422 : InnerMatcher(InnerMatcher) {}
424 virtual bool matches(const T &Node,
425 ASTMatchFinder *Finder,
426 BoundNodesTreeBuilder *Builder) const {
427 return matchesSpecialized(Node, Finder, Builder);
431 /// \brief If getDecl exists as a member of U, returns whether the inner
432 /// matcher matches Node.getDecl().
433 template <typename U>
434 bool matchesSpecialized(
435 const U &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder,
436 typename llvm::enable_if<has_getDecl<U>, int>::type = 0) const {
437 return matchesDecl(Node.getDecl(), Finder, Builder);
440 /// \brief Extracts the CXXRecordDecl or EnumDecl of a QualType and returns
441 /// whether the inner matcher matches on it.
442 bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder,
443 BoundNodesTreeBuilder *Builder) const {
444 /// FIXME: Add other ways to convert...
447 if (const EnumType *AsEnum = dyn_cast<EnumType>(Node.getTypePtr()))
448 return matchesDecl(AsEnum->getDecl(), Finder, Builder);
449 return matchesDecl(Node->getAsCXXRecordDecl(), Finder, Builder);
452 /// \brief Gets the TemplateDecl from a TemplateSpecializationType
453 /// and returns whether the inner matches on it.
454 bool matchesSpecialized(const TemplateSpecializationType &Node,
455 ASTMatchFinder *Finder,
456 BoundNodesTreeBuilder *Builder) const {
457 return matchesDecl(Node.getTemplateName().getAsTemplateDecl(),
461 /// \brief Extracts the Decl of the callee of a CallExpr and returns whether
462 /// the inner matcher matches on it.
463 bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder,
464 BoundNodesTreeBuilder *Builder) const {
465 return matchesDecl(Node.getCalleeDecl(), Finder, Builder);
468 /// \brief Extracts the Decl of the constructor call and returns whether the
469 /// inner matcher matches on it.
470 bool matchesSpecialized(const CXXConstructExpr &Node,
471 ASTMatchFinder *Finder,
472 BoundNodesTreeBuilder *Builder) const {
473 return matchesDecl(Node.getConstructor(), Finder, Builder);
476 /// \brief Extracts the \c ValueDecl a \c MemberExpr refers to and returns
477 /// whether the inner matcher matches on it.
478 bool matchesSpecialized(const MemberExpr &Node,
479 ASTMatchFinder *Finder,
480 BoundNodesTreeBuilder *Builder) const {
481 return matchesDecl(Node.getMemberDecl(), Finder, Builder);
484 /// \brief Returns whether the inner matcher \c Node. Returns false if \c Node
486 bool matchesDecl(const Decl *Node,
487 ASTMatchFinder *Finder,
488 BoundNodesTreeBuilder *Builder) const {
489 return Node != NULL && InnerMatcher.matches(*Node, Finder, Builder);
492 const Matcher<Decl> InnerMatcher;
495 /// \brief IsBaseType<T>::value is true if T is a "base" type in the AST
496 /// node class hierarchies.
497 template <typename T>
499 static const bool value =
500 (llvm::is_same<T, Decl>::value ||
501 llvm::is_same<T, Stmt>::value ||
502 llvm::is_same<T, QualType>::value ||
503 llvm::is_same<T, Type>::value ||
504 llvm::is_same<T, TypeLoc>::value ||
505 llvm::is_same<T, NestedNameSpecifier>::value ||
506 llvm::is_same<T, NestedNameSpecifierLoc>::value ||
507 llvm::is_same<T, CXXCtorInitializer>::value);
509 template <typename T>
510 const bool IsBaseType<T>::value;
512 /// \brief Interface that allows matchers to traverse the AST.
513 /// FIXME: Find a better name.
515 /// This provides three entry methods for each base node type in the AST:
516 /// - \c matchesChildOf:
517 /// Matches a matcher on every child node of the given node. Returns true
518 /// if at least one child node could be matched.
519 /// - \c matchesDescendantOf:
520 /// Matches a matcher on all descendant nodes of the given node. Returns true
521 /// if at least one descendant matched.
522 /// - \c matchesAncestorOf:
523 /// Matches a matcher on all ancestors of the given node. Returns true if
524 /// at least one ancestor matched.
526 /// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal.
527 /// In the future, we wan to implement this for all nodes for which it makes
528 /// sense. In the case of matchesAncestorOf, we'll want to implement it for
529 /// all nodes, as all nodes have ancestors.
530 class ASTMatchFinder {
532 /// \brief Defines how we descend a level in the AST when we pass
533 /// through expressions.
535 /// Will traverse any child nodes.
537 /// Will not traverse implicit casts and parentheses.
538 TK_IgnoreImplicitCastsAndParentheses
541 /// \brief Defines how bindings are processed on recursive matches.
543 /// Stop at the first match and only bind the first match.
545 /// Create results for all combinations of bindings that match.
549 /// \brief Defines which ancestors are considered for a match.
550 enum AncestorMatchMode {
553 /// Direct parent only.
557 virtual ~ASTMatchFinder() {}
559 /// \brief Returns true if the given class is directly or indirectly derived
560 /// from a base type matching \c base.
562 /// A class is considered to be also derived from itself.
563 virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
564 const Matcher<NamedDecl> &Base,
565 BoundNodesTreeBuilder *Builder) = 0;
567 template <typename T>
568 bool matchesChildOf(const T &Node,
569 const DynTypedMatcher &Matcher,
570 BoundNodesTreeBuilder *Builder,
571 TraversalKind Traverse,
573 TOOLING_COMPILE_ASSERT(
574 (llvm::is_base_of<Decl, T>::value ||
575 llvm::is_base_of<Stmt, T>::value ||
576 llvm::is_base_of<NestedNameSpecifier, T>::value ||
577 llvm::is_base_of<NestedNameSpecifierLoc, T>::value ||
578 llvm::is_base_of<TypeLoc, T>::value ||
579 llvm::is_base_of<QualType, T>::value),
580 unsupported_type_for_recursive_matching);
581 return matchesChildOf(ast_type_traits::DynTypedNode::create(Node),
582 Matcher, Builder, Traverse, Bind);
585 template <typename T>
586 bool matchesDescendantOf(const T &Node,
587 const DynTypedMatcher &Matcher,
588 BoundNodesTreeBuilder *Builder,
590 TOOLING_COMPILE_ASSERT(
591 (llvm::is_base_of<Decl, T>::value ||
592 llvm::is_base_of<Stmt, T>::value ||
593 llvm::is_base_of<NestedNameSpecifier, T>::value ||
594 llvm::is_base_of<NestedNameSpecifierLoc, T>::value ||
595 llvm::is_base_of<TypeLoc, T>::value ||
596 llvm::is_base_of<QualType, T>::value),
597 unsupported_type_for_recursive_matching);
598 return matchesDescendantOf(ast_type_traits::DynTypedNode::create(Node),
599 Matcher, Builder, Bind);
602 // FIXME: Implement support for BindKind.
603 template <typename T>
604 bool matchesAncestorOf(const T &Node,
605 const DynTypedMatcher &Matcher,
606 BoundNodesTreeBuilder *Builder,
607 AncestorMatchMode MatchMode) {
608 TOOLING_COMPILE_ASSERT((llvm::is_base_of<Decl, T>::value ||
609 llvm::is_base_of<Stmt, T>::value),
610 only_Decl_or_Stmt_allowed_for_recursive_matching);
611 return matchesAncestorOf(ast_type_traits::DynTypedNode::create(Node),
612 Matcher, Builder, MatchMode);
615 virtual ASTContext &getASTContext() const = 0;
618 virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node,
619 const DynTypedMatcher &Matcher,
620 BoundNodesTreeBuilder *Builder,
621 TraversalKind Traverse,
624 virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node,
625 const DynTypedMatcher &Matcher,
626 BoundNodesTreeBuilder *Builder,
629 virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node,
630 const DynTypedMatcher &Matcher,
631 BoundNodesTreeBuilder *Builder,
632 AncestorMatchMode MatchMode) = 0;
635 /// \brief Converts a \c Matcher<T> to a matcher of desired type \c To by
636 /// "adapting" a \c To into a \c T.
638 /// The \c ArgumentAdapterT argument specifies how the adaptation is done.
641 /// \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher);
642 /// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher
643 /// that is convertible into any matcher of type \c To by constructing
644 /// \c HasMatcher<To, T>(InnerMatcher).
646 /// If a matcher does not need knowledge about the inner type, prefer to use
647 /// PolymorphicMatcherWithParam1.
648 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
650 class ArgumentAdaptingMatcher {
652 explicit ArgumentAdaptingMatcher(const Matcher<T> &InnerMatcher)
653 : InnerMatcher(InnerMatcher) {}
655 template <typename To>
656 operator Matcher<To>() const {
657 return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher));
661 const Matcher<T> InnerMatcher;
664 /// \brief A PolymorphicMatcherWithParamN<MatcherT, P1, ..., PN> object can be
665 /// created from N parameters p1, ..., pN (of type P1, ..., PN) and
666 /// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN)
667 /// can be constructed.
670 /// - PolymorphicMatcherWithParam0<IsDefinitionMatcher>()
671 /// creates an object that can be used as a Matcher<T> for any type T
672 /// where an IsDefinitionMatcher<T>() can be constructed.
673 /// - PolymorphicMatcherWithParam1<ValueEqualsMatcher, int>(42)
674 /// creates an object that can be used as a Matcher<T> for any type T
675 /// where a ValueEqualsMatcher<T, int>(42) can be constructed.
676 template <template <typename T> class MatcherT>
677 class PolymorphicMatcherWithParam0 {
679 template <typename T>
680 operator Matcher<T>() const {
681 return Matcher<T>(new MatcherT<T>());
685 template <template <typename T, typename P1> class MatcherT,
687 class PolymorphicMatcherWithParam1 {
689 explicit PolymorphicMatcherWithParam1(const P1 &Param1)
692 template <typename T>
693 operator Matcher<T>() const {
694 return Matcher<T>(new MatcherT<T, P1>(Param1));
701 template <template <typename T, typename P1, typename P2> class MatcherT,
702 typename P1, typename P2>
703 class PolymorphicMatcherWithParam2 {
705 PolymorphicMatcherWithParam2(const P1 &Param1, const P2 &Param2)
706 : Param1(Param1), Param2(Param2) {}
708 template <typename T>
709 operator Matcher<T>() const {
710 return Matcher<T>(new MatcherT<T, P1, P2>(Param1, Param2));
718 /// \brief Matches any instance of the given NodeType.
720 /// This is useful when a matcher syntactically requires a child matcher,
721 /// but the context doesn't care. See for example: anything().
723 /// FIXME: Alternatively we could also create a IsAMatcher or something
724 /// that checks that a dyn_cast is possible. This is purely needed for the
725 /// difference between calling for example:
728 /// record(SomeMatcher)
729 /// In the second case we need the correct type we were dyn_cast'ed to in order
730 /// to get the right type for the inner matcher. In the first case we don't need
731 /// that, but we use the type conversion anyway and insert a TrueMatcher.
732 template <typename T>
733 class TrueMatcher : public SingleNodeMatcherInterface<T> {
735 virtual bool matchesNode(const T &Node) const {
740 /// \brief Provides a MatcherInterface<T> for a Matcher<To> that matches if T is
741 /// dyn_cast'able into To and the given Matcher<To> matches on the dyn_cast'ed
743 template <typename T, typename To>
744 class DynCastMatcher : public MatcherInterface<T> {
746 explicit DynCastMatcher(const Matcher<To> &InnerMatcher)
747 : InnerMatcher(InnerMatcher) {}
749 virtual bool matches(const T &Node,
750 ASTMatchFinder *Finder,
751 BoundNodesTreeBuilder *Builder) const {
752 const To *InnerMatchValue = dyn_cast<To>(&Node);
753 return InnerMatchValue != NULL &&
754 InnerMatcher.matches(*InnerMatchValue, Finder, Builder);
758 const Matcher<To> InnerMatcher;
761 /// \brief Matcher<T> that wraps an inner Matcher<T> and binds the matched node
762 /// to an ID if the inner matcher matches on the node.
763 template <typename T>
764 class IdMatcher : public MatcherInterface<T> {
766 /// \brief Creates an IdMatcher that binds to 'ID' if 'InnerMatcher' matches
768 IdMatcher(StringRef ID, const Matcher<T> &InnerMatcher)
769 : ID(ID), InnerMatcher(InnerMatcher) {}
771 virtual bool matches(const T &Node,
772 ASTMatchFinder *Finder,
773 BoundNodesTreeBuilder *Builder) const {
774 bool Result = InnerMatcher.matches(Node, Finder, Builder);
776 Builder->setBinding(ID, &Node);
782 const std::string ID;
783 const Matcher<T> InnerMatcher;
786 /// \brief A Matcher that allows binding the node it matches to an id.
788 /// BindableMatcher provides a \a bind() method that allows binding the
789 /// matched node to an id if the match was successful.
790 template <typename T>
791 class BindableMatcher : public Matcher<T> {
793 BindableMatcher(MatcherInterface<T> *Implementation)
794 : Matcher<T>(Implementation) {}
796 /// \brief Returns a matcher that will bind the matched node on a match.
798 /// The returned matcher is equivalent to this matcher, but will
799 /// bind the matched node on a match.
800 Matcher<T> bind(StringRef ID) const {
801 return Matcher<T>(new IdMatcher<T>(ID, *this));
805 /// \brief Matches nodes of type T that have child nodes of type ChildT for
806 /// which a specified child matcher matches.
808 /// ChildT must be an AST base type.
809 template <typename T, typename ChildT>
810 class HasMatcher : public MatcherInterface<T> {
811 TOOLING_COMPILE_ASSERT(IsBaseType<ChildT>::value,
812 has_only_accepts_base_type_matcher);
814 explicit HasMatcher(const Matcher<ChildT> &ChildMatcher)
815 : ChildMatcher(ChildMatcher) {}
817 virtual bool matches(const T &Node,
818 ASTMatchFinder *Finder,
819 BoundNodesTreeBuilder *Builder) const {
820 return Finder->matchesChildOf(
821 Node, ChildMatcher, Builder,
822 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
823 ASTMatchFinder::BK_First);
827 const Matcher<ChildT> ChildMatcher;
830 /// \brief Matches nodes of type T that have child nodes of type ChildT for
831 /// which a specified child matcher matches. ChildT must be an AST base
833 /// As opposed to the HasMatcher, the ForEachMatcher will produce a match
834 /// for each child that matches.
835 template <typename T, typename ChildT>
836 class ForEachMatcher : public MatcherInterface<T> {
837 TOOLING_COMPILE_ASSERT(IsBaseType<ChildT>::value,
838 for_each_only_accepts_base_type_matcher);
840 explicit ForEachMatcher(const Matcher<ChildT> &ChildMatcher)
841 : ChildMatcher(ChildMatcher) {}
843 virtual bool matches(const T& Node,
844 ASTMatchFinder* Finder,
845 BoundNodesTreeBuilder* Builder) const {
846 return Finder->matchesChildOf(
847 Node, ChildMatcher, Builder,
848 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses,
849 ASTMatchFinder::BK_All);
853 const Matcher<ChildT> ChildMatcher;
856 /// \brief Matches nodes of type T if the given Matcher<T> does not match.
858 /// Type argument MatcherT is required by PolymorphicMatcherWithParam1
859 /// but not actually used. It will always be instantiated with a type
860 /// convertible to Matcher<T>.
861 template <typename T, typename MatcherT>
862 class NotMatcher : public MatcherInterface<T> {
864 explicit NotMatcher(const Matcher<T> &InnerMatcher)
865 : InnerMatcher(InnerMatcher) {}
867 virtual bool matches(const T &Node,
868 ASTMatchFinder *Finder,
869 BoundNodesTreeBuilder *Builder) const {
870 return !InnerMatcher.matches(Node, Finder, Builder);
874 const Matcher<T> InnerMatcher;
877 /// \brief Matches nodes of type T for which both provided matchers match.
879 /// Type arguments MatcherT1 and MatcherT2 are required by
880 /// PolymorphicMatcherWithParam2 but not actually used. They will
881 /// always be instantiated with types convertible to Matcher<T>.
882 template <typename T, typename MatcherT1, typename MatcherT2>
883 class AllOfMatcher : public MatcherInterface<T> {
885 AllOfMatcher(const Matcher<T> &InnerMatcher1, const Matcher<T> &InnerMatcher2)
886 : InnerMatcher1(InnerMatcher1), InnerMatcher2(InnerMatcher2) {}
888 virtual bool matches(const T &Node,
889 ASTMatchFinder *Finder,
890 BoundNodesTreeBuilder *Builder) const {
891 return InnerMatcher1.matches(Node, Finder, Builder) &&
892 InnerMatcher2.matches(Node, Finder, Builder);
896 const Matcher<T> InnerMatcher1;
897 const Matcher<T> InnerMatcher2;
900 /// \brief Matches nodes of type T for which at least one of the two provided
901 /// matchers matches.
903 /// Type arguments MatcherT1 and MatcherT2 are
904 /// required by PolymorphicMatcherWithParam2 but not actually
905 /// used. They will always be instantiated with types convertible to
907 template <typename T, typename MatcherT1, typename MatcherT2>
908 class EachOfMatcher : public MatcherInterface<T> {
910 EachOfMatcher(const Matcher<T> &InnerMatcher1,
911 const Matcher<T> &InnerMatcher2)
912 : InnerMatcher1(InnerMatcher1), InnerMatcher2(InnerMatcher2) {
915 virtual bool matches(const T &Node, ASTMatchFinder *Finder,
916 BoundNodesTreeBuilder *Builder) const {
917 BoundNodesTreeBuilder Builder1;
918 bool Matched1 = InnerMatcher1.matches(Node, Finder, &Builder1);
920 Builder->addMatch(Builder1.build());
922 BoundNodesTreeBuilder Builder2;
923 bool Matched2 = InnerMatcher2.matches(Node, Finder, &Builder2);
925 Builder->addMatch(Builder2.build());
927 return Matched1 || Matched2;
931 const Matcher<T> InnerMatcher1;
932 const Matcher<T> InnerMatcher2;
935 /// \brief Matches nodes of type T for which at least one of the two provided
936 /// matchers matches.
938 /// Type arguments MatcherT1 and MatcherT2 are
939 /// required by PolymorphicMatcherWithParam2 but not actually
940 /// used. They will always be instantiated with types convertible to
942 template <typename T, typename MatcherT1, typename MatcherT2>
943 class AnyOfMatcher : public MatcherInterface<T> {
945 AnyOfMatcher(const Matcher<T> &InnerMatcher1, const Matcher<T> &InnerMatcher2)
946 : InnerMatcher1(InnerMatcher1), InnerMatcher2(InnerMatcher2) {}
948 virtual bool matches(const T &Node,
949 ASTMatchFinder *Finder,
950 BoundNodesTreeBuilder *Builder) const {
951 return InnerMatcher1.matches(Node, Finder, Builder) ||
952 InnerMatcher2.matches(Node, Finder, Builder);
956 const Matcher<T> InnerMatcher1;
957 const Matcher<T> InnerMatcher2;
960 /// \brief Creates a Matcher<T> that matches if all inner matchers match.
962 BindableMatcher<T> makeAllOfComposite(
963 ArrayRef<const Matcher<T> *> InnerMatchers) {
964 if (InnerMatchers.empty())
965 return BindableMatcher<T>(new TrueMatcher<T>);
966 MatcherInterface<T> *InnerMatcher = new TrueMatcher<T>;
967 for (int i = InnerMatchers.size() - 1; i >= 0; --i) {
968 InnerMatcher = new AllOfMatcher<T, Matcher<T>, Matcher<T> >(
969 *InnerMatchers[i], makeMatcher(InnerMatcher));
971 return BindableMatcher<T>(InnerMatcher);
974 /// \brief Creates a Matcher<T> that matches if
975 /// T is dyn_cast'able into InnerT and all inner matchers match.
977 /// Returns BindableMatcher, as matchers that use dyn_cast have
978 /// the same object both to match on and to run submatchers on,
979 /// so there is no ambiguity with what gets bound.
980 template<typename T, typename InnerT>
981 BindableMatcher<T> makeDynCastAllOfComposite(
982 ArrayRef<const Matcher<InnerT> *> InnerMatchers) {
983 return BindableMatcher<T>(new DynCastMatcher<T, InnerT>(
984 makeAllOfComposite(InnerMatchers)));
987 /// \brief Matches nodes of type T that have at least one descendant node of
988 /// type DescendantT for which the given inner matcher matches.
990 /// DescendantT must be an AST base type.
991 template <typename T, typename DescendantT>
992 class HasDescendantMatcher : public MatcherInterface<T> {
993 TOOLING_COMPILE_ASSERT(IsBaseType<DescendantT>::value,
994 has_descendant_only_accepts_base_type_matcher);
996 explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher)
997 : DescendantMatcher(DescendantMatcher) {}
999 virtual bool matches(const T &Node,
1000 ASTMatchFinder *Finder,
1001 BoundNodesTreeBuilder *Builder) const {
1002 return Finder->matchesDescendantOf(
1003 Node, DescendantMatcher, Builder, ASTMatchFinder::BK_First);
1007 const Matcher<DescendantT> DescendantMatcher;
1010 /// \brief Matches nodes of type \c T that have a parent node of type \c ParentT
1011 /// for which the given inner matcher matches.
1013 /// \c ParentT must be an AST base type.
1014 template <typename T, typename ParentT>
1015 class HasParentMatcher : public MatcherInterface<T> {
1016 TOOLING_COMPILE_ASSERT(IsBaseType<ParentT>::value,
1017 has_parent_only_accepts_base_type_matcher);
1019 explicit HasParentMatcher(const Matcher<ParentT> &ParentMatcher)
1020 : ParentMatcher(ParentMatcher) {}
1022 virtual bool matches(const T &Node,
1023 ASTMatchFinder *Finder,
1024 BoundNodesTreeBuilder *Builder) const {
1025 return Finder->matchesAncestorOf(
1026 Node, ParentMatcher, Builder, ASTMatchFinder::AMM_ParentOnly);
1030 const Matcher<ParentT> ParentMatcher;
1033 /// \brief Matches nodes of type \c T that have at least one ancestor node of
1034 /// type \c AncestorT for which the given inner matcher matches.
1036 /// \c AncestorT must be an AST base type.
1037 template <typename T, typename AncestorT>
1038 class HasAncestorMatcher : public MatcherInterface<T> {
1039 TOOLING_COMPILE_ASSERT(IsBaseType<AncestorT>::value,
1040 has_ancestor_only_accepts_base_type_matcher);
1042 explicit HasAncestorMatcher(const Matcher<AncestorT> &AncestorMatcher)
1043 : AncestorMatcher(AncestorMatcher) {}
1045 virtual bool matches(const T &Node,
1046 ASTMatchFinder *Finder,
1047 BoundNodesTreeBuilder *Builder) const {
1048 return Finder->matchesAncestorOf(
1049 Node, AncestorMatcher, Builder, ASTMatchFinder::AMM_All);
1053 const Matcher<AncestorT> AncestorMatcher;
1056 /// \brief Matches nodes of type T that have at least one descendant node of
1057 /// type DescendantT for which the given inner matcher matches.
1059 /// DescendantT must be an AST base type.
1060 /// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match
1061 /// for each descendant node that matches instead of only for the first.
1062 template <typename T, typename DescendantT>
1063 class ForEachDescendantMatcher : public MatcherInterface<T> {
1064 TOOLING_COMPILE_ASSERT(IsBaseType<DescendantT>::value,
1065 for_each_descendant_only_accepts_base_type_matcher);
1067 explicit ForEachDescendantMatcher(
1068 const Matcher<DescendantT>& DescendantMatcher)
1069 : DescendantMatcher(DescendantMatcher) {}
1071 virtual bool matches(const T& Node,
1072 ASTMatchFinder* Finder,
1073 BoundNodesTreeBuilder* Builder) const {
1074 return Finder->matchesDescendantOf(Node, DescendantMatcher, Builder,
1075 ASTMatchFinder::BK_All);
1079 const Matcher<DescendantT> DescendantMatcher;
1082 /// \brief Matches on nodes that have a getValue() method if getValue() equals
1083 /// the value the ValueEqualsMatcher was constructed with.
1084 template <typename T, typename ValueT>
1085 class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> {
1086 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CharacterLiteral, T>::value ||
1087 llvm::is_base_of<CXXBoolLiteralExpr,
1089 llvm::is_base_of<FloatingLiteral, T>::value ||
1090 llvm::is_base_of<IntegerLiteral, T>::value),
1091 the_node_must_have_a_getValue_method);
1093 explicit ValueEqualsMatcher(const ValueT &ExpectedValue)
1094 : ExpectedValue(ExpectedValue) {}
1096 virtual bool matchesNode(const T &Node) const {
1097 return Node.getValue() == ExpectedValue;
1101 const ValueT ExpectedValue;
1104 /// \brief A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a
1105 /// variadic functor that takes a number of Matcher<TargetT> and returns a
1106 /// Matcher<SourceT> that matches TargetT nodes that are matched by all of the
1107 /// given matchers, if SourceT can be dynamically casted into TargetT.
1110 /// const VariadicDynCastAllOfMatcher<
1111 /// Decl, CXXRecordDecl> record;
1112 /// Creates a functor record(...) that creates a Matcher<Decl> given
1113 /// a variable number of arguments of type Matcher<CXXRecordDecl>.
1114 /// The returned matcher matches if the given Decl can by dynamically
1115 /// casted to CXXRecordDecl and all given matchers match.
1116 template <typename SourceT, typename TargetT>
1117 class VariadicDynCastAllOfMatcher
1118 : public llvm::VariadicFunction<
1119 BindableMatcher<SourceT>, Matcher<TargetT>,
1120 makeDynCastAllOfComposite<SourceT, TargetT> > {
1122 VariadicDynCastAllOfMatcher() {}
1125 /// \brief A \c VariadicAllOfMatcher<T> object is a variadic functor that takes
1126 /// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T
1127 /// nodes that are matched by all of the given matchers.
1130 /// const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
1131 /// Creates a functor nestedNameSpecifier(...) that creates a
1132 /// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type
1133 /// \c Matcher<NestedNameSpecifier>.
1134 /// The returned matcher matches if all given matchers match.
1135 template <typename T>
1136 class VariadicAllOfMatcher : public llvm::VariadicFunction<
1137 BindableMatcher<T>, Matcher<T>,
1138 makeAllOfComposite<T> > {
1140 VariadicAllOfMatcher() {}
1143 /// \brief Matches nodes of type \c TLoc for which the inner
1144 /// \c Matcher<T> matches.
1145 template <typename TLoc, typename T>
1146 class LocMatcher : public MatcherInterface<TLoc> {
1148 explicit LocMatcher(const Matcher<T> &InnerMatcher)
1149 : InnerMatcher(InnerMatcher) {}
1151 virtual bool matches(const TLoc &Node,
1152 ASTMatchFinder *Finder,
1153 BoundNodesTreeBuilder *Builder) const {
1156 return InnerMatcher.matches(*extract(Node), Finder, Builder);
1160 const NestedNameSpecifier *extract(const NestedNameSpecifierLoc &Loc) const {
1161 return Loc.getNestedNameSpecifier();
1164 const Matcher<T> InnerMatcher;
1167 /// \brief Matches \c TypeLocs based on an inner matcher matching a certain
1170 /// Used to implement the \c loc() matcher.
1171 class TypeLocTypeMatcher : public MatcherInterface<TypeLoc> {
1173 explicit TypeLocTypeMatcher(const Matcher<QualType> &InnerMatcher)
1174 : InnerMatcher(InnerMatcher) {}
1176 virtual bool matches(const TypeLoc &Node,
1177 ASTMatchFinder *Finder,
1178 BoundNodesTreeBuilder *Builder) const {
1181 return InnerMatcher.matches(Node.getType(), Finder, Builder);
1185 const Matcher<QualType> InnerMatcher;
1188 /// \brief Matches nodes of type \c T for which the inner matcher matches on a
1189 /// another node of type \c T that can be reached using a given traverse
1191 template <typename T>
1192 class TypeTraverseMatcher : public MatcherInterface<T> {
1194 explicit TypeTraverseMatcher(const Matcher<QualType> &InnerMatcher,
1195 QualType (T::*TraverseFunction)() const)
1196 : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {}
1198 virtual bool matches(const T &Node,
1199 ASTMatchFinder *Finder,
1200 BoundNodesTreeBuilder *Builder) const {
1201 QualType NextNode = (Node.*TraverseFunction)();
1202 if (NextNode.isNull())
1204 return InnerMatcher.matches(NextNode, Finder, Builder);
1208 const Matcher<QualType> InnerMatcher;
1209 QualType (T::*TraverseFunction)() const;
1212 /// \brief Matches nodes of type \c T in a ..Loc hierarchy, for which the inner
1213 /// matcher matches on a another node of type \c T that can be reached using a
1214 /// given traverse function.
1215 template <typename T>
1216 class TypeLocTraverseMatcher : public MatcherInterface<T> {
1218 explicit TypeLocTraverseMatcher(const Matcher<TypeLoc> &InnerMatcher,
1219 TypeLoc (T::*TraverseFunction)() const)
1220 : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {}
1222 virtual bool matches(const T &Node,
1223 ASTMatchFinder *Finder,
1224 BoundNodesTreeBuilder *Builder) const {
1225 TypeLoc NextNode = (Node.*TraverseFunction)();
1228 return InnerMatcher.matches(NextNode, Finder, Builder);
1232 const Matcher<TypeLoc> InnerMatcher;
1233 TypeLoc (T::*TraverseFunction)() const;
1236 template <typename T, typename InnerT>
1237 T makeTypeAllOfComposite(ArrayRef<const Matcher<InnerT> *> InnerMatchers) {
1238 return T(makeAllOfComposite<InnerT>(InnerMatchers));
1241 } // end namespace internal
1242 } // end namespace ast_matchers
1243 } // end namespace clang
1245 #endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H