ASTMatchersInternal.h revision 3abf77872ca6c520903f9174cf6cd89a50df2714
1//===--- ASTMatchersInternal.h - Structural query framework -----*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// Implements the base layer of the matcher framework. 11// 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 16// retrieved later. 17// 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>. 25// 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. 30// 31// This file contains the base classes needed to construct the actual matchers. 32// 33//===----------------------------------------------------------------------===// 34 35#ifndef LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H 36#define LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H 37 38#include "clang/AST/Decl.h" 39#include "clang/AST/DeclCXX.h" 40#include "clang/AST/ExprCXX.h" 41#include "clang/AST/Stmt.h" 42#include "clang/AST/StmtCXX.h" 43#include "clang/AST/Type.h" 44#include "clang/ASTMatchers/ASTTypeTraits.h" 45#include "llvm/ADT/VariadicFunction.h" 46#include "llvm/Support/type_traits.h" 47#include <map> 48#include <string> 49#include <vector> 50 51namespace clang { 52namespace ast_matchers { 53 54/// FIXME: Move into the llvm support library. 55template <bool> struct CompileAssert {}; 56#define TOOLING_COMPILE_ASSERT(Expr, Msg) \ 57 typedef CompileAssert<(bool(Expr))> Msg[bool(Expr) ? 1 : -1] 58 59class BoundNodes; 60 61namespace internal { 62 63class BoundNodesTreeBuilder; 64/// \brief Internal version of BoundNodes. Holds all the bound nodes. 65class BoundNodesMap { 66public: 67 /// \brief Adds \c Node to the map with key \c ID. 68 /// 69 /// The node's base type should be in NodeBaseType or it will be unaccessible. 70 template <typename T> 71 void addNode(StringRef ID, const T* Node) { 72 NodeMap[ID] = ast_type_traits::DynTypedNode::create(*Node); 73 } 74 void addNode(StringRef ID, ast_type_traits::DynTypedNode Node) { 75 NodeMap[ID] = Node; 76 } 77 78 /// \brief Returns the AST node bound to \c ID. 79 /// 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. 82 template <typename T> 83 const T *getNodeAs(StringRef ID) const { 84 IDToNodeMap::const_iterator It = NodeMap.find(ID); 85 if (It == NodeMap.end()) { 86 return NULL; 87 } 88 return It->second.get<T>(); 89 } 90 91 /// \brief Copies all ID/Node pairs to BoundNodesTreeBuilder \c Builder. 92 void copyTo(BoundNodesTreeBuilder *Builder) const; 93 94 /// \brief Copies all ID/Node pairs to BoundNodesMap \c Other. 95 void copyTo(BoundNodesMap *Other) const; 96 97private: 98 /// \brief A map from IDs to the bound nodes. 99 typedef std::map<std::string, ast_type_traits::DynTypedNode> IDToNodeMap; 100 101 IDToNodeMap NodeMap; 102}; 103 104/// \brief A tree of bound nodes in match results. 105/// 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. 109/// 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. 113class BoundNodesTree { 114public: 115 /// \brief A visitor interface to visit all BoundNodes results for a 116 /// BoundNodesTree. 117 class Visitor { 118 public: 119 virtual ~Visitor() {} 120 121 /// \brief Called multiple times during a single call to VisitMatches(...). 122 /// 123 /// 'BoundNodesView' contains the bound nodes for a single match. 124 virtual void visitMatch(const BoundNodes& BoundNodesView) = 0; 125 }; 126 127 BoundNodesTree(); 128 129 /// \brief Create a BoundNodesTree from pre-filled maps of bindings. 130 BoundNodesTree(const BoundNodesMap& Bindings, 131 const std::vector<BoundNodesTree> RecursiveBindings); 132 133 /// \brief Adds all bound nodes to \c Builder. 134 void copyTo(BoundNodesTreeBuilder* Builder) const; 135 136 /// \brief Visits all matches that this BoundNodesTree represents. 137 /// 138 /// The ownership of 'ResultVisitor' remains at the caller. 139 void visitMatches(Visitor* ResultVisitor); 140 141private: 142 void visitMatchesRecursively( 143 Visitor* ResultVistior, 144 const BoundNodesMap& AggregatedBindings); 145 146 // FIXME: Find out whether we want to use different data structures here - 147 // first benchmarks indicate that it doesn't matter though. 148 149 BoundNodesMap Bindings; 150 151 std::vector<BoundNodesTree> RecursiveBindings; 152}; 153 154/// \brief Creates BoundNodesTree objects. 155/// 156/// The tree builder is used during the matching process to insert the bound 157/// nodes from the Id matcher. 158class BoundNodesTreeBuilder { 159public: 160 BoundNodesTreeBuilder(); 161 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); 166 } 167 void setBinding(const std::string &Id, ast_type_traits::DynTypedNode Node) { 168 Bindings.addNode(Id, Node); 169 } 170 171 /// \brief Adds a branch in the tree. 172 void addMatch(const BoundNodesTree& Bindings); 173 174 /// \brief Returns a BoundNodes object containing all current bindings. 175 BoundNodesTree build() const; 176 177private: 178 BoundNodesTreeBuilder(const BoundNodesTreeBuilder &) LLVM_DELETED_FUNCTION; 179 void operator=(const BoundNodesTreeBuilder &) LLVM_DELETED_FUNCTION; 180 181 BoundNodesMap Bindings; 182 183 std::vector<BoundNodesTree> RecursiveBindings; 184}; 185 186class ASTMatchFinder; 187 188/// \brief Generic interface for matchers on an AST node of type T. 189/// 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. 195template <typename T> 196class MatcherInterface : public RefCountedBaseVPTR { 197public: 198 virtual ~MatcherInterface() {} 199 200 /// \brief Returns true if 'Node' can be matched. 201 /// 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; 207}; 208 209/// \brief Interface for matchers that only evaluate properties on a single 210/// node. 211template <typename T> 212class SingleNodeMatcherInterface : public MatcherInterface<T> { 213public: 214 /// \brief Returns true if the matcher matches the provided node. 215 /// 216 /// A subclass must implement this instead of Matches(). 217 virtual bool matchesNode(const T &Node) const = 0; 218 219private: 220 /// Implements MatcherInterface::Matches. 221 virtual bool matches(const T &Node, 222 ASTMatchFinder * /* Finder */, 223 BoundNodesTreeBuilder * /* Builder */) const { 224 return matchesNode(Node); 225 } 226}; 227 228/// \brief Base class for all matchers that works on a \c DynTypedNode. 229/// 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. 233class DynTypedMatcher { 234public: 235 virtual ~DynTypedMatcher() {} 236 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; 241 242 /// \brief Returns a unique ID for the matcher. 243 virtual uint64_t getID() const = 0; 244}; 245 246/// \brief Wrapper of a MatcherInterface<T> *that allows copying. 247/// 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. 254template <typename T> 255class Matcher : public DynTypedMatcher { 256public: 257 /// \brief Takes ownership of the provided implementation pointer. 258 explicit Matcher(MatcherInterface<T> *Implementation) 259 : Implementation(Implementation) {} 260 261 /// \brief Implicitly converts \c Other to a Matcher<T>. 262 /// 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)) {} 270 271 /// \brief Implicitly converts \c Matcher<Type> to \c Matcher<QualType>. 272 /// 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)) {} 280 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); 286 } 287 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()); 293 } 294 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); 302 } 303 304 /// \brief Allows the conversion of a \c Matcher<Type> to a \c 305 /// Matcher<QualType>. 306 /// 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> { 312 public: 313 TypeToQualType(const Matcher<TypeT> &InnerMatcher) 314 : InnerMatcher(InnerMatcher) {} 315 316 virtual bool matches(const QualType &Node, 317 ASTMatchFinder *Finder, 318 BoundNodesTreeBuilder *Builder) const { 319 if (Node.isNull()) 320 return false; 321 return InnerMatcher.matches(*Node, Finder, Builder); 322 } 323 private: 324 const Matcher<TypeT> InnerMatcher; 325 }; 326 327private: 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> { 332 public: 333 explicit ImplicitCastMatcher(const Matcher<Base> &From) 334 : From(From) {} 335 336 virtual bool matches(const T &Node, 337 ASTMatchFinder *Finder, 338 BoundNodesTreeBuilder *Builder) const { 339 return From.matches(Node, Finder, Builder); 340 } 341 342 private: 343 const Matcher<Base> From; 344 }; 345 346 IntrusiveRefCntPtr< MatcherInterface<T> > Implementation; 347}; // class Matcher 348 349/// \brief A convenient helper for creating a Matcher<T> without specifying 350/// the template type argument. 351template <typename T> 352inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) { 353 return Matcher<T>(Implementation); 354} 355 356/// \brief Metafunction to determine if type T has a member called getDecl. 357template <typename T> struct has_getDecl { 358 struct Default { int getDecl; }; 359 struct Derived : T, Default { }; 360 361 template<typename C, C> struct CheckT; 362 363 // If T::getDecl exists, an ambiguity arises and CheckT will 364 // not be instantiable. This makes f(...) the only available 365 // overload. 366 template<typename C> 367 static char (&f(CheckT<int Default::*, &C::getDecl>*))[1]; 368 template<typename C> static char (&f(...))[2]; 369 370 static bool const value = sizeof(f<Derived>(0)) == 2; 371}; 372 373/// \brief Matches declarations for QualType and CallExpr. 374/// 375/// Type argument DeclMatcherT is required by PolymorphicMatcherWithParam1 but 376/// not actually used. 377template <typename T, typename DeclMatcherT> 378class HasDeclarationMatcher : public MatcherInterface<T> { 379 TOOLING_COMPILE_ASSERT((llvm::is_same< DeclMatcherT, 380 Matcher<Decl> >::value), 381 instantiated_with_wrong_types); 382public: 383 explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher) 384 : InnerMatcher(InnerMatcher) {} 385 386 virtual bool matches(const T &Node, 387 ASTMatchFinder *Finder, 388 BoundNodesTreeBuilder *Builder) const { 389 return matchesSpecialized(Node, Finder, Builder); 390 } 391 392private: 393 /// \brief If getDecl exists as a member of U, returns whether the inner 394 /// matcher matches Node.getDecl(). 395 template <typename U> 396 bool matchesSpecialized( 397 const U &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder, 398 typename llvm::enable_if<has_getDecl<U>, int>::type = 0) const { 399 return matchesDecl(Node.getDecl(), Finder, Builder); 400 } 401 402 /// \brief Extracts the CXXRecordDecl or EnumDecl of a QualType and returns 403 /// whether the inner matcher matches on it. 404 bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder, 405 BoundNodesTreeBuilder *Builder) const { 406 /// FIXME: Add other ways to convert... 407 if (Node.isNull()) 408 return false; 409 if (const EnumType *AsEnum = dyn_cast<EnumType>(Node.getTypePtr())) 410 return matchesDecl(AsEnum->getDecl(), Finder, Builder); 411 return matchesDecl(Node->getAsCXXRecordDecl(), Finder, Builder); 412 } 413 414 /// \brief Gets the TemplateDecl from a TemplateSpecializationType 415 /// and returns whether the inner matches on it. 416 bool matchesSpecialized(const TemplateSpecializationType &Node, 417 ASTMatchFinder *Finder, 418 BoundNodesTreeBuilder *Builder) const { 419 return matchesDecl(Node.getTemplateName().getAsTemplateDecl(), 420 Finder, Builder); 421 } 422 423 /// \brief Extracts the Decl of the callee of a CallExpr and returns whether 424 /// the inner matcher matches on it. 425 bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder, 426 BoundNodesTreeBuilder *Builder) const { 427 return matchesDecl(Node.getCalleeDecl(), Finder, Builder); 428 } 429 430 /// \brief Extracts the Decl of the constructor call and returns whether the 431 /// inner matcher matches on it. 432 bool matchesSpecialized(const CXXConstructExpr &Node, 433 ASTMatchFinder *Finder, 434 BoundNodesTreeBuilder *Builder) const { 435 return matchesDecl(Node.getConstructor(), Finder, Builder); 436 } 437 438 /// \brief Extracts the \c ValueDecl a \c MemberExpr refers to and returns 439 /// whether the inner matcher matches on it. 440 bool matchesSpecialized(const MemberExpr &Node, 441 ASTMatchFinder *Finder, 442 BoundNodesTreeBuilder *Builder) const { 443 return matchesDecl(Node.getMemberDecl(), Finder, Builder); 444 } 445 446 /// \brief Returns whether the inner matcher \c Node. Returns false if \c Node 447 /// is \c NULL. 448 bool matchesDecl(const Decl *Node, 449 ASTMatchFinder *Finder, 450 BoundNodesTreeBuilder *Builder) const { 451 return Node != NULL && InnerMatcher.matches(*Node, Finder, Builder); 452 } 453 454 const Matcher<Decl> InnerMatcher; 455}; 456 457/// \brief IsBaseType<T>::value is true if T is a "base" type in the AST 458/// node class hierarchies. 459template <typename T> 460struct IsBaseType { 461 static const bool value = 462 (llvm::is_same<T, Decl>::value || 463 llvm::is_same<T, Stmt>::value || 464 llvm::is_same<T, QualType>::value || 465 llvm::is_same<T, Type>::value || 466 llvm::is_same<T, TypeLoc>::value || 467 llvm::is_same<T, NestedNameSpecifier>::value || 468 llvm::is_same<T, NestedNameSpecifierLoc>::value || 469 llvm::is_same<T, CXXCtorInitializer>::value); 470}; 471template <typename T> 472const bool IsBaseType<T>::value; 473 474/// \brief Interface that allows matchers to traverse the AST. 475/// FIXME: Find a better name. 476/// 477/// This provides three entry methods for each base node type in the AST: 478/// - \c matchesChildOf: 479/// Matches a matcher on every child node of the given node. Returns true 480/// if at least one child node could be matched. 481/// - \c matchesDescendantOf: 482/// Matches a matcher on all descendant nodes of the given node. Returns true 483/// if at least one descendant matched. 484/// - \c matchesAncestorOf: 485/// Matches a matcher on all ancestors of the given node. Returns true if 486/// at least one ancestor matched. 487/// 488/// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal. 489/// In the future, we wan to implement this for all nodes for which it makes 490/// sense. In the case of matchesAncestorOf, we'll want to implement it for 491/// all nodes, as all nodes have ancestors. 492class ASTMatchFinder { 493public: 494 /// \brief Defines how we descend a level in the AST when we pass 495 /// through expressions. 496 enum TraversalKind { 497 /// Will traverse any child nodes. 498 TK_AsIs, 499 /// Will not traverse implicit casts and parentheses. 500 TK_IgnoreImplicitCastsAndParentheses 501 }; 502 503 /// \brief Defines how bindings are processed on recursive matches. 504 enum BindKind { 505 /// Stop at the first match and only bind the first match. 506 BK_First, 507 /// Create results for all combinations of bindings that match. 508 BK_All 509 }; 510 511 /// \brief Defines which ancestors are considered for a match. 512 enum AncestorMatchMode { 513 /// All ancestors. 514 AMM_All, 515 /// Direct parent only. 516 AMM_ParentOnly 517 }; 518 519 virtual ~ASTMatchFinder() {} 520 521 /// \brief Returns true if the given class is directly or indirectly derived 522 /// from a base type matching \c base. 523 /// 524 /// A class is considered to be also derived from itself. 525 virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration, 526 const Matcher<NamedDecl> &Base, 527 BoundNodesTreeBuilder *Builder) = 0; 528 529 template <typename T> 530 bool matchesChildOf(const T &Node, 531 const DynTypedMatcher &Matcher, 532 BoundNodesTreeBuilder *Builder, 533 TraversalKind Traverse, 534 BindKind Bind) { 535 TOOLING_COMPILE_ASSERT( 536 (llvm::is_base_of<Decl, T>::value || 537 llvm::is_base_of<Stmt, T>::value || 538 llvm::is_base_of<NestedNameSpecifier, T>::value || 539 llvm::is_base_of<NestedNameSpecifierLoc, T>::value || 540 llvm::is_base_of<TypeLoc, T>::value || 541 llvm::is_base_of<QualType, T>::value), 542 unsupported_type_for_recursive_matching); 543 return matchesChildOf(ast_type_traits::DynTypedNode::create(Node), 544 Matcher, Builder, Traverse, Bind); 545 } 546 547 template <typename T> 548 bool matchesDescendantOf(const T &Node, 549 const DynTypedMatcher &Matcher, 550 BoundNodesTreeBuilder *Builder, 551 BindKind Bind) { 552 TOOLING_COMPILE_ASSERT( 553 (llvm::is_base_of<Decl, T>::value || 554 llvm::is_base_of<Stmt, T>::value || 555 llvm::is_base_of<NestedNameSpecifier, T>::value || 556 llvm::is_base_of<NestedNameSpecifierLoc, T>::value || 557 llvm::is_base_of<TypeLoc, T>::value || 558 llvm::is_base_of<QualType, T>::value), 559 unsupported_type_for_recursive_matching); 560 return matchesDescendantOf(ast_type_traits::DynTypedNode::create(Node), 561 Matcher, Builder, Bind); 562 } 563 564 // FIXME: Implement support for BindKind. 565 template <typename T> 566 bool matchesAncestorOf(const T &Node, 567 const DynTypedMatcher &Matcher, 568 BoundNodesTreeBuilder *Builder, 569 AncestorMatchMode MatchMode) { 570 TOOLING_COMPILE_ASSERT((llvm::is_base_of<Decl, T>::value || 571 llvm::is_base_of<Stmt, T>::value), 572 only_Decl_or_Stmt_allowed_for_recursive_matching); 573 return matchesAncestorOf(ast_type_traits::DynTypedNode::create(Node), 574 Matcher, Builder, MatchMode); 575 } 576 577 virtual ASTContext &getASTContext() const = 0; 578 579protected: 580 virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node, 581 const DynTypedMatcher &Matcher, 582 BoundNodesTreeBuilder *Builder, 583 TraversalKind Traverse, 584 BindKind Bind) = 0; 585 586 virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node, 587 const DynTypedMatcher &Matcher, 588 BoundNodesTreeBuilder *Builder, 589 BindKind Bind) = 0; 590 591 virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node, 592 const DynTypedMatcher &Matcher, 593 BoundNodesTreeBuilder *Builder, 594 AncestorMatchMode MatchMode) = 0; 595}; 596 597/// \brief Converts a \c Matcher<T> to a matcher of desired type \c To by 598/// "adapting" a \c To into a \c T. 599/// 600/// The \c ArgumentAdapterT argument specifies how the adaptation is done. 601/// 602/// For example: 603/// \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher); 604/// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher 605/// that is convertible into any matcher of type \c To by constructing 606/// \c HasMatcher<To, T>(InnerMatcher). 607/// 608/// If a matcher does not need knowledge about the inner type, prefer to use 609/// PolymorphicMatcherWithParam1. 610template <template <typename ToArg, typename FromArg> class ArgumentAdapterT, 611 typename T> 612class ArgumentAdaptingMatcher { 613public: 614 explicit ArgumentAdaptingMatcher(const Matcher<T> &InnerMatcher) 615 : InnerMatcher(InnerMatcher) {} 616 617 template <typename To> 618 operator Matcher<To>() const { 619 return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher)); 620 } 621 622private: 623 const Matcher<T> InnerMatcher; 624}; 625 626/// \brief A PolymorphicMatcherWithParamN<MatcherT, P1, ..., PN> object can be 627/// created from N parameters p1, ..., pN (of type P1, ..., PN) and 628/// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN) 629/// can be constructed. 630/// 631/// For example: 632/// - PolymorphicMatcherWithParam0<IsDefinitionMatcher>() 633/// creates an object that can be used as a Matcher<T> for any type T 634/// where an IsDefinitionMatcher<T>() can be constructed. 635/// - PolymorphicMatcherWithParam1<ValueEqualsMatcher, int>(42) 636/// creates an object that can be used as a Matcher<T> for any type T 637/// where a ValueEqualsMatcher<T, int>(42) can be constructed. 638template <template <typename T> class MatcherT> 639class PolymorphicMatcherWithParam0 { 640public: 641 template <typename T> 642 operator Matcher<T>() const { 643 return Matcher<T>(new MatcherT<T>()); 644 } 645}; 646 647template <template <typename T, typename P1> class MatcherT, 648 typename P1> 649class PolymorphicMatcherWithParam1 { 650public: 651 explicit PolymorphicMatcherWithParam1(const P1 &Param1) 652 : Param1(Param1) {} 653 654 template <typename T> 655 operator Matcher<T>() const { 656 return Matcher<T>(new MatcherT<T, P1>(Param1)); 657 } 658 659private: 660 const P1 Param1; 661}; 662 663template <template <typename T, typename P1, typename P2> class MatcherT, 664 typename P1, typename P2> 665class PolymorphicMatcherWithParam2 { 666public: 667 PolymorphicMatcherWithParam2(const P1 &Param1, const P2 &Param2) 668 : Param1(Param1), Param2(Param2) {} 669 670 template <typename T> 671 operator Matcher<T>() const { 672 return Matcher<T>(new MatcherT<T, P1, P2>(Param1, Param2)); 673 } 674 675private: 676 const P1 Param1; 677 const P2 Param2; 678}; 679 680/// \brief Matches any instance of the given NodeType. 681/// 682/// This is useful when a matcher syntactically requires a child matcher, 683/// but the context doesn't care. See for example: anything(). 684/// 685/// FIXME: Alternatively we could also create a IsAMatcher or something 686/// that checks that a dyn_cast is possible. This is purely needed for the 687/// difference between calling for example: 688/// record() 689/// and 690/// record(SomeMatcher) 691/// In the second case we need the correct type we were dyn_cast'ed to in order 692/// to get the right type for the inner matcher. In the first case we don't need 693/// that, but we use the type conversion anyway and insert a TrueMatcher. 694template <typename T> 695class TrueMatcher : public SingleNodeMatcherInterface<T> { 696public: 697 virtual bool matchesNode(const T &Node) const { 698 return true; 699 } 700}; 701 702/// \brief Provides a MatcherInterface<T> for a Matcher<To> that matches if T is 703/// dyn_cast'able into To and the given Matcher<To> matches on the dyn_cast'ed 704/// node. 705template <typename T, typename To> 706class DynCastMatcher : public MatcherInterface<T> { 707public: 708 explicit DynCastMatcher(const Matcher<To> &InnerMatcher) 709 : InnerMatcher(InnerMatcher) {} 710 711 virtual bool matches(const T &Node, 712 ASTMatchFinder *Finder, 713 BoundNodesTreeBuilder *Builder) const { 714 const To *InnerMatchValue = dyn_cast<To>(&Node); 715 return InnerMatchValue != NULL && 716 InnerMatcher.matches(*InnerMatchValue, Finder, Builder); 717 } 718 719private: 720 const Matcher<To> InnerMatcher; 721}; 722 723/// \brief Matcher<T> that wraps an inner Matcher<T> and binds the matched node 724/// to an ID if the inner matcher matches on the node. 725template <typename T> 726class IdMatcher : public MatcherInterface<T> { 727public: 728 /// \brief Creates an IdMatcher that binds to 'ID' if 'InnerMatcher' matches 729 /// the node. 730 IdMatcher(StringRef ID, const Matcher<T> &InnerMatcher) 731 : ID(ID), InnerMatcher(InnerMatcher) {} 732 733 virtual bool matches(const T &Node, 734 ASTMatchFinder *Finder, 735 BoundNodesTreeBuilder *Builder) const { 736 bool Result = InnerMatcher.matches(Node, Finder, Builder); 737 if (Result) { 738 Builder->setBinding(ID, &Node); 739 } 740 return Result; 741 } 742 743private: 744 const std::string ID; 745 const Matcher<T> InnerMatcher; 746}; 747 748/// \brief A Matcher that allows binding the node it matches to an id. 749/// 750/// BindableMatcher provides a \a bind() method that allows binding the 751/// matched node to an id if the match was successful. 752template <typename T> 753class BindableMatcher : public Matcher<T> { 754public: 755 BindableMatcher(MatcherInterface<T> *Implementation) 756 : Matcher<T>(Implementation) {} 757 758 /// \brief Returns a matcher that will bind the matched node on a match. 759 /// 760 /// The returned matcher is equivalent to this matcher, but will 761 /// bind the matched node on a match. 762 Matcher<T> bind(StringRef ID) const { 763 return Matcher<T>(new IdMatcher<T>(ID, *this)); 764 } 765}; 766 767/// \brief Matches nodes of type T that have child nodes of type ChildT for 768/// which a specified child matcher matches. 769/// 770/// ChildT must be an AST base type. 771template <typename T, typename ChildT> 772class HasMatcher : public MatcherInterface<T> { 773 TOOLING_COMPILE_ASSERT(IsBaseType<ChildT>::value, 774 has_only_accepts_base_type_matcher); 775public: 776 explicit HasMatcher(const Matcher<ChildT> &ChildMatcher) 777 : ChildMatcher(ChildMatcher) {} 778 779 virtual bool matches(const T &Node, 780 ASTMatchFinder *Finder, 781 BoundNodesTreeBuilder *Builder) const { 782 return Finder->matchesChildOf( 783 Node, ChildMatcher, Builder, 784 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses, 785 ASTMatchFinder::BK_First); 786 } 787 788 private: 789 const Matcher<ChildT> ChildMatcher; 790}; 791 792/// \brief Matches nodes of type T that have child nodes of type ChildT for 793/// which a specified child matcher matches. ChildT must be an AST base 794/// type. 795/// As opposed to the HasMatcher, the ForEachMatcher will produce a match 796/// for each child that matches. 797template <typename T, typename ChildT> 798class ForEachMatcher : public MatcherInterface<T> { 799 TOOLING_COMPILE_ASSERT(IsBaseType<ChildT>::value, 800 for_each_only_accepts_base_type_matcher); 801 public: 802 explicit ForEachMatcher(const Matcher<ChildT> &ChildMatcher) 803 : ChildMatcher(ChildMatcher) {} 804 805 virtual bool matches(const T& Node, 806 ASTMatchFinder* Finder, 807 BoundNodesTreeBuilder* Builder) const { 808 return Finder->matchesChildOf( 809 Node, ChildMatcher, Builder, 810 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses, 811 ASTMatchFinder::BK_All); 812 } 813 814private: 815 const Matcher<ChildT> ChildMatcher; 816}; 817 818/// \brief Matches nodes of type T if the given Matcher<T> does not match. 819/// 820/// Type argument MatcherT is required by PolymorphicMatcherWithParam1 821/// but not actually used. It will always be instantiated with a type 822/// convertible to Matcher<T>. 823template <typename T, typename MatcherT> 824class NotMatcher : public MatcherInterface<T> { 825public: 826 explicit NotMatcher(const Matcher<T> &InnerMatcher) 827 : InnerMatcher(InnerMatcher) {} 828 829 virtual bool matches(const T &Node, 830 ASTMatchFinder *Finder, 831 BoundNodesTreeBuilder *Builder) const { 832 return !InnerMatcher.matches(Node, Finder, Builder); 833 } 834 835private: 836 const Matcher<T> InnerMatcher; 837}; 838 839/// \brief Matches nodes of type T for which both provided matchers match. 840/// 841/// Type arguments MatcherT1 and MatcherT2 are required by 842/// PolymorphicMatcherWithParam2 but not actually used. They will 843/// always be instantiated with types convertible to Matcher<T>. 844template <typename T, typename MatcherT1, typename MatcherT2> 845class AllOfMatcher : public MatcherInterface<T> { 846public: 847 AllOfMatcher(const Matcher<T> &InnerMatcher1, const Matcher<T> &InnerMatcher2) 848 : InnerMatcher1(InnerMatcher1), InnerMatcher2(InnerMatcher2) {} 849 850 virtual bool matches(const T &Node, 851 ASTMatchFinder *Finder, 852 BoundNodesTreeBuilder *Builder) const { 853 return InnerMatcher1.matches(Node, Finder, Builder) && 854 InnerMatcher2.matches(Node, Finder, Builder); 855 } 856 857private: 858 const Matcher<T> InnerMatcher1; 859 const Matcher<T> InnerMatcher2; 860}; 861 862/// \brief Matches nodes of type T for which at least one of the two provided 863/// matchers matches. 864/// 865/// Type arguments MatcherT1 and MatcherT2 are 866/// required by PolymorphicMatcherWithParam2 but not actually 867/// used. They will always be instantiated with types convertible to 868/// Matcher<T>. 869template <typename T, typename MatcherT1, typename MatcherT2> 870class EachOfMatcher : public MatcherInterface<T> { 871public: 872 EachOfMatcher(const Matcher<T> &InnerMatcher1, 873 const Matcher<T> &InnerMatcher2) 874 : InnerMatcher1(InnerMatcher1), InnerMatcher2(InnerMatcher2) { 875 } 876 877 virtual bool matches(const T &Node, ASTMatchFinder *Finder, 878 BoundNodesTreeBuilder *Builder) const { 879 BoundNodesTreeBuilder Builder1; 880 bool Matched1 = InnerMatcher1.matches(Node, Finder, &Builder1); 881 if (Matched1) 882 Builder->addMatch(Builder1.build()); 883 884 BoundNodesTreeBuilder Builder2; 885 bool Matched2 = InnerMatcher2.matches(Node, Finder, &Builder2); 886 if (Matched2) 887 Builder->addMatch(Builder2.build()); 888 889 return Matched1 || Matched2; 890 } 891 892private: 893 const Matcher<T> InnerMatcher1; 894 const Matcher<T> InnerMatcher2; 895}; 896 897/// \brief Matches nodes of type T for which at least one of the two provided 898/// matchers matches. 899/// 900/// Type arguments MatcherT1 and MatcherT2 are 901/// required by PolymorphicMatcherWithParam2 but not actually 902/// used. They will always be instantiated with types convertible to 903/// Matcher<T>. 904template <typename T, typename MatcherT1, typename MatcherT2> 905class AnyOfMatcher : public MatcherInterface<T> { 906public: 907 AnyOfMatcher(const Matcher<T> &InnerMatcher1, const Matcher<T> &InnerMatcher2) 908 : InnerMatcher1(InnerMatcher1), InnerMatcher2(InnerMatcher2) {} 909 910 virtual bool matches(const T &Node, 911 ASTMatchFinder *Finder, 912 BoundNodesTreeBuilder *Builder) const { 913 return InnerMatcher1.matches(Node, Finder, Builder) || 914 InnerMatcher2.matches(Node, Finder, Builder); 915 } 916 917private: 918 const Matcher<T> InnerMatcher1; 919 const Matcher<T> InnerMatcher2; 920}; 921 922/// \brief Creates a Matcher<T> that matches if all inner matchers match. 923template<typename T> 924BindableMatcher<T> makeAllOfComposite( 925 ArrayRef<const Matcher<T> *> InnerMatchers) { 926 if (InnerMatchers.empty()) 927 return BindableMatcher<T>(new TrueMatcher<T>); 928 MatcherInterface<T> *InnerMatcher = new TrueMatcher<T>; 929 for (int i = InnerMatchers.size() - 1; i >= 0; --i) { 930 InnerMatcher = new AllOfMatcher<T, Matcher<T>, Matcher<T> >( 931 *InnerMatchers[i], makeMatcher(InnerMatcher)); 932 } 933 return BindableMatcher<T>(InnerMatcher); 934} 935 936/// \brief Creates a Matcher<T> that matches if 937/// T is dyn_cast'able into InnerT and all inner matchers match. 938/// 939/// Returns BindableMatcher, as matchers that use dyn_cast have 940/// the same object both to match on and to run submatchers on, 941/// so there is no ambiguity with what gets bound. 942template<typename T, typename InnerT> 943BindableMatcher<T> makeDynCastAllOfComposite( 944 ArrayRef<const Matcher<InnerT> *> InnerMatchers) { 945 return BindableMatcher<T>(new DynCastMatcher<T, InnerT>( 946 makeAllOfComposite(InnerMatchers))); 947} 948 949/// \brief Matches nodes of type T that have at least one descendant node of 950/// type DescendantT for which the given inner matcher matches. 951/// 952/// DescendantT must be an AST base type. 953template <typename T, typename DescendantT> 954class HasDescendantMatcher : public MatcherInterface<T> { 955 TOOLING_COMPILE_ASSERT(IsBaseType<DescendantT>::value, 956 has_descendant_only_accepts_base_type_matcher); 957public: 958 explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher) 959 : DescendantMatcher(DescendantMatcher) {} 960 961 virtual bool matches(const T &Node, 962 ASTMatchFinder *Finder, 963 BoundNodesTreeBuilder *Builder) const { 964 return Finder->matchesDescendantOf( 965 Node, DescendantMatcher, Builder, ASTMatchFinder::BK_First); 966 } 967 968 private: 969 const Matcher<DescendantT> DescendantMatcher; 970}; 971 972/// \brief Matches nodes of type \c T that have a parent node of type \c ParentT 973/// for which the given inner matcher matches. 974/// 975/// \c ParentT must be an AST base type. 976template <typename T, typename ParentT> 977class HasParentMatcher : public MatcherInterface<T> { 978 TOOLING_COMPILE_ASSERT(IsBaseType<ParentT>::value, 979 has_parent_only_accepts_base_type_matcher); 980public: 981 explicit HasParentMatcher(const Matcher<ParentT> &ParentMatcher) 982 : ParentMatcher(ParentMatcher) {} 983 984 virtual bool matches(const T &Node, 985 ASTMatchFinder *Finder, 986 BoundNodesTreeBuilder *Builder) const { 987 return Finder->matchesAncestorOf( 988 Node, ParentMatcher, Builder, ASTMatchFinder::AMM_ParentOnly); 989 } 990 991 private: 992 const Matcher<ParentT> ParentMatcher; 993}; 994 995/// \brief Matches nodes of type \c T that have at least one ancestor node of 996/// type \c AncestorT for which the given inner matcher matches. 997/// 998/// \c AncestorT must be an AST base type. 999template <typename T, typename AncestorT> 1000class HasAncestorMatcher : public MatcherInterface<T> { 1001 TOOLING_COMPILE_ASSERT(IsBaseType<AncestorT>::value, 1002 has_ancestor_only_accepts_base_type_matcher); 1003public: 1004 explicit HasAncestorMatcher(const Matcher<AncestorT> &AncestorMatcher) 1005 : AncestorMatcher(AncestorMatcher) {} 1006 1007 virtual bool matches(const T &Node, 1008 ASTMatchFinder *Finder, 1009 BoundNodesTreeBuilder *Builder) const { 1010 return Finder->matchesAncestorOf( 1011 Node, AncestorMatcher, Builder, ASTMatchFinder::AMM_All); 1012 } 1013 1014 private: 1015 const Matcher<AncestorT> AncestorMatcher; 1016}; 1017 1018/// \brief Matches nodes of type T that have at least one descendant node of 1019/// type DescendantT for which the given inner matcher matches. 1020/// 1021/// DescendantT must be an AST base type. 1022/// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match 1023/// for each descendant node that matches instead of only for the first. 1024template <typename T, typename DescendantT> 1025class ForEachDescendantMatcher : public MatcherInterface<T> { 1026 TOOLING_COMPILE_ASSERT(IsBaseType<DescendantT>::value, 1027 for_each_descendant_only_accepts_base_type_matcher); 1028 public: 1029 explicit ForEachDescendantMatcher( 1030 const Matcher<DescendantT>& DescendantMatcher) 1031 : DescendantMatcher(DescendantMatcher) {} 1032 1033 virtual bool matches(const T& Node, 1034 ASTMatchFinder* Finder, 1035 BoundNodesTreeBuilder* Builder) const { 1036 return Finder->matchesDescendantOf(Node, DescendantMatcher, Builder, 1037 ASTMatchFinder::BK_All); 1038 } 1039 1040private: 1041 const Matcher<DescendantT> DescendantMatcher; 1042}; 1043 1044/// \brief Matches on nodes that have a getValue() method if getValue() equals 1045/// the value the ValueEqualsMatcher was constructed with. 1046template <typename T, typename ValueT> 1047class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> { 1048 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CharacterLiteral, T>::value || 1049 llvm::is_base_of<CXXBoolLiteralExpr, 1050 T>::value || 1051 llvm::is_base_of<FloatingLiteral, T>::value || 1052 llvm::is_base_of<IntegerLiteral, T>::value), 1053 the_node_must_have_a_getValue_method); 1054public: 1055 explicit ValueEqualsMatcher(const ValueT &ExpectedValue) 1056 : ExpectedValue(ExpectedValue) {} 1057 1058 virtual bool matchesNode(const T &Node) const { 1059 return Node.getValue() == ExpectedValue; 1060 } 1061 1062private: 1063 const ValueT ExpectedValue; 1064}; 1065 1066/// \brief A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a 1067/// variadic functor that takes a number of Matcher<TargetT> and returns a 1068/// Matcher<SourceT> that matches TargetT nodes that are matched by all of the 1069/// given matchers, if SourceT can be dynamically casted into TargetT. 1070/// 1071/// For example: 1072/// const VariadicDynCastAllOfMatcher< 1073/// Decl, CXXRecordDecl> record; 1074/// Creates a functor record(...) that creates a Matcher<Decl> given 1075/// a variable number of arguments of type Matcher<CXXRecordDecl>. 1076/// The returned matcher matches if the given Decl can by dynamically 1077/// casted to CXXRecordDecl and all given matchers match. 1078template <typename SourceT, typename TargetT> 1079class VariadicDynCastAllOfMatcher 1080 : public llvm::VariadicFunction< 1081 BindableMatcher<SourceT>, Matcher<TargetT>, 1082 makeDynCastAllOfComposite<SourceT, TargetT> > { 1083public: 1084 VariadicDynCastAllOfMatcher() {} 1085}; 1086 1087/// \brief A \c VariadicAllOfMatcher<T> object is a variadic functor that takes 1088/// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T 1089/// nodes that are matched by all of the given matchers. 1090/// 1091/// For example: 1092/// const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier; 1093/// Creates a functor nestedNameSpecifier(...) that creates a 1094/// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type 1095/// \c Matcher<NestedNameSpecifier>. 1096/// The returned matcher matches if all given matchers match. 1097template <typename T> 1098class VariadicAllOfMatcher : public llvm::VariadicFunction< 1099 BindableMatcher<T>, Matcher<T>, 1100 makeAllOfComposite<T> > { 1101public: 1102 VariadicAllOfMatcher() {} 1103}; 1104 1105/// \brief Matches nodes of type \c TLoc for which the inner 1106/// \c Matcher<T> matches. 1107template <typename TLoc, typename T> 1108class LocMatcher : public MatcherInterface<TLoc> { 1109public: 1110 explicit LocMatcher(const Matcher<T> &InnerMatcher) 1111 : InnerMatcher(InnerMatcher) {} 1112 1113 virtual bool matches(const TLoc &Node, 1114 ASTMatchFinder *Finder, 1115 BoundNodesTreeBuilder *Builder) const { 1116 if (!Node) 1117 return false; 1118 return InnerMatcher.matches(*extract(Node), Finder, Builder); 1119 } 1120 1121private: 1122 const NestedNameSpecifier *extract(const NestedNameSpecifierLoc &Loc) const { 1123 return Loc.getNestedNameSpecifier(); 1124 } 1125 1126 const Matcher<T> InnerMatcher; 1127}; 1128 1129/// \brief Matches \c TypeLocs based on an inner matcher matching a certain 1130/// \c QualType. 1131/// 1132/// Used to implement the \c loc() matcher. 1133class TypeLocTypeMatcher : public MatcherInterface<TypeLoc> { 1134public: 1135 explicit TypeLocTypeMatcher(const Matcher<QualType> &InnerMatcher) 1136 : InnerMatcher(InnerMatcher) {} 1137 1138 virtual bool matches(const TypeLoc &Node, 1139 ASTMatchFinder *Finder, 1140 BoundNodesTreeBuilder *Builder) const { 1141 if (!Node) 1142 return false; 1143 return InnerMatcher.matches(Node.getType(), Finder, Builder); 1144 } 1145 1146private: 1147 const Matcher<QualType> InnerMatcher; 1148}; 1149 1150/// \brief Matches nodes of type \c T for which the inner matcher matches on a 1151/// another node of type \c T that can be reached using a given traverse 1152/// function. 1153template <typename T> 1154class TypeTraverseMatcher : public MatcherInterface<T> { 1155public: 1156 explicit TypeTraverseMatcher(const Matcher<QualType> &InnerMatcher, 1157 QualType (T::*TraverseFunction)() const) 1158 : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {} 1159 1160 virtual bool matches(const T &Node, 1161 ASTMatchFinder *Finder, 1162 BoundNodesTreeBuilder *Builder) const { 1163 QualType NextNode = (Node.*TraverseFunction)(); 1164 if (NextNode.isNull()) 1165 return false; 1166 return InnerMatcher.matches(NextNode, Finder, Builder); 1167 } 1168 1169private: 1170 const Matcher<QualType> InnerMatcher; 1171 QualType (T::*TraverseFunction)() const; 1172}; 1173 1174/// \brief Matches nodes of type \c T in a ..Loc hierarchy, for which the inner 1175/// matcher matches on a another node of type \c T that can be reached using a 1176/// given traverse function. 1177template <typename T> 1178class TypeLocTraverseMatcher : public MatcherInterface<T> { 1179public: 1180 explicit TypeLocTraverseMatcher(const Matcher<TypeLoc> &InnerMatcher, 1181 TypeLoc (T::*TraverseFunction)() const) 1182 : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {} 1183 1184 virtual bool matches(const T &Node, 1185 ASTMatchFinder *Finder, 1186 BoundNodesTreeBuilder *Builder) const { 1187 TypeLoc NextNode = (Node.*TraverseFunction)(); 1188 if (!NextNode) 1189 return false; 1190 return InnerMatcher.matches(NextNode, Finder, Builder); 1191 } 1192 1193private: 1194 const Matcher<TypeLoc> InnerMatcher; 1195 TypeLoc (T::*TraverseFunction)() const; 1196}; 1197 1198template <typename T, typename InnerT> 1199T makeTypeAllOfComposite(ArrayRef<const Matcher<InnerT> *> InnerMatchers) { 1200 return T(makeAllOfComposite<InnerT>(InnerMatchers)); 1201} 1202 1203} // end namespace internal 1204} // end namespace ast_matchers 1205} // end namespace clang 1206 1207#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H 1208