ASTMatchersInternal.h revision a78d0d6203a990b88c9c3e4c4f2a277001e8bd46
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/Type.h" 43#include "clang/ASTMatchers/ASTTypeTraits.h" 44#include "llvm/ADT/VariadicFunction.h" 45#include "llvm/Support/type_traits.h" 46#include <map> 47#include <string> 48#include <vector> 49 50namespace clang { 51namespace ast_matchers { 52 53/// FIXME: Move into the llvm support library. 54template <bool> struct CompileAssert {}; 55#define TOOLING_COMPILE_ASSERT(Expr, Msg) \ 56 typedef CompileAssert<(bool(Expr))> Msg[bool(Expr) ? 1 : -1] 57 58class BoundNodes; 59 60namespace internal { 61 62class BoundNodesTreeBuilder; 63/// \brief Internal version of BoundNodes. Holds all the bound nodes. 64class BoundNodesMap { 65public: 66 /// \brief Adds \c Node to the map with key \c ID. 67 /// 68 /// The node's base type should be in NodeBaseType or it will be unaccessible. 69 template <typename T> 70 void addNode(StringRef ID, const T* Node) { 71 NodeMap[ID] = ast_type_traits::DynTypedNode::create(*Node); 72 } 73 void addNode(StringRef ID, ast_type_traits::DynTypedNode Node) { 74 NodeMap[ID] = Node; 75 } 76 77 /// \brief Returns the AST node bound to \c ID. 78 /// 79 /// Returns NULL if there was no node bound to \c ID or if there is a node but 80 /// it cannot be converted to the specified type. 81 template <typename T> 82 const T *getNodeAs(StringRef ID) const { 83 IDToNodeMap::const_iterator It = NodeMap.find(ID); 84 if (It == NodeMap.end()) { 85 return NULL; 86 } 87 return It->second.get<T>(); 88 } 89 90 /// \brief Copies all ID/Node pairs to BoundNodesTreeBuilder \c Builder. 91 void copyTo(BoundNodesTreeBuilder *Builder) const; 92 93 /// \brief Copies all ID/Node pairs to BoundNodesMap \c Other. 94 void copyTo(BoundNodesMap *Other) const; 95 96private: 97 /// \brief A map from IDs to the bound nodes. 98 typedef std::map<std::string, ast_type_traits::DynTypedNode> IDToNodeMap; 99 100 IDToNodeMap NodeMap; 101}; 102 103/// \brief A tree of bound nodes in match results. 104/// 105/// If a match can contain multiple matches on the same node with different 106/// matching subexpressions, BoundNodesTree contains a branch for each of 107/// those matching subexpressions. 108/// 109/// BoundNodesTree's are created during the matching process; when a match 110/// is found, we iterate over the tree and create a BoundNodes object containing 111/// the union of all bound nodes on the path from the root to a each leaf. 112class BoundNodesTree { 113public: 114 /// \brief A visitor interface to visit all BoundNodes results for a 115 /// BoundNodesTree. 116 class Visitor { 117 public: 118 virtual ~Visitor() {} 119 120 /// \brief Called multiple times during a single call to VisitMatches(...). 121 /// 122 /// 'BoundNodesView' contains the bound nodes for a single match. 123 virtual void visitMatch(const BoundNodes& BoundNodesView) = 0; 124 }; 125 126 BoundNodesTree(); 127 128 /// \brief Create a BoundNodesTree from pre-filled maps of bindings. 129 BoundNodesTree(const BoundNodesMap& Bindings, 130 const std::vector<BoundNodesTree> RecursiveBindings); 131 132 /// \brief Adds all bound nodes to \c Builder. 133 void copyTo(BoundNodesTreeBuilder* Builder) const; 134 135 /// \brief Visits all matches that this BoundNodesTree represents. 136 /// 137 /// The ownership of 'ResultVisitor' remains at the caller. 138 void visitMatches(Visitor* ResultVisitor); 139 140private: 141 void visitMatchesRecursively( 142 Visitor* ResultVistior, 143 BoundNodesMap *AggregatedBindings); 144 145 // FIXME: Find out whether we want to use different data structures here - 146 // first benchmarks indicate that it doesn't matter though. 147 148 BoundNodesMap Bindings; 149 150 std::vector<BoundNodesTree> RecursiveBindings; 151}; 152 153/// \brief Creates BoundNodesTree objects. 154/// 155/// The tree builder is used during the matching process to insert the bound 156/// nodes from the Id matcher. 157class BoundNodesTreeBuilder { 158public: 159 BoundNodesTreeBuilder(); 160 161 /// \brief Add a binding from an id to a node. 162 template <typename T> 163 void setBinding(const std::string &Id, const T *Node) { 164 Bindings.addNode(Id, Node); 165 } 166 void setBinding(const std::string &Id, ast_type_traits::DynTypedNode Node) { 167 Bindings.addNode(Id, Node); 168 } 169 170 /// \brief Adds a branch in the tree. 171 void addMatch(const BoundNodesTree& Bindings); 172 173 /// \brief Returns a BoundNodes object containing all current bindings. 174 BoundNodesTree build() const; 175 176private: 177 BoundNodesTreeBuilder(const BoundNodesTreeBuilder&); // DO NOT IMPLEMENT 178 void operator=(const BoundNodesTreeBuilder&); // DO NOT IMPLEMENT 179 180 BoundNodesMap Bindings; 181 182 std::vector<BoundNodesTree> RecursiveBindings; 183}; 184 185class ASTMatchFinder; 186 187/// \brief Generic interface for matchers on an AST node of type T. 188/// 189/// Implement this if your matcher may need to inspect the children or 190/// descendants of the node or bind matched nodes to names. If you are 191/// writing a simple matcher that only inspects properties of the 192/// current node and doesn't care about its children or descendants, 193/// implement SingleNodeMatcherInterface instead. 194template <typename T> 195class MatcherInterface : public llvm::RefCountedBaseVPTR { 196public: 197 virtual ~MatcherInterface() {} 198 199 /// \brief Returns true if 'Node' can be matched. 200 /// 201 /// May bind 'Node' to an ID via 'Builder', or recurse into 202 /// the AST via 'Finder'. 203 virtual bool matches(const T &Node, 204 ASTMatchFinder *Finder, 205 BoundNodesTreeBuilder *Builder) const = 0; 206}; 207 208/// \brief Interface for matchers that only evaluate properties on a single 209/// node. 210template <typename T> 211class SingleNodeMatcherInterface : public MatcherInterface<T> { 212public: 213 /// \brief Returns true if the matcher matches the provided node. 214 /// 215 /// A subclass must implement this instead of Matches(). 216 virtual bool matchesNode(const T &Node) const = 0; 217 218private: 219 /// Implements MatcherInterface::Matches. 220 virtual bool matches(const T &Node, 221 ASTMatchFinder * /* Finder */, 222 BoundNodesTreeBuilder * /* Builder */) const { 223 return matchesNode(Node); 224 } 225}; 226 227/// \brief Base class for all matchers that works on a \c DynTypedNode. 228/// 229/// Matcher implementations will check whether the \c DynTypedNode is 230/// convertible into the respecitve types and then do the actual match 231/// on the actual node, or return false if it is not convertible. 232class DynTypedMatcher { 233public: 234 virtual ~DynTypedMatcher() {} 235 236 /// \brief Returns true if the matcher matches the given \c DynNode. 237 virtual bool matches(const ast_type_traits::DynTypedNode DynNode, 238 ASTMatchFinder *Finder, 239 BoundNodesTreeBuilder *Builder) const = 0; 240 241 /// \brief Returns a unique ID for the matcher. 242 virtual uint64_t getID() const = 0; 243}; 244 245/// \brief Wrapper of a MatcherInterface<T> *that allows copying. 246/// 247/// A Matcher<Base> can be used anywhere a Matcher<Derived> is 248/// required. This establishes an is-a relationship which is reverse 249/// to the AST hierarchy. In other words, Matcher<T> is contravariant 250/// with respect to T. The relationship is built via a type conversion 251/// operator rather than a type hierarchy to be able to templatize the 252/// type hierarchy instead of spelling it out. 253template <typename T> 254class Matcher : public DynTypedMatcher { 255public: 256 /// \brief Takes ownership of the provided implementation pointer. 257 explicit Matcher(MatcherInterface<T> *Implementation) 258 : Implementation(Implementation) {} 259 260 /// \brief Forwards the call to the underlying MatcherInterface<T> pointer. 261 bool matches(const T &Node, 262 ASTMatchFinder *Finder, 263 BoundNodesTreeBuilder *Builder) const { 264 return Implementation->matches(Node, Finder, Builder); 265 } 266 267 /// \brief Implicitly converts this object to a Matcher<Derived>. 268 /// 269 /// Requires Derived to be derived from T. 270 template <typename Derived> 271 operator Matcher<Derived>() const { 272 return Matcher<Derived>(new ImplicitCastMatcher<Derived>(*this)); 273 } 274 275 /// \brief Returns an ID that uniquely identifies the matcher. 276 uint64_t getID() const { 277 /// FIXME: Document the requirements this imposes on matcher 278 /// implementations (no new() implementation_ during a Matches()). 279 return reinterpret_cast<uint64_t>(Implementation.getPtr()); 280 } 281 282 /// \brief Returns whether the matcher matches on the given \c DynNode. 283 virtual bool matches(const ast_type_traits::DynTypedNode DynNode, 284 ASTMatchFinder *Finder, 285 BoundNodesTreeBuilder *Builder) const { 286 const T *Node = DynNode.get<T>(); 287 if (!Node) return false; 288 return matches(*Node, Finder, Builder); 289 } 290 291private: 292 /// \brief Allows conversion from Matcher<T> to Matcher<Derived> if Derived 293 /// is derived from T. 294 template <typename Derived> 295 class ImplicitCastMatcher : public MatcherInterface<Derived> { 296 public: 297 explicit ImplicitCastMatcher(const Matcher<T> &From) 298 : From(From) {} 299 300 virtual bool matches(const Derived &Node, 301 ASTMatchFinder *Finder, 302 BoundNodesTreeBuilder *Builder) const { 303 return From.matches(Node, Finder, Builder); 304 } 305 306 private: 307 const Matcher<T> From; 308 }; 309 310 llvm::IntrusiveRefCntPtr< MatcherInterface<T> > Implementation; 311}; // class Matcher 312 313/// \brief A convenient helper for creating a Matcher<T> without specifying 314/// the template type argument. 315template <typename T> 316inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) { 317 return Matcher<T>(Implementation); 318} 319 320/// \brief Matches declarations for QualType and CallExpr. 321/// 322/// Type argument DeclMatcherT is required by PolymorphicMatcherWithParam1 but 323/// not actually used. 324template <typename T, typename DeclMatcherT> 325class HasDeclarationMatcher : public MatcherInterface<T> { 326 TOOLING_COMPILE_ASSERT((llvm::is_same< DeclMatcherT, 327 Matcher<Decl> >::value), 328 instantiated_with_wrong_types); 329public: 330 explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher) 331 : InnerMatcher(InnerMatcher) {} 332 333 virtual bool matches(const T &Node, 334 ASTMatchFinder *Finder, 335 BoundNodesTreeBuilder *Builder) const { 336 return matchesSpecialized(Node, Finder, Builder); 337 } 338 339private: 340 /// \brief Extracts the CXXRecordDecl of a QualType and returns whether the 341 /// inner matcher matches on it. 342 bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder, 343 BoundNodesTreeBuilder *Builder) const { 344 /// FIXME: Add other ways to convert... 345 if (Node.isNull()) 346 return false; 347 CXXRecordDecl *NodeAsRecordDecl = Node->getAsCXXRecordDecl(); 348 return NodeAsRecordDecl != NULL && 349 InnerMatcher.matches(*NodeAsRecordDecl, Finder, Builder); 350 } 351 352 /// \brief Extracts the Decl of the callee of a CallExpr and returns whether 353 /// the inner matcher matches on it. 354 bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder, 355 BoundNodesTreeBuilder *Builder) const { 356 const Decl *NodeAsDecl = Node.getCalleeDecl(); 357 return NodeAsDecl != NULL && 358 InnerMatcher.matches(*NodeAsDecl, Finder, Builder); 359 } 360 361 /// \brief Extracts the Decl of the constructor call and returns whether the 362 /// inner matcher matches on it. 363 bool matchesSpecialized(const CXXConstructExpr &Node, 364 ASTMatchFinder *Finder, 365 BoundNodesTreeBuilder *Builder) const { 366 const Decl *NodeAsDecl = Node.getConstructor(); 367 return NodeAsDecl != NULL && 368 InnerMatcher.matches(*NodeAsDecl, Finder, Builder); 369 } 370 371 const Matcher<Decl> InnerMatcher; 372}; 373 374/// \brief IsBaseType<T>::value is true if T is a "base" type in the AST 375/// node class hierarchies (i.e. if T is Decl, Stmt, QualType, or 376/// CXXCtorInitializer). 377template <typename T> 378struct IsBaseType { 379 static const bool value = 380 (llvm::is_same<T, Decl>::value || 381 llvm::is_same<T, Stmt>::value || 382 llvm::is_same<T, QualType>::value || 383 llvm::is_same<T, CXXCtorInitializer>::value); 384}; 385template <typename T> 386const bool IsBaseType<T>::value; 387 388/// \brief Interface that allows matchers to traverse the AST. 389/// FIXME: Find a better name. 390/// 391/// This provides two entry methods for each base node type in the AST: 392/// - matchesChildOf: 393/// Matches a matcher on every child node of the given node. Returns true 394/// if at least one child node could be matched. 395/// - matchesDescendantOf: 396/// Matches a matcher on all descendant nodes of the given node. Returns true 397/// if at least one descendant matched. 398class ASTMatchFinder { 399public: 400 /// \brief Defines how we descend a level in the AST when we pass 401 /// through expressions. 402 enum TraversalKind { 403 /// Will traverse any child nodes. 404 TK_AsIs, 405 /// Will not traverse implicit casts and parentheses. 406 TK_IgnoreImplicitCastsAndParentheses 407 }; 408 409 /// \brief Defines how bindings are processed on recursive matches. 410 enum BindKind { 411 /// Stop at the first match and only bind the first match. 412 BK_First, 413 /// Create results for all combinations of bindings that match. 414 BK_All 415 }; 416 417 virtual ~ASTMatchFinder() {} 418 419 /// \brief Returns true if the given class is directly or indirectly derived 420 /// from a base type matching \c base. 421 /// 422 /// A class is considered to be also derived from itself. 423 virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration, 424 const Matcher<NamedDecl> &Base, 425 BoundNodesTreeBuilder *Builder) = 0; 426 427 template <typename T> 428 bool matchesChildOf(const T &Node, 429 const DynTypedMatcher &Matcher, 430 BoundNodesTreeBuilder *Builder, 431 TraversalKind Traverse, 432 BindKind Bind) { 433 TOOLING_COMPILE_ASSERT((llvm::is_base_of<Decl, T>::value || 434 llvm::is_base_of<Stmt, T>::value), 435 only_Decl_or_Stmt_allowed_for_recursive_matching); 436 return matchesChildOf(ast_type_traits::DynTypedNode::create(Node), 437 Matcher, Builder, Traverse, Bind); 438 } 439 440 template <typename T> 441 bool matchesDescendantOf(const T &Node, 442 const DynTypedMatcher &Matcher, 443 BoundNodesTreeBuilder *Builder, 444 BindKind Bind) { 445 TOOLING_COMPILE_ASSERT((llvm::is_base_of<Decl, T>::value || 446 llvm::is_base_of<Stmt, T>::value), 447 only_Decl_or_Stmt_allowed_for_recursive_matching); 448 return matchesDescendantOf(ast_type_traits::DynTypedNode::create(Node), 449 Matcher, Builder, Bind); 450 } 451 452protected: 453 // FIXME: Implement for other base nodes. 454 virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node, 455 const DynTypedMatcher &Matcher, 456 BoundNodesTreeBuilder *Builder, 457 TraversalKind Traverse, 458 BindKind Bind) = 0; 459 460 virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node, 461 const DynTypedMatcher &Matcher, 462 BoundNodesTreeBuilder *Builder, 463 BindKind Bind) = 0; 464}; 465 466/// \brief Converts a \c Matcher<T> to a matcher of desired type \c To by 467/// "adapting" a \c To into a \c T. 468/// 469/// The \c ArgumentAdapterT argument specifies how the adaptation is done. 470/// 471/// For example: 472/// \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher); 473/// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher 474/// that is convertible into any matcher of type \c To by constructing 475/// \c HasMatcher<To, T>(InnerMatcher). 476/// 477/// If a matcher does not need knowledge about the inner type, prefer to use 478/// PolymorphicMatcherWithParam1. 479template <template <typename ToArg, typename FromArg> class ArgumentAdapterT, 480 typename T> 481class ArgumentAdaptingMatcher { 482public: 483 explicit ArgumentAdaptingMatcher(const Matcher<T> &InnerMatcher) 484 : InnerMatcher(InnerMatcher) {} 485 486 template <typename To> 487 operator Matcher<To>() const { 488 return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher)); 489 } 490 491private: 492 const Matcher<T> InnerMatcher; 493}; 494 495/// \brief A PolymorphicMatcherWithParamN<MatcherT, P1, ..., PN> object can be 496/// created from N parameters p1, ..., pN (of type P1, ..., PN) and 497/// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN) 498/// can be constructed. 499/// 500/// For example: 501/// - PolymorphicMatcherWithParam0<IsDefinitionMatcher>() 502/// creates an object that can be used as a Matcher<T> for any type T 503/// where an IsDefinitionMatcher<T>() can be constructed. 504/// - PolymorphicMatcherWithParam1<ValueEqualsMatcher, int>(42) 505/// creates an object that can be used as a Matcher<T> for any type T 506/// where a ValueEqualsMatcher<T, int>(42) can be constructed. 507template <template <typename T> class MatcherT> 508class PolymorphicMatcherWithParam0 { 509public: 510 template <typename T> 511 operator Matcher<T>() const { 512 return Matcher<T>(new MatcherT<T>()); 513 } 514}; 515 516template <template <typename T, typename P1> class MatcherT, 517 typename P1> 518class PolymorphicMatcherWithParam1 { 519public: 520 explicit PolymorphicMatcherWithParam1(const P1 &Param1) 521 : Param1(Param1) {} 522 523 template <typename T> 524 operator Matcher<T>() const { 525 return Matcher<T>(new MatcherT<T, P1>(Param1)); 526 } 527 528private: 529 const P1 Param1; 530}; 531 532template <template <typename T, typename P1, typename P2> class MatcherT, 533 typename P1, typename P2> 534class PolymorphicMatcherWithParam2 { 535public: 536 PolymorphicMatcherWithParam2(const P1 &Param1, const P2 &Param2) 537 : Param1(Param1), Param2(Param2) {} 538 539 template <typename T> 540 operator Matcher<T>() const { 541 return Matcher<T>(new MatcherT<T, P1, P2>(Param1, Param2)); 542 } 543 544private: 545 const P1 Param1; 546 const P2 Param2; 547}; 548 549/// \brief Matches any instance of the given NodeType. 550/// 551/// This is useful when a matcher syntactically requires a child matcher, 552/// but the context doesn't care. See for example: anything(). 553/// 554/// FIXME: Alternatively we could also create a IsAMatcher or something 555/// that checks that a dyn_cast is possible. This is purely needed for the 556/// difference between calling for example: 557/// record() 558/// and 559/// record(SomeMatcher) 560/// In the second case we need the correct type we were dyn_cast'ed to in order 561/// to get the right type for the inner matcher. In the first case we don't need 562/// that, but we use the type conversion anyway and insert a TrueMatcher. 563template <typename T> 564class TrueMatcher : public SingleNodeMatcherInterface<T> { 565public: 566 virtual bool matchesNode(const T &Node) const { 567 return true; 568 } 569}; 570 571/// \brief Provides a MatcherInterface<T> for a Matcher<To> that matches if T is 572/// dyn_cast'able into To and the given Matcher<To> matches on the dyn_cast'ed 573/// node. 574template <typename T, typename To> 575class DynCastMatcher : public MatcherInterface<T> { 576public: 577 explicit DynCastMatcher(const Matcher<To> &InnerMatcher) 578 : InnerMatcher(InnerMatcher) {} 579 580 virtual bool matches(const T &Node, 581 ASTMatchFinder *Finder, 582 BoundNodesTreeBuilder *Builder) const { 583 const To *InnerMatchValue = llvm::dyn_cast<To>(&Node); 584 return InnerMatchValue != NULL && 585 InnerMatcher.matches(*InnerMatchValue, Finder, Builder); 586 } 587 588private: 589 const Matcher<To> InnerMatcher; 590}; 591 592/// \brief Matcher<T> that wraps an inner Matcher<T> and binds the matched node 593/// to an ID if the inner matcher matches on the node. 594template <typename T> 595class IdMatcher : public MatcherInterface<T> { 596public: 597 /// \brief Creates an IdMatcher that binds to 'ID' if 'InnerMatcher' matches 598 /// the node. 599 IdMatcher(StringRef ID, const Matcher<T> &InnerMatcher) 600 : ID(ID), InnerMatcher(InnerMatcher) {} 601 602 virtual bool matches(const T &Node, 603 ASTMatchFinder *Finder, 604 BoundNodesTreeBuilder *Builder) const { 605 bool Result = InnerMatcher.matches(Node, Finder, Builder); 606 if (Result) { 607 Builder->setBinding(ID, &Node); 608 } 609 return Result; 610 } 611 612private: 613 const std::string ID; 614 const Matcher<T> InnerMatcher; 615}; 616 617/// \brief A Matcher that allows binding the node it matches to an id. 618/// 619/// BindableMatcher provides a \a bind() method that allows binding the 620/// matched node to an id if the match was successful. 621template <typename T> 622class BindableMatcher : public Matcher<T> { 623public: 624 BindableMatcher(MatcherInterface<T> *Implementation) 625 : Matcher<T>(Implementation) {} 626 627 /// \brief Returns a matcher that will bind the matched node on a match. 628 /// 629 /// The returned matcher is equivalent to this matcher, but will 630 /// bind the matched node on a match. 631 Matcher<T> bind(StringRef ID) const { 632 TOOLING_COMPILE_ASSERT((llvm::is_base_of<Stmt, T>::value || 633 llvm::is_base_of<Decl, T>::value), 634 trying_to_bind_unsupported_node_type__only_decl_and_stmt_supported); 635 return Matcher<T>(new IdMatcher<T>(ID, *this)); 636 } 637}; 638 639/// \brief Matches nodes of type T that have child nodes of type ChildT for 640/// which a specified child matcher matches. 641/// 642/// ChildT must be an AST base type. 643template <typename T, typename ChildT> 644class HasMatcher : public MatcherInterface<T> { 645 TOOLING_COMPILE_ASSERT(IsBaseType<ChildT>::value, 646 has_only_accepts_base_type_matcher); 647public: 648 explicit HasMatcher(const Matcher<ChildT> &ChildMatcher) 649 : ChildMatcher(ChildMatcher) {} 650 651 virtual bool matches(const T &Node, 652 ASTMatchFinder *Finder, 653 BoundNodesTreeBuilder *Builder) const { 654 return Finder->matchesChildOf( 655 Node, ChildMatcher, Builder, 656 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses, 657 ASTMatchFinder::BK_First); 658 } 659 660 private: 661 const Matcher<ChildT> ChildMatcher; 662}; 663 664/// \brief Matches nodes of type T that have child nodes of type ChildT for 665/// which a specified child matcher matches. ChildT must be an AST base 666/// type. 667/// As opposed to the HasMatcher, the ForEachMatcher will produce a match 668/// for each child that matches. 669template <typename T, typename ChildT> 670class ForEachMatcher : public MatcherInterface<T> { 671 TOOLING_COMPILE_ASSERT(IsBaseType<ChildT>::value, 672 for_each_only_accepts_base_type_matcher); 673 public: 674 explicit ForEachMatcher(const Matcher<ChildT> &ChildMatcher) 675 : ChildMatcher(ChildMatcher) {} 676 677 virtual bool matches(const T& Node, 678 ASTMatchFinder* Finder, 679 BoundNodesTreeBuilder* Builder) const { 680 return Finder->matchesChildOf( 681 Node, ChildMatcher, Builder, 682 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses, 683 ASTMatchFinder::BK_All); 684 } 685 686private: 687 const Matcher<ChildT> ChildMatcher; 688}; 689 690/// \brief Matches nodes of type T if the given Matcher<T> does not match. 691/// 692/// Type argument MatcherT is required by PolymorphicMatcherWithParam1 693/// but not actually used. It will always be instantiated with a type 694/// convertible to Matcher<T>. 695template <typename T, typename MatcherT> 696class NotMatcher : public MatcherInterface<T> { 697public: 698 explicit NotMatcher(const Matcher<T> &InnerMatcher) 699 : InnerMatcher(InnerMatcher) {} 700 701 virtual bool matches(const T &Node, 702 ASTMatchFinder *Finder, 703 BoundNodesTreeBuilder *Builder) const { 704 return !InnerMatcher.matches(Node, Finder, Builder); 705 } 706 707private: 708 const Matcher<T> InnerMatcher; 709}; 710 711/// \brief Matches nodes of type T for which both provided matchers match. 712/// 713/// Type arguments MatcherT1 and MatcherT2 are required by 714/// PolymorphicMatcherWithParam2 but not actually used. They will 715/// always be instantiated with types convertible to Matcher<T>. 716template <typename T, typename MatcherT1, typename MatcherT2> 717class AllOfMatcher : public MatcherInterface<T> { 718public: 719 AllOfMatcher(const Matcher<T> &InnerMatcher1, const Matcher<T> &InnerMatcher2) 720 : InnerMatcher1(InnerMatcher1), InnerMatcher2(InnerMatcher2) {} 721 722 virtual bool matches(const T &Node, 723 ASTMatchFinder *Finder, 724 BoundNodesTreeBuilder *Builder) const { 725 return InnerMatcher1.matches(Node, Finder, Builder) && 726 InnerMatcher2.matches(Node, Finder, Builder); 727 } 728 729private: 730 const Matcher<T> InnerMatcher1; 731 const Matcher<T> InnerMatcher2; 732}; 733 734/// \brief Matches nodes of type T for which at least one of the two provided 735/// matchers matches. 736/// 737/// Type arguments MatcherT1 and MatcherT2 are 738/// required by PolymorphicMatcherWithParam2 but not actually 739/// used. They will always be instantiated with types convertible to 740/// Matcher<T>. 741template <typename T, typename MatcherT1, typename MatcherT2> 742class AnyOfMatcher : public MatcherInterface<T> { 743public: 744 AnyOfMatcher(const Matcher<T> &InnerMatcher1, const Matcher<T> &InnerMatcher2) 745 : InnerMatcher1(InnerMatcher1), InnertMatcher2(InnerMatcher2) {} 746 747 virtual bool matches(const T &Node, 748 ASTMatchFinder *Finder, 749 BoundNodesTreeBuilder *Builder) const { 750 return InnerMatcher1.matches(Node, Finder, Builder) || 751 InnertMatcher2.matches(Node, Finder, Builder); 752 } 753 754private: 755 const Matcher<T> InnerMatcher1; 756 const Matcher<T> InnertMatcher2; 757}; 758 759/// \brief Creates a Matcher<T> that matches if 760/// T is dyn_cast'able into InnerT and all inner matchers match. 761/// 762/// Returns BindableMatcher, as matchers that use dyn_cast have 763/// the same object both to match on and to run submatchers on, 764/// so there is no ambiguity with what gets bound. 765template<typename T, typename InnerT> 766BindableMatcher<T> makeDynCastAllOfComposite( 767 ArrayRef<const Matcher<InnerT> *> InnerMatchers) { 768 if (InnerMatchers.empty()) { 769 Matcher<InnerT> InnerMatcher = makeMatcher(new TrueMatcher<InnerT>); 770 return BindableMatcher<T>(new DynCastMatcher<T, InnerT>(InnerMatcher)); 771 } 772 Matcher<InnerT> InnerMatcher = *InnerMatchers.back(); 773 for (int i = InnerMatchers.size() - 2; i >= 0; --i) { 774 InnerMatcher = makeMatcher( 775 new AllOfMatcher<InnerT, Matcher<InnerT>, Matcher<InnerT> >( 776 *InnerMatchers[i], InnerMatcher)); 777 } 778 return BindableMatcher<T>(new DynCastMatcher<T, InnerT>(InnerMatcher)); 779} 780 781/// \brief Matches nodes of type T that have at least one descendant node of 782/// type DescendantT for which the given inner matcher matches. 783/// 784/// DescendantT must be an AST base type. 785template <typename T, typename DescendantT> 786class HasDescendantMatcher : public MatcherInterface<T> { 787 TOOLING_COMPILE_ASSERT(IsBaseType<DescendantT>::value, 788 has_descendant_only_accepts_base_type_matcher); 789public: 790 explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher) 791 : DescendantMatcher(DescendantMatcher) {} 792 793 virtual bool matches(const T &Node, 794 ASTMatchFinder *Finder, 795 BoundNodesTreeBuilder *Builder) const { 796 return Finder->matchesDescendantOf( 797 Node, DescendantMatcher, Builder, ASTMatchFinder::BK_First); 798 } 799 800 private: 801 const Matcher<DescendantT> DescendantMatcher; 802}; 803 804/// \brief Matches nodes of type T that have at least one descendant node of 805/// type DescendantT for which the given inner matcher matches. 806/// 807/// DescendantT must be an AST base type. 808/// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match 809/// for each descendant node that matches instead of only for the first. 810template <typename T, typename DescendantT> 811class ForEachDescendantMatcher : public MatcherInterface<T> { 812 TOOLING_COMPILE_ASSERT(IsBaseType<DescendantT>::value, 813 for_each_descendant_only_accepts_base_type_matcher); 814 public: 815 explicit ForEachDescendantMatcher( 816 const Matcher<DescendantT>& DescendantMatcher) 817 : DescendantMatcher(DescendantMatcher) {} 818 819 virtual bool matches(const T& Node, 820 ASTMatchFinder* Finder, 821 BoundNodesTreeBuilder* Builder) const { 822 return Finder->matchesDescendantOf(Node, DescendantMatcher, Builder, 823 ASTMatchFinder::BK_All); 824 } 825 826private: 827 const Matcher<DescendantT> DescendantMatcher; 828}; 829 830/// \brief Matches on nodes that have a getValue() method if getValue() equals 831/// the value the ValueEqualsMatcher was constructed with. 832template <typename T, typename ValueT> 833class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> { 834 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CharacterLiteral, T>::value || 835 llvm::is_base_of<CXXBoolLiteralExpr, 836 T>::value || 837 llvm::is_base_of<FloatingLiteral, T>::value || 838 llvm::is_base_of<IntegerLiteral, T>::value), 839 the_node_must_have_a_getValue_method); 840public: 841 explicit ValueEqualsMatcher(const ValueT &ExpectedValue) 842 : ExpectedValue(ExpectedValue) {} 843 844 virtual bool matchesNode(const T &Node) const { 845 return Node.getValue() == ExpectedValue; 846 } 847 848private: 849 const ValueT ExpectedValue; 850}; 851 852template <typename T> 853class IsDefinitionMatcher : public SingleNodeMatcherInterface<T> { 854 TOOLING_COMPILE_ASSERT( 855 (llvm::is_base_of<TagDecl, T>::value) || 856 (llvm::is_base_of<VarDecl, T>::value) || 857 (llvm::is_base_of<FunctionDecl, T>::value), 858 is_definition_requires_isThisDeclarationADefinition_method); 859public: 860 virtual bool matchesNode(const T &Node) const { 861 return Node.isThisDeclarationADefinition(); 862 } 863}; 864 865/// \brief Matches on template instantiations for FunctionDecl, VarDecl or 866/// CXXRecordDecl nodes. 867template <typename T> 868class IsTemplateInstantiationMatcher : public MatcherInterface<T> { 869 TOOLING_COMPILE_ASSERT((llvm::is_base_of<FunctionDecl, T>::value) || 870 (llvm::is_base_of<VarDecl, T>::value) || 871 (llvm::is_base_of<CXXRecordDecl, T>::value), 872 requires_getTemplateSpecializationKind_method); 873 public: 874 virtual bool matches(const T& Node, 875 ASTMatchFinder* Finder, 876 BoundNodesTreeBuilder* Builder) const { 877 return (Node.getTemplateSpecializationKind() == 878 TSK_ImplicitInstantiation || 879 Node.getTemplateSpecializationKind() == 880 TSK_ExplicitInstantiationDefinition); 881 } 882}; 883 884/// \brief Matches on explicit template specializations for FunctionDecl, 885/// VarDecl or CXXRecordDecl nodes. 886template <typename T> 887class IsExplicitTemplateSpecializationMatcher : public MatcherInterface<T> { 888 TOOLING_COMPILE_ASSERT((llvm::is_base_of<FunctionDecl, T>::value) || 889 (llvm::is_base_of<VarDecl, T>::value) || 890 (llvm::is_base_of<CXXRecordDecl, T>::value), 891 requires_getTemplateSpecializationKind_method); 892 public: 893 virtual bool matches(const T& Node, 894 ASTMatchFinder* Finder, 895 BoundNodesTreeBuilder* Builder) const { 896 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization); 897 } 898}; 899 900 901class IsArrowMatcher : public SingleNodeMatcherInterface<MemberExpr> { 902public: 903 virtual bool matchesNode(const MemberExpr &Node) const { 904 return Node.isArrow(); 905 } 906}; 907 908class IsConstQualifiedMatcher 909 : public SingleNodeMatcherInterface<QualType> { 910 public: 911 virtual bool matchesNode(const QualType& Node) const { 912 return Node.isConstQualified(); 913 } 914}; 915 916/// \brief A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a 917/// variadic functor that takes a number of Matcher<TargetT> and returns a 918/// Matcher<SourceT> that matches TargetT nodes that are matched by all of the 919/// given matchers, if SourceT can be dynamically casted into TargetT. 920/// 921/// For example: 922/// const VariadicDynCastAllOfMatcher< 923/// Decl, CXXRecordDecl> record; 924/// Creates a functor record(...) that creates a Matcher<Decl> given 925/// a variable number of arguments of type Matcher<CXXRecordDecl>. 926/// The returned matcher matches if the given Decl can by dynamically 927/// casted to CXXRecordDecl and all given matchers match. 928template <typename SourceT, typename TargetT> 929class VariadicDynCastAllOfMatcher 930 : public llvm::VariadicFunction< 931 BindableMatcher<SourceT>, Matcher<TargetT>, 932 makeDynCastAllOfComposite<SourceT, TargetT> > { 933public: 934 VariadicDynCastAllOfMatcher() {} 935}; 936 937} // end namespace internal 938} // end namespace ast_matchers 939} // end namespace clang 940 941#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H 942