ASTMatchersInternal.h revision b3278162bd6d34783607d4bfe8814df73e8ef8c1
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 &) LLVM_DELETED_FUNCTION; 178 void operator=(const BoundNodesTreeBuilder &) LLVM_DELETED_FUNCTION; 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 Implicitly converts \c Other to a Matcher<T>. 261 /// 262 /// Requires \c T to be derived from \c From. 263 template <typename From> 264 Matcher(const Matcher<From> &Other, 265 typename llvm::enable_if_c< 266 llvm::is_base_of<From, T>::value && 267 !llvm::is_same<From, T>::value >::type* = 0) 268 : Implementation(new ImplicitCastMatcher<From>(Other)) {} 269 270 /// \brief Forwards the call to the underlying MatcherInterface<T> pointer. 271 bool matches(const T &Node, 272 ASTMatchFinder *Finder, 273 BoundNodesTreeBuilder *Builder) const { 274 return Implementation->matches(Node, Finder, Builder); 275 } 276 277 /// \brief Returns an ID that uniquely identifies the matcher. 278 uint64_t getID() const { 279 /// FIXME: Document the requirements this imposes on matcher 280 /// implementations (no new() implementation_ during a Matches()). 281 return reinterpret_cast<uint64_t>(Implementation.getPtr()); 282 } 283 284 /// \brief Returns whether the matcher matches on the given \c DynNode. 285 virtual bool matches(const ast_type_traits::DynTypedNode DynNode, 286 ASTMatchFinder *Finder, 287 BoundNodesTreeBuilder *Builder) const { 288 const T *Node = DynNode.get<T>(); 289 if (!Node) return false; 290 return matches(*Node, Finder, Builder); 291 } 292 293private: 294 /// \brief Allows conversion from Matcher<Base> to Matcher<T> if T 295 /// is derived from Base. 296 template <typename Base> 297 class ImplicitCastMatcher : public MatcherInterface<T> { 298 public: 299 explicit ImplicitCastMatcher(const Matcher<Base> &From) 300 : From(From) {} 301 302 virtual bool matches(const T &Node, 303 ASTMatchFinder *Finder, 304 BoundNodesTreeBuilder *Builder) const { 305 return From.matches(Node, Finder, Builder); 306 } 307 308 private: 309 const Matcher<Base> From; 310 }; 311 312 llvm::IntrusiveRefCntPtr< MatcherInterface<T> > Implementation; 313}; // class Matcher 314 315/// \brief A convenient helper for creating a Matcher<T> without specifying 316/// the template type argument. 317template <typename T> 318inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) { 319 return Matcher<T>(Implementation); 320} 321 322/// \brief Matches declarations for QualType and CallExpr. 323/// 324/// Type argument DeclMatcherT is required by PolymorphicMatcherWithParam1 but 325/// not actually used. 326template <typename T, typename DeclMatcherT> 327class HasDeclarationMatcher : public MatcherInterface<T> { 328 TOOLING_COMPILE_ASSERT((llvm::is_same< DeclMatcherT, 329 Matcher<Decl> >::value), 330 instantiated_with_wrong_types); 331public: 332 explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher) 333 : InnerMatcher(InnerMatcher) {} 334 335 virtual bool matches(const T &Node, 336 ASTMatchFinder *Finder, 337 BoundNodesTreeBuilder *Builder) const { 338 return matchesSpecialized(Node, Finder, Builder); 339 } 340 341private: 342 /// \brief Extracts the CXXRecordDecl of a QualType and returns whether the 343 /// inner matcher matches on it. 344 bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder, 345 BoundNodesTreeBuilder *Builder) const { 346 /// FIXME: Add other ways to convert... 347 if (Node.isNull()) 348 return false; 349 CXXRecordDecl *NodeAsRecordDecl = Node->getAsCXXRecordDecl(); 350 return NodeAsRecordDecl != NULL && 351 InnerMatcher.matches(*NodeAsRecordDecl, Finder, Builder); 352 } 353 354 /// \brief Extracts the Decl of the callee of a CallExpr and returns whether 355 /// the inner matcher matches on it. 356 bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder, 357 BoundNodesTreeBuilder *Builder) const { 358 const Decl *NodeAsDecl = Node.getCalleeDecl(); 359 return NodeAsDecl != NULL && 360 InnerMatcher.matches(*NodeAsDecl, Finder, Builder); 361 } 362 363 /// \brief Extracts the Decl of the constructor call and returns whether the 364 /// inner matcher matches on it. 365 bool matchesSpecialized(const CXXConstructExpr &Node, 366 ASTMatchFinder *Finder, 367 BoundNodesTreeBuilder *Builder) const { 368 const Decl *NodeAsDecl = Node.getConstructor(); 369 return NodeAsDecl != NULL && 370 InnerMatcher.matches(*NodeAsDecl, Finder, Builder); 371 } 372 373 const Matcher<Decl> InnerMatcher; 374}; 375 376/// \brief IsBaseType<T>::value is true if T is a "base" type in the AST 377/// node class hierarchies (i.e. if T is Decl, Stmt, QualType, or 378/// CXXCtorInitializer). 379template <typename T> 380struct IsBaseType { 381 static const bool value = 382 (llvm::is_same<T, Decl>::value || 383 llvm::is_same<T, Stmt>::value || 384 llvm::is_same<T, QualType>::value || 385 llvm::is_same<T, NestedNameSpecifier>::value || 386 llvm::is_same<T, NestedNameSpecifierLoc>::value || 387 llvm::is_same<T, CXXCtorInitializer>::value); 388}; 389template <typename T> 390const bool IsBaseType<T>::value; 391 392/// \brief Interface that allows matchers to traverse the AST. 393/// FIXME: Find a better name. 394/// 395/// This provides three entry methods for each base node type in the AST: 396/// - \c matchesChildOf: 397/// Matches a matcher on every child node of the given node. Returns true 398/// if at least one child node could be matched. 399/// - \c matchesDescendantOf: 400/// Matches a matcher on all descendant nodes of the given node. Returns true 401/// if at least one descendant matched. 402/// - \c matchesAncestorOf: 403/// Matches a matcher on all ancestors of the given node. Returns true if 404/// at least one ancestor matched. 405/// 406/// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal. 407/// In the future, we wan to implement this for all nodes for which it makes 408/// sense. In the case of matchesAncestorOf, we'll want to implement it for 409/// all nodes, as all nodes have ancestors. 410class ASTMatchFinder { 411public: 412 /// \brief Defines how we descend a level in the AST when we pass 413 /// through expressions. 414 enum TraversalKind { 415 /// Will traverse any child nodes. 416 TK_AsIs, 417 /// Will not traverse implicit casts and parentheses. 418 TK_IgnoreImplicitCastsAndParentheses 419 }; 420 421 /// \brief Defines how bindings are processed on recursive matches. 422 enum BindKind { 423 /// Stop at the first match and only bind the first match. 424 BK_First, 425 /// Create results for all combinations of bindings that match. 426 BK_All 427 }; 428 429 virtual ~ASTMatchFinder() {} 430 431 /// \brief Returns true if the given class is directly or indirectly derived 432 /// from a base type matching \c base. 433 /// 434 /// A class is considered to be also derived from itself. 435 virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration, 436 const Matcher<NamedDecl> &Base, 437 BoundNodesTreeBuilder *Builder) = 0; 438 439 template <typename T> 440 bool matchesChildOf(const T &Node, 441 const DynTypedMatcher &Matcher, 442 BoundNodesTreeBuilder *Builder, 443 TraversalKind Traverse, 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 matchesChildOf(ast_type_traits::DynTypedNode::create(Node), 449 Matcher, Builder, Traverse, Bind); 450 } 451 452 template <typename T> 453 bool matchesDescendantOf(const T &Node, 454 const DynTypedMatcher &Matcher, 455 BoundNodesTreeBuilder *Builder, 456 BindKind Bind) { 457 TOOLING_COMPILE_ASSERT((llvm::is_base_of<Decl, T>::value || 458 llvm::is_base_of<Stmt, T>::value), 459 only_Decl_or_Stmt_allowed_for_recursive_matching); 460 return matchesDescendantOf(ast_type_traits::DynTypedNode::create(Node), 461 Matcher, Builder, Bind); 462 } 463 464 // FIXME: Implement support for BindKind. 465 template <typename T> 466 bool matchesAncestorOf(const T &Node, 467 const DynTypedMatcher &Matcher, 468 BoundNodesTreeBuilder *Builder) { 469 TOOLING_COMPILE_ASSERT((llvm::is_base_of<Decl, T>::value || 470 llvm::is_base_of<Stmt, T>::value), 471 only_Decl_or_Stmt_allowed_for_recursive_matching); 472 return matchesAncestorOf(ast_type_traits::DynTypedNode::create(Node), 473 Matcher, Builder); 474 } 475 476protected: 477 virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node, 478 const DynTypedMatcher &Matcher, 479 BoundNodesTreeBuilder *Builder, 480 TraversalKind Traverse, 481 BindKind Bind) = 0; 482 483 virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node, 484 const DynTypedMatcher &Matcher, 485 BoundNodesTreeBuilder *Builder, 486 BindKind Bind) = 0; 487 488 virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node, 489 const DynTypedMatcher &Matcher, 490 BoundNodesTreeBuilder *Builder) = 0; 491}; 492 493/// \brief Converts a \c Matcher<T> to a matcher of desired type \c To by 494/// "adapting" a \c To into a \c T. 495/// 496/// The \c ArgumentAdapterT argument specifies how the adaptation is done. 497/// 498/// For example: 499/// \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher); 500/// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher 501/// that is convertible into any matcher of type \c To by constructing 502/// \c HasMatcher<To, T>(InnerMatcher). 503/// 504/// If a matcher does not need knowledge about the inner type, prefer to use 505/// PolymorphicMatcherWithParam1. 506template <template <typename ToArg, typename FromArg> class ArgumentAdapterT, 507 typename T> 508class ArgumentAdaptingMatcher { 509public: 510 explicit ArgumentAdaptingMatcher(const Matcher<T> &InnerMatcher) 511 : InnerMatcher(InnerMatcher) {} 512 513 template <typename To> 514 operator Matcher<To>() const { 515 return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher)); 516 } 517 518private: 519 const Matcher<T> InnerMatcher; 520}; 521 522/// \brief A PolymorphicMatcherWithParamN<MatcherT, P1, ..., PN> object can be 523/// created from N parameters p1, ..., pN (of type P1, ..., PN) and 524/// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN) 525/// can be constructed. 526/// 527/// For example: 528/// - PolymorphicMatcherWithParam0<IsDefinitionMatcher>() 529/// creates an object that can be used as a Matcher<T> for any type T 530/// where an IsDefinitionMatcher<T>() can be constructed. 531/// - PolymorphicMatcherWithParam1<ValueEqualsMatcher, int>(42) 532/// creates an object that can be used as a Matcher<T> for any type T 533/// where a ValueEqualsMatcher<T, int>(42) can be constructed. 534template <template <typename T> class MatcherT> 535class PolymorphicMatcherWithParam0 { 536public: 537 template <typename T> 538 operator Matcher<T>() const { 539 return Matcher<T>(new MatcherT<T>()); 540 } 541}; 542 543template <template <typename T, typename P1> class MatcherT, 544 typename P1> 545class PolymorphicMatcherWithParam1 { 546public: 547 explicit PolymorphicMatcherWithParam1(const P1 &Param1) 548 : Param1(Param1) {} 549 550 template <typename T> 551 operator Matcher<T>() const { 552 return Matcher<T>(new MatcherT<T, P1>(Param1)); 553 } 554 555private: 556 const P1 Param1; 557}; 558 559template <template <typename T, typename P1, typename P2> class MatcherT, 560 typename P1, typename P2> 561class PolymorphicMatcherWithParam2 { 562public: 563 PolymorphicMatcherWithParam2(const P1 &Param1, const P2 &Param2) 564 : Param1(Param1), Param2(Param2) {} 565 566 template <typename T> 567 operator Matcher<T>() const { 568 return Matcher<T>(new MatcherT<T, P1, P2>(Param1, Param2)); 569 } 570 571private: 572 const P1 Param1; 573 const P2 Param2; 574}; 575 576/// \brief Matches any instance of the given NodeType. 577/// 578/// This is useful when a matcher syntactically requires a child matcher, 579/// but the context doesn't care. See for example: anything(). 580/// 581/// FIXME: Alternatively we could also create a IsAMatcher or something 582/// that checks that a dyn_cast is possible. This is purely needed for the 583/// difference between calling for example: 584/// record() 585/// and 586/// record(SomeMatcher) 587/// In the second case we need the correct type we were dyn_cast'ed to in order 588/// to get the right type for the inner matcher. In the first case we don't need 589/// that, but we use the type conversion anyway and insert a TrueMatcher. 590template <typename T> 591class TrueMatcher : public SingleNodeMatcherInterface<T> { 592public: 593 virtual bool matchesNode(const T &Node) const { 594 return true; 595 } 596}; 597 598/// \brief Provides a MatcherInterface<T> for a Matcher<To> that matches if T is 599/// dyn_cast'able into To and the given Matcher<To> matches on the dyn_cast'ed 600/// node. 601template <typename T, typename To> 602class DynCastMatcher : public MatcherInterface<T> { 603public: 604 explicit DynCastMatcher(const Matcher<To> &InnerMatcher) 605 : InnerMatcher(InnerMatcher) {} 606 607 virtual bool matches(const T &Node, 608 ASTMatchFinder *Finder, 609 BoundNodesTreeBuilder *Builder) const { 610 const To *InnerMatchValue = llvm::dyn_cast<To>(&Node); 611 return InnerMatchValue != NULL && 612 InnerMatcher.matches(*InnerMatchValue, Finder, Builder); 613 } 614 615private: 616 const Matcher<To> InnerMatcher; 617}; 618 619/// \brief Matcher<T> that wraps an inner Matcher<T> and binds the matched node 620/// to an ID if the inner matcher matches on the node. 621template <typename T> 622class IdMatcher : public MatcherInterface<T> { 623public: 624 /// \brief Creates an IdMatcher that binds to 'ID' if 'InnerMatcher' matches 625 /// the node. 626 IdMatcher(StringRef ID, const Matcher<T> &InnerMatcher) 627 : ID(ID), InnerMatcher(InnerMatcher) {} 628 629 virtual bool matches(const T &Node, 630 ASTMatchFinder *Finder, 631 BoundNodesTreeBuilder *Builder) const { 632 bool Result = InnerMatcher.matches(Node, Finder, Builder); 633 if (Result) { 634 Builder->setBinding(ID, &Node); 635 } 636 return Result; 637 } 638 639private: 640 const std::string ID; 641 const Matcher<T> InnerMatcher; 642}; 643 644/// \brief A Matcher that allows binding the node it matches to an id. 645/// 646/// BindableMatcher provides a \a bind() method that allows binding the 647/// matched node to an id if the match was successful. 648template <typename T> 649class BindableMatcher : public Matcher<T> { 650public: 651 BindableMatcher(MatcherInterface<T> *Implementation) 652 : Matcher<T>(Implementation) {} 653 654 /// \brief Returns a matcher that will bind the matched node on a match. 655 /// 656 /// The returned matcher is equivalent to this matcher, but will 657 /// bind the matched node on a match. 658 Matcher<T> bind(StringRef ID) const { 659 return Matcher<T>(new IdMatcher<T>(ID, *this)); 660 } 661}; 662 663/// \brief Matches nodes of type T that have child nodes of type ChildT for 664/// which a specified child matcher matches. 665/// 666/// ChildT must be an AST base type. 667template <typename T, typename ChildT> 668class HasMatcher : public MatcherInterface<T> { 669 TOOLING_COMPILE_ASSERT(IsBaseType<ChildT>::value, 670 has_only_accepts_base_type_matcher); 671public: 672 explicit HasMatcher(const Matcher<ChildT> &ChildMatcher) 673 : ChildMatcher(ChildMatcher) {} 674 675 virtual bool matches(const T &Node, 676 ASTMatchFinder *Finder, 677 BoundNodesTreeBuilder *Builder) const { 678 return Finder->matchesChildOf( 679 Node, ChildMatcher, Builder, 680 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses, 681 ASTMatchFinder::BK_First); 682 } 683 684 private: 685 const Matcher<ChildT> ChildMatcher; 686}; 687 688/// \brief Matches nodes of type T that have child nodes of type ChildT for 689/// which a specified child matcher matches. ChildT must be an AST base 690/// type. 691/// As opposed to the HasMatcher, the ForEachMatcher will produce a match 692/// for each child that matches. 693template <typename T, typename ChildT> 694class ForEachMatcher : public MatcherInterface<T> { 695 TOOLING_COMPILE_ASSERT(IsBaseType<ChildT>::value, 696 for_each_only_accepts_base_type_matcher); 697 public: 698 explicit ForEachMatcher(const Matcher<ChildT> &ChildMatcher) 699 : ChildMatcher(ChildMatcher) {} 700 701 virtual bool matches(const T& Node, 702 ASTMatchFinder* Finder, 703 BoundNodesTreeBuilder* Builder) const { 704 return Finder->matchesChildOf( 705 Node, ChildMatcher, Builder, 706 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses, 707 ASTMatchFinder::BK_All); 708 } 709 710private: 711 const Matcher<ChildT> ChildMatcher; 712}; 713 714/// \brief Matches nodes of type T if the given Matcher<T> does not match. 715/// 716/// Type argument MatcherT is required by PolymorphicMatcherWithParam1 717/// but not actually used. It will always be instantiated with a type 718/// convertible to Matcher<T>. 719template <typename T, typename MatcherT> 720class NotMatcher : public MatcherInterface<T> { 721public: 722 explicit NotMatcher(const Matcher<T> &InnerMatcher) 723 : InnerMatcher(InnerMatcher) {} 724 725 virtual bool matches(const T &Node, 726 ASTMatchFinder *Finder, 727 BoundNodesTreeBuilder *Builder) const { 728 return !InnerMatcher.matches(Node, Finder, Builder); 729 } 730 731private: 732 const Matcher<T> InnerMatcher; 733}; 734 735/// \brief Matches nodes of type T for which both provided matchers match. 736/// 737/// Type arguments MatcherT1 and MatcherT2 are required by 738/// PolymorphicMatcherWithParam2 but not actually used. They will 739/// always be instantiated with types convertible to Matcher<T>. 740template <typename T, typename MatcherT1, typename MatcherT2> 741class AllOfMatcher : public MatcherInterface<T> { 742public: 743 AllOfMatcher(const Matcher<T> &InnerMatcher1, const Matcher<T> &InnerMatcher2) 744 : InnerMatcher1(InnerMatcher1), InnerMatcher2(InnerMatcher2) {} 745 746 virtual bool matches(const T &Node, 747 ASTMatchFinder *Finder, 748 BoundNodesTreeBuilder *Builder) const { 749 return InnerMatcher1.matches(Node, Finder, Builder) && 750 InnerMatcher2.matches(Node, Finder, Builder); 751 } 752 753private: 754 const Matcher<T> InnerMatcher1; 755 const Matcher<T> InnerMatcher2; 756}; 757 758/// \brief Matches nodes of type T for which at least one of the two provided 759/// matchers matches. 760/// 761/// Type arguments MatcherT1 and MatcherT2 are 762/// required by PolymorphicMatcherWithParam2 but not actually 763/// used. They will always be instantiated with types convertible to 764/// Matcher<T>. 765template <typename T, typename MatcherT1, typename MatcherT2> 766class AnyOfMatcher : public MatcherInterface<T> { 767public: 768 AnyOfMatcher(const Matcher<T> &InnerMatcher1, const Matcher<T> &InnerMatcher2) 769 : InnerMatcher1(InnerMatcher1), InnertMatcher2(InnerMatcher2) {} 770 771 virtual bool matches(const T &Node, 772 ASTMatchFinder *Finder, 773 BoundNodesTreeBuilder *Builder) const { 774 return InnerMatcher1.matches(Node, Finder, Builder) || 775 InnertMatcher2.matches(Node, Finder, Builder); 776 } 777 778private: 779 const Matcher<T> InnerMatcher1; 780 const Matcher<T> InnertMatcher2; 781}; 782 783/// \brief Creates a Matcher<T> that matches if all inner matchers match. 784template<typename T> 785BindableMatcher<T> makeAllOfComposite( 786 ArrayRef<const Matcher<T> *> InnerMatchers) { 787 if (InnerMatchers.empty()) 788 return BindableMatcher<T>(new TrueMatcher<T>); 789 MatcherInterface<T> *InnerMatcher = new TrueMatcher<T>; 790 for (int i = InnerMatchers.size() - 1; i >= 0; --i) { 791 InnerMatcher = new AllOfMatcher<T, Matcher<T>, Matcher<T> >( 792 *InnerMatchers[i], makeMatcher(InnerMatcher)); 793 } 794 return BindableMatcher<T>(InnerMatcher); 795} 796 797/// \brief Creates a Matcher<T> that matches if 798/// T is dyn_cast'able into InnerT and all inner matchers match. 799/// 800/// Returns BindableMatcher, as matchers that use dyn_cast have 801/// the same object both to match on and to run submatchers on, 802/// so there is no ambiguity with what gets bound. 803template<typename T, typename InnerT> 804BindableMatcher<T> makeDynCastAllOfComposite( 805 ArrayRef<const Matcher<InnerT> *> InnerMatchers) { 806 return BindableMatcher<T>(new DynCastMatcher<T, InnerT>( 807 makeAllOfComposite(InnerMatchers))); 808} 809 810/// \brief Matches nodes of type T that have at least one descendant node of 811/// type DescendantT for which the given inner matcher matches. 812/// 813/// DescendantT must be an AST base type. 814template <typename T, typename DescendantT> 815class HasDescendantMatcher : public MatcherInterface<T> { 816 TOOLING_COMPILE_ASSERT(IsBaseType<DescendantT>::value, 817 has_descendant_only_accepts_base_type_matcher); 818public: 819 explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher) 820 : DescendantMatcher(DescendantMatcher) {} 821 822 virtual bool matches(const T &Node, 823 ASTMatchFinder *Finder, 824 BoundNodesTreeBuilder *Builder) const { 825 return Finder->matchesDescendantOf( 826 Node, DescendantMatcher, Builder, ASTMatchFinder::BK_First); 827 } 828 829 private: 830 const Matcher<DescendantT> DescendantMatcher; 831}; 832 833/// \brief Matches nodes of type \c T that have at least one ancestor node of 834/// type \c AncestorT for which the given inner matcher matches. 835/// 836/// \c AncestorT must be an AST base type. 837template <typename T, typename AncestorT> 838class HasAncestorMatcher : public MatcherInterface<T> { 839 TOOLING_COMPILE_ASSERT(IsBaseType<AncestorT>::value, 840 has_ancestor_only_accepts_base_type_matcher); 841public: 842 explicit HasAncestorMatcher(const Matcher<AncestorT> &AncestorMatcher) 843 : AncestorMatcher(AncestorMatcher) {} 844 845 virtual bool matches(const T &Node, 846 ASTMatchFinder *Finder, 847 BoundNodesTreeBuilder *Builder) const { 848 return Finder->matchesAncestorOf( 849 Node, AncestorMatcher, Builder); 850 } 851 852 private: 853 const Matcher<AncestorT> AncestorMatcher; 854}; 855 856/// \brief Matches nodes of type T that have at least one descendant node of 857/// type DescendantT for which the given inner matcher matches. 858/// 859/// DescendantT must be an AST base type. 860/// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match 861/// for each descendant node that matches instead of only for the first. 862template <typename T, typename DescendantT> 863class ForEachDescendantMatcher : public MatcherInterface<T> { 864 TOOLING_COMPILE_ASSERT(IsBaseType<DescendantT>::value, 865 for_each_descendant_only_accepts_base_type_matcher); 866 public: 867 explicit ForEachDescendantMatcher( 868 const Matcher<DescendantT>& DescendantMatcher) 869 : DescendantMatcher(DescendantMatcher) {} 870 871 virtual bool matches(const T& Node, 872 ASTMatchFinder* Finder, 873 BoundNodesTreeBuilder* Builder) const { 874 return Finder->matchesDescendantOf(Node, DescendantMatcher, Builder, 875 ASTMatchFinder::BK_All); 876 } 877 878private: 879 const Matcher<DescendantT> DescendantMatcher; 880}; 881 882/// \brief Matches on nodes that have a getValue() method if getValue() equals 883/// the value the ValueEqualsMatcher was constructed with. 884template <typename T, typename ValueT> 885class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> { 886 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CharacterLiteral, T>::value || 887 llvm::is_base_of<CXXBoolLiteralExpr, 888 T>::value || 889 llvm::is_base_of<FloatingLiteral, T>::value || 890 llvm::is_base_of<IntegerLiteral, T>::value), 891 the_node_must_have_a_getValue_method); 892public: 893 explicit ValueEqualsMatcher(const ValueT &ExpectedValue) 894 : ExpectedValue(ExpectedValue) {} 895 896 virtual bool matchesNode(const T &Node) const { 897 return Node.getValue() == ExpectedValue; 898 } 899 900private: 901 const ValueT ExpectedValue; 902}; 903 904template <typename T> 905class IsDefinitionMatcher : public SingleNodeMatcherInterface<T> { 906 TOOLING_COMPILE_ASSERT( 907 (llvm::is_base_of<TagDecl, T>::value) || 908 (llvm::is_base_of<VarDecl, T>::value) || 909 (llvm::is_base_of<FunctionDecl, T>::value), 910 is_definition_requires_isThisDeclarationADefinition_method); 911public: 912 virtual bool matchesNode(const T &Node) const { 913 return Node.isThisDeclarationADefinition(); 914 } 915}; 916 917/// \brief Matches on template instantiations for FunctionDecl, VarDecl or 918/// CXXRecordDecl nodes. 919template <typename T> 920class IsTemplateInstantiationMatcher : public MatcherInterface<T> { 921 TOOLING_COMPILE_ASSERT((llvm::is_base_of<FunctionDecl, T>::value) || 922 (llvm::is_base_of<VarDecl, T>::value) || 923 (llvm::is_base_of<CXXRecordDecl, T>::value), 924 requires_getTemplateSpecializationKind_method); 925 public: 926 virtual bool matches(const T& Node, 927 ASTMatchFinder* Finder, 928 BoundNodesTreeBuilder* Builder) const { 929 return (Node.getTemplateSpecializationKind() == 930 TSK_ImplicitInstantiation || 931 Node.getTemplateSpecializationKind() == 932 TSK_ExplicitInstantiationDefinition); 933 } 934}; 935 936/// \brief Matches on explicit template specializations for FunctionDecl, 937/// VarDecl or CXXRecordDecl nodes. 938template <typename T> 939class IsExplicitTemplateSpecializationMatcher : public MatcherInterface<T> { 940 TOOLING_COMPILE_ASSERT((llvm::is_base_of<FunctionDecl, T>::value) || 941 (llvm::is_base_of<VarDecl, T>::value) || 942 (llvm::is_base_of<CXXRecordDecl, T>::value), 943 requires_getTemplateSpecializationKind_method); 944 public: 945 virtual bool matches(const T& Node, 946 ASTMatchFinder* Finder, 947 BoundNodesTreeBuilder* Builder) const { 948 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization); 949 } 950}; 951 952 953class IsArrowMatcher : public SingleNodeMatcherInterface<MemberExpr> { 954public: 955 virtual bool matchesNode(const MemberExpr &Node) const { 956 return Node.isArrow(); 957 } 958}; 959 960class IsConstQualifiedMatcher 961 : public SingleNodeMatcherInterface<QualType> { 962 public: 963 virtual bool matchesNode(const QualType& Node) const { 964 return Node.isConstQualified(); 965 } 966}; 967 968/// \brief A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a 969/// variadic functor that takes a number of Matcher<TargetT> and returns a 970/// Matcher<SourceT> that matches TargetT nodes that are matched by all of the 971/// given matchers, if SourceT can be dynamically casted into TargetT. 972/// 973/// For example: 974/// const VariadicDynCastAllOfMatcher< 975/// Decl, CXXRecordDecl> record; 976/// Creates a functor record(...) that creates a Matcher<Decl> given 977/// a variable number of arguments of type Matcher<CXXRecordDecl>. 978/// The returned matcher matches if the given Decl can by dynamically 979/// casted to CXXRecordDecl and all given matchers match. 980template <typename SourceT, typename TargetT> 981class VariadicDynCastAllOfMatcher 982 : public llvm::VariadicFunction< 983 BindableMatcher<SourceT>, Matcher<TargetT>, 984 makeDynCastAllOfComposite<SourceT, TargetT> > { 985public: 986 VariadicDynCastAllOfMatcher() {} 987}; 988 989/// \brief A \c VariadicAllOfMatcher<T> object is a variadic functor that takes 990/// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T 991/// nodes that are matched by all of the given matchers. 992/// 993/// For example: 994/// const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier; 995/// Creates a functor nestedNameSpecifier(...) that creates a 996/// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type 997/// \c Matcher<NestedNameSpecifier>. 998/// The returned matcher matches if all given matchers match. 999template <typename T> 1000class VariadicAllOfMatcher : public llvm::VariadicFunction< 1001 BindableMatcher<T>, Matcher<T>, 1002 makeAllOfComposite<T> > { 1003public: 1004 VariadicAllOfMatcher() {} 1005}; 1006 1007/// \brief Matches nodes of type \c TLoc for which the inner 1008/// \c Matcher<T> matches. 1009template <typename TLoc, typename T> 1010class LocMatcher : public MatcherInterface<TLoc> { 1011public: 1012 explicit LocMatcher(const Matcher<T> &InnerMatcher) 1013 : InnerMatcher(InnerMatcher) {} 1014 1015 virtual bool matches(const TLoc &Node, 1016 ASTMatchFinder *Finder, 1017 BoundNodesTreeBuilder *Builder) const { 1018 if (!Node) 1019 return false; 1020 return InnerMatcher.matches(*extract(Node), Finder, Builder); 1021 } 1022 1023private: 1024 const NestedNameSpecifier *extract(const NestedNameSpecifierLoc &Loc) const { 1025 return Loc.getNestedNameSpecifier(); 1026 } 1027 // FIXME: Add overload for TypeLoc when implementing TypeLoc-matchers. 1028 1029 const Matcher<T> InnerMatcher; 1030}; 1031 1032/// \brief Matches nodes of type \c T for which the inner matcher matches on a 1033/// another node of type \c T that can be reached using a given traverse 1034/// function. 1035template <typename T> 1036class TraverseMatcher : public MatcherInterface<T> { 1037public: 1038 explicit TraverseMatcher(const Matcher<T> &InnerMatcher, 1039 T *(T::*TraverseFunction)() const) 1040 : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {} 1041 1042 virtual bool matches(const T &Node, 1043 ASTMatchFinder *Finder, 1044 BoundNodesTreeBuilder *Builder) const { 1045 T* NextNode = (Node.*TraverseFunction)(); 1046 if (NextNode == NULL) 1047 return false; 1048 return InnerMatcher.matches(*NextNode, Finder, Builder); 1049 } 1050 1051private: 1052 const Matcher<T> InnerMatcher; 1053 T *(T::*TraverseFunction)() const; 1054}; 1055 1056/// \brief Matches nodes of type \c T in a ..Loc hierarchy, for which the inner 1057/// matcher matches on a another node of type \c T that can be reached using a 1058/// given traverse function. 1059template <typename T> 1060class LocTraverseMatcher : public MatcherInterface<T> { 1061public: 1062 explicit LocTraverseMatcher(const Matcher<T> &InnerMatcher, 1063 T (T::*TraverseFunction)() const) 1064 : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {} 1065 1066 virtual bool matches(const T &Node, 1067 ASTMatchFinder *Finder, 1068 BoundNodesTreeBuilder *Builder) const { 1069 if (!Node) 1070 return false; 1071 T NextNode = (Node.*TraverseFunction)(); 1072 if (!NextNode) 1073 return false; 1074 return InnerMatcher.matches(NextNode, Finder, Builder); 1075 } 1076 1077private: 1078 const Matcher<T> InnerMatcher; 1079 T (T::*TraverseFunction)() const; 1080}; 1081 1082} // end namespace internal 1083} // end namespace ast_matchers 1084} // end namespace clang 1085 1086#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H 1087