ASTMatchersInternal.h revision b7488d77414b000ce2506b520a6b29f845fb3950
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/ASTTypeTraits.h" 39#include "clang/AST/Decl.h" 40#include "clang/AST/DeclCXX.h" 41#include "clang/AST/ExprCXX.h" 42#include "clang/AST/Stmt.h" 43#include "clang/AST/StmtCXX.h" 44#include "clang/AST/Type.h" 45#include "llvm/ADT/Optional.h" 46#include "llvm/ADT/VariadicFunction.h" 47#include "llvm/Support/type_traits.h" 48#include <map> 49#include <string> 50#include <vector> 51 52namespace clang { 53namespace ast_matchers { 54 55/// FIXME: Move into the llvm support library. 56template <bool> struct CompileAssert {}; 57#define TOOLING_COMPILE_ASSERT(Expr, Msg) \ 58 typedef CompileAssert<(bool(Expr))> Msg[bool(Expr) ? 1 : -1] 59 60class BoundNodes; 61 62namespace internal { 63 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 75 /// \brief Returns the AST node bound to \c ID. 76 /// 77 /// Returns NULL if there was no node bound to \c ID or if there is a node but 78 /// it cannot be converted to the specified type. 79 template <typename T> 80 const T *getNodeAs(StringRef ID) const { 81 IDToNodeMap::const_iterator It = NodeMap.find(ID); 82 if (It == NodeMap.end()) { 83 return NULL; 84 } 85 return It->second.get<T>(); 86 } 87 88 ast_type_traits::DynTypedNode getNode(StringRef ID) const { 89 IDToNodeMap::const_iterator It = NodeMap.find(ID); 90 if (It == NodeMap.end()) { 91 return ast_type_traits::DynTypedNode(); 92 } 93 return It->second; 94 } 95 96 /// \brief Imposes an order on BoundNodesMaps. 97 bool operator<(const BoundNodesMap &Other) const { 98 return NodeMap < Other.NodeMap; 99 } 100 101private: 102 /// \brief A map from IDs to the bound nodes. 103 /// 104 /// Note that we're using std::map here, as for memoization: 105 /// - we need a comparison operator 106 /// - we need an assignment operator 107 typedef std::map<std::string, ast_type_traits::DynTypedNode> IDToNodeMap; 108 109 IDToNodeMap NodeMap; 110}; 111 112/// \brief Creates BoundNodesTree objects. 113/// 114/// The tree builder is used during the matching process to insert the bound 115/// nodes from the Id matcher. 116class BoundNodesTreeBuilder { 117public: 118 /// \brief A visitor interface to visit all BoundNodes results for a 119 /// BoundNodesTree. 120 class Visitor { 121 public: 122 virtual ~Visitor() {} 123 124 /// \brief Called multiple times during a single call to VisitMatches(...). 125 /// 126 /// 'BoundNodesView' contains the bound nodes for a single match. 127 virtual void visitMatch(const BoundNodes& BoundNodesView) = 0; 128 }; 129 130 /// \brief Add a binding from an id to a node. 131 template <typename T> void setBinding(const std::string &Id, const T *Node) { 132 if (Bindings.empty()) 133 Bindings.push_back(BoundNodesMap()); 134 for (unsigned i = 0, e = Bindings.size(); i != e; ++i) 135 Bindings[i].addNode(Id, Node); 136 } 137 138 /// \brief Adds a branch in the tree. 139 void addMatch(const BoundNodesTreeBuilder &Bindings); 140 141 /// \brief Visits all matches that this BoundNodesTree represents. 142 /// 143 /// The ownership of 'ResultVisitor' remains at the caller. 144 void visitMatches(Visitor* ResultVisitor); 145 146 template <typename ExcludePredicate> 147 bool removeBindings(const ExcludePredicate &Predicate) { 148 Bindings.erase(std::remove_if(Bindings.begin(), Bindings.end(), Predicate), 149 Bindings.end()); 150 return !Bindings.empty(); 151 } 152 153 /// \brief Imposes an order on BoundNodesTreeBuilders. 154 bool operator<(const BoundNodesTreeBuilder &Other) const { 155 return Bindings < Other.Bindings; 156 } 157 158private: 159 SmallVector<BoundNodesMap, 16> Bindings; 160}; 161 162class ASTMatchFinder; 163 164/// \brief Generic interface for matchers on an AST node of type T. 165/// 166/// Implement this if your matcher may need to inspect the children or 167/// descendants of the node or bind matched nodes to names. If you are 168/// writing a simple matcher that only inspects properties of the 169/// current node and doesn't care about its children or descendants, 170/// implement SingleNodeMatcherInterface instead. 171template <typename T> 172class MatcherInterface : public RefCountedBaseVPTR { 173public: 174 virtual ~MatcherInterface() {} 175 176 /// \brief Returns true if 'Node' can be matched. 177 /// 178 /// May bind 'Node' to an ID via 'Builder', or recurse into 179 /// the AST via 'Finder'. 180 virtual bool matches(const T &Node, 181 ASTMatchFinder *Finder, 182 BoundNodesTreeBuilder *Builder) const = 0; 183}; 184 185/// \brief Interface for matchers that only evaluate properties on a single 186/// node. 187template <typename T> 188class SingleNodeMatcherInterface : public MatcherInterface<T> { 189public: 190 /// \brief Returns true if the matcher matches the provided node. 191 /// 192 /// A subclass must implement this instead of Matches(). 193 virtual bool matchesNode(const T &Node) const = 0; 194 195private: 196 /// Implements MatcherInterface::Matches. 197 virtual bool matches(const T &Node, 198 ASTMatchFinder * /* Finder */, 199 BoundNodesTreeBuilder * /* Builder */) const { 200 return matchesNode(Node); 201 } 202}; 203 204/// \brief Wrapper of a MatcherInterface<T> *that allows copying. 205/// 206/// A Matcher<Base> can be used anywhere a Matcher<Derived> is 207/// required. This establishes an is-a relationship which is reverse 208/// to the AST hierarchy. In other words, Matcher<T> is contravariant 209/// with respect to T. The relationship is built via a type conversion 210/// operator rather than a type hierarchy to be able to templatize the 211/// type hierarchy instead of spelling it out. 212template <typename T> 213class Matcher { 214public: 215 /// \brief Takes ownership of the provided implementation pointer. 216 explicit Matcher(MatcherInterface<T> *Implementation) 217 : Implementation(Implementation) {} 218 219 /// \brief Implicitly converts \c Other to a Matcher<T>. 220 /// 221 /// Requires \c T to be derived from \c From. 222 template <typename From> 223 Matcher(const Matcher<From> &Other, 224 typename llvm::enable_if_c< 225 llvm::is_base_of<From, T>::value && 226 !llvm::is_same<From, T>::value >::type* = 0) 227 : Implementation(new ImplicitCastMatcher<From>(Other)) {} 228 229 /// \brief Implicitly converts \c Matcher<Type> to \c Matcher<QualType>. 230 /// 231 /// The resulting matcher is not strict, i.e. ignores qualifiers. 232 template <typename TypeT> 233 Matcher(const Matcher<TypeT> &Other, 234 typename llvm::enable_if_c< 235 llvm::is_same<T, QualType>::value && 236 llvm::is_same<TypeT, Type>::value >::type* = 0) 237 : Implementation(new TypeToQualType<TypeT>(Other)) {} 238 239 /// \brief Forwards the call to the underlying MatcherInterface<T> pointer. 240 bool matches(const T &Node, 241 ASTMatchFinder *Finder, 242 BoundNodesTreeBuilder *Builder) const { 243 if (Implementation->matches(Node, Finder, Builder)) 244 return true; 245 // Delete all bindings when a matcher does not match. 246 // This prevents unexpected exposure of bound nodes in unmatches 247 // branches of the match tree. 248 *Builder = BoundNodesTreeBuilder(); 249 return false; 250 } 251 252 /// \brief Returns an ID that uniquely identifies the matcher. 253 uint64_t getID() const { 254 /// FIXME: Document the requirements this imposes on matcher 255 /// implementations (no new() implementation_ during a Matches()). 256 return reinterpret_cast<uint64_t>(Implementation.getPtr()); 257 } 258 259 /// \brief Allows the conversion of a \c Matcher<Type> to a \c 260 /// Matcher<QualType>. 261 /// 262 /// Depending on the constructor argument, the matcher is either strict, i.e. 263 /// does only matches in the absence of qualifiers, or not, i.e. simply 264 /// ignores any qualifiers. 265 template <typename TypeT> 266 class TypeToQualType : public MatcherInterface<QualType> { 267 public: 268 TypeToQualType(const Matcher<TypeT> &InnerMatcher) 269 : InnerMatcher(InnerMatcher) {} 270 271 virtual bool matches(const QualType &Node, 272 ASTMatchFinder *Finder, 273 BoundNodesTreeBuilder *Builder) const { 274 if (Node.isNull()) 275 return false; 276 return InnerMatcher.matches(*Node, Finder, Builder); 277 } 278 private: 279 const Matcher<TypeT> InnerMatcher; 280 }; 281 282private: 283 /// \brief Allows conversion from Matcher<Base> to Matcher<T> if T 284 /// is derived from Base. 285 template <typename Base> 286 class ImplicitCastMatcher : public MatcherInterface<T> { 287 public: 288 explicit ImplicitCastMatcher(const Matcher<Base> &From) 289 : From(From) {} 290 291 virtual bool matches(const T &Node, 292 ASTMatchFinder *Finder, 293 BoundNodesTreeBuilder *Builder) const { 294 return From.matches(Node, Finder, Builder); 295 } 296 297 private: 298 const Matcher<Base> From; 299 }; 300 301 IntrusiveRefCntPtr< MatcherInterface<T> > Implementation; 302}; // class Matcher 303 304/// \brief A convenient helper for creating a Matcher<T> without specifying 305/// the template type argument. 306template <typename T> 307inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) { 308 return Matcher<T>(Implementation); 309} 310 311template <typename T> class BindableMatcher; 312 313/// \brief Matcher that works on a \c DynTypedNode. 314/// 315/// It is constructed from a \c Matcher<T> object and redirects most calls to 316/// underlying matcher. 317/// It checks whether the \c DynTypedNode is convertible into the type of the 318/// underlying matcher and then do the actual match on the actual node, or 319/// return false if it is not convertible. 320class DynTypedMatcher { 321public: 322 /// \brief Construct from a \c Matcher<T>. Copies the matcher. 323 template <typename T> inline DynTypedMatcher(const Matcher<T> &M); 324 325 /// \brief Construct from a bindable \c Matcher<T>. Copies the matcher. 326 /// 327 /// This version enables \c tryBind() on the \c DynTypedMatcher. 328 template <typename T> inline DynTypedMatcher(const BindableMatcher<T> &M); 329 330 /// \brief Returns true if the matcher matches the given \c DynNode. 331 bool matches(const ast_type_traits::DynTypedNode DynNode, 332 ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const { 333 return Storage->matches(DynNode, Finder, Builder); 334 } 335 336 /// \brief Bind the specified \p ID to the matcher. 337 /// \return A new matcher with the \p ID bound to it if this matcher supports 338 /// binding. Otherwise, returns an empty \c Optional<>. 339 llvm::Optional<DynTypedMatcher> tryBind(StringRef ID) const { 340 return Storage->tryBind(ID); 341 } 342 343 /// \brief Returns a unique \p ID for the matcher. 344 uint64_t getID() const { return Storage->getID(); } 345 346 /// \brief Returns the type this matcher works on. 347 /// 348 /// \c matches() will always return false unless the node passed is of this 349 /// or a derived type. 350 ast_type_traits::ASTNodeKind getSupportedKind() const { 351 return Storage->getSupportedKind(); 352 } 353 354 /// \brief Returns \c true if the passed \c DynTypedMatcher can be converted 355 /// to a \c Matcher<T>. 356 /// 357 /// This method verifies that the underlying matcher in \c Other can process 358 /// nodes of types T. 359 template <typename T> bool canConvertTo() const { 360 return getSupportedKind().isBaseOf( 361 ast_type_traits::ASTNodeKind::getFromNodeKind<T>()); 362 } 363 364 /// \brief Construct a \c Matcher<T> interface around the dynamic matcher. 365 /// 366 /// This method asserts that \c canConvertTo() is \c true. Callers 367 /// should call \c canConvertTo() first to make sure that \c this is 368 /// compatible with T. 369 template <typename T> Matcher<T> convertTo() const { 370 assert(canConvertTo<T>()); 371 return unconditionalConvertTo<T>(); 372 } 373 374 /// \brief Same as \c convertTo(), but does not check that the underlying 375 /// matcher can handle a value of T. 376 /// 377 /// If it is not compatible, then this matcher will never match anything. 378 template <typename T> Matcher<T> unconditionalConvertTo() const { 379 return Matcher<T>(new WrappedMatcher<T>(*this)); 380 } 381 382private: 383 class MatcherStorage : public RefCountedBaseVPTR { 384 public: 385 MatcherStorage(ast_type_traits::ASTNodeKind SupportedKind, uint64_t ID) 386 : SupportedKind(SupportedKind), ID(ID) {} 387 virtual ~MatcherStorage(); 388 389 virtual bool matches(const ast_type_traits::DynTypedNode DynNode, 390 ASTMatchFinder *Finder, 391 BoundNodesTreeBuilder *Builder) const = 0; 392 393 virtual llvm::Optional<DynTypedMatcher> tryBind(StringRef ID) const = 0; 394 395 ast_type_traits::ASTNodeKind getSupportedKind() const { 396 return SupportedKind; 397 } 398 399 uint64_t getID() const { return ID; } 400 401 private: 402 const ast_type_traits::ASTNodeKind SupportedKind; 403 const uint64_t ID; 404 }; 405 406 /// \brief Typed implementation of \c MatcherStorage. 407 template <typename T> class TypedMatcherStorage; 408 409 /// \brief Simple MatcherInterface<T> wrapper around a DynTypedMatcher. 410 template <typename T> class WrappedMatcher; 411 412 IntrusiveRefCntPtr<const MatcherStorage> Storage; 413}; 414 415template <typename T> 416class DynTypedMatcher::TypedMatcherStorage : public MatcherStorage { 417public: 418 TypedMatcherStorage(const Matcher<T> &Other, bool AllowBind) 419 : MatcherStorage(ast_type_traits::ASTNodeKind::getFromNodeKind<T>(), 420 Other.getID()), 421 InnerMatcher(Other), AllowBind(AllowBind) {} 422 423 bool matches(const ast_type_traits::DynTypedNode DynNode, 424 ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder) const 425 LLVM_OVERRIDE { 426 if (const T *Node = DynNode.get<T>()) { 427 return InnerMatcher.matches(*Node, Finder, Builder); 428 } 429 return false; 430 } 431 432 llvm::Optional<DynTypedMatcher> tryBind(StringRef ID) const LLVM_OVERRIDE { 433 if (!AllowBind) 434 return llvm::Optional<DynTypedMatcher>(); 435 return DynTypedMatcher(BindableMatcher<T>(InnerMatcher).bind(ID)); 436 } 437 438private: 439 const Matcher<T> InnerMatcher; 440 const bool AllowBind; 441}; 442 443template <typename T> 444inline DynTypedMatcher::DynTypedMatcher(const Matcher<T> &M) 445 : Storage(new TypedMatcherStorage<T>(M, false)) {} 446 447template <typename T> 448inline DynTypedMatcher::DynTypedMatcher(const BindableMatcher<T> &M) 449 : Storage(new TypedMatcherStorage<T>(M, true)) {} 450 451template <typename T> 452class DynTypedMatcher::WrappedMatcher : public MatcherInterface<T> { 453public: 454 explicit WrappedMatcher(const DynTypedMatcher &Matcher) : Inner(Matcher) {} 455 virtual ~WrappedMatcher() {} 456 457 bool matches(const T &Node, ASTMatchFinder *Finder, 458 BoundNodesTreeBuilder *Builder) const { 459 return Inner.matches(ast_type_traits::DynTypedNode::create(Node), Finder, 460 Builder); 461 } 462 463private: 464 const DynTypedMatcher Inner; 465}; 466 467/// \brief Specialization of the conversion functions for QualType. 468/// 469/// These specializations provide the Matcher<Type>->Matcher<QualType> 470/// conversion that the static API does. 471template <> inline bool DynTypedMatcher::canConvertTo<QualType>() const { 472 const ast_type_traits::ASTNodeKind SourceKind = getSupportedKind(); 473 return SourceKind.isSame( 474 ast_type_traits::ASTNodeKind::getFromNodeKind<Type>()) || 475 SourceKind.isSame( 476 ast_type_traits::ASTNodeKind::getFromNodeKind<QualType>()); 477} 478 479template <> 480inline Matcher<QualType> DynTypedMatcher::convertTo<QualType>() const { 481 assert(canConvertTo<QualType>()); 482 const ast_type_traits::ASTNodeKind SourceKind = getSupportedKind(); 483 if (SourceKind.isSame( 484 ast_type_traits::ASTNodeKind::getFromNodeKind<Type>())) { 485 // We support implicit conversion from Matcher<Type> to Matcher<QualType> 486 return unconditionalConvertTo<Type>(); 487 } 488 return unconditionalConvertTo<QualType>(); 489} 490 491/// \brief Finds the first node in a range that matches the given matcher. 492template <typename MatcherT, typename IteratorT> 493bool matchesFirstInRange(const MatcherT &Matcher, IteratorT Start, 494 IteratorT End, ASTMatchFinder *Finder, 495 BoundNodesTreeBuilder *Builder) { 496 for (IteratorT I = Start; I != End; ++I) { 497 BoundNodesTreeBuilder Result(*Builder); 498 if (Matcher.matches(*I, Finder, &Result)) { 499 *Builder = Result; 500 return true; 501 } 502 } 503 return false; 504} 505 506/// \brief Finds the first node in a pointer range that matches the given 507/// matcher. 508template <typename MatcherT, typename IteratorT> 509bool matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start, 510 IteratorT End, ASTMatchFinder *Finder, 511 BoundNodesTreeBuilder *Builder) { 512 for (IteratorT I = Start; I != End; ++I) { 513 BoundNodesTreeBuilder Result(*Builder); 514 if (Matcher.matches(**I, Finder, &Result)) { 515 *Builder = Result; 516 return true; 517 } 518 } 519 return false; 520} 521 522/// \brief Metafunction to determine if type T has a member called getDecl. 523template <typename T> struct has_getDecl { 524 struct Default { int getDecl; }; 525 struct Derived : T, Default { }; 526 527 template<typename C, C> struct CheckT; 528 529 // If T::getDecl exists, an ambiguity arises and CheckT will 530 // not be instantiable. This makes f(...) the only available 531 // overload. 532 template<typename C> 533 static char (&f(CheckT<int Default::*, &C::getDecl>*))[1]; 534 template<typename C> static char (&f(...))[2]; 535 536 static bool const value = sizeof(f<Derived>(0)) == 2; 537}; 538 539/// \brief Matches overloaded operators with a specific name. 540/// 541/// The type argument ArgT is not used by this matcher but is used by 542/// PolymorphicMatcherWithParam1 and should be StringRef. 543template <typename T, typename ArgT> 544class HasOverloadedOperatorNameMatcher : public SingleNodeMatcherInterface<T> { 545 TOOLING_COMPILE_ASSERT((llvm::is_same<T, CXXOperatorCallExpr>::value || 546 llvm::is_same<T, CXXMethodDecl>::value), 547 unsupported_class_for_matcher); 548 TOOLING_COMPILE_ASSERT((llvm::is_same<ArgT, StringRef>::value), 549 argument_type_must_be_StringRef); 550public: 551 explicit HasOverloadedOperatorNameMatcher(const StringRef Name) 552 : SingleNodeMatcherInterface<T>(), Name(Name) {} 553 554 virtual bool matchesNode(const T &Node) const LLVM_OVERRIDE { 555 return matchesSpecialized(Node); 556 } 557 558private: 559 560 /// \brief CXXOperatorCallExpr exist only for calls to overloaded operators 561 /// so this function returns true if the call is to an operator of the given 562 /// name. 563 bool matchesSpecialized(const CXXOperatorCallExpr &Node) const { 564 return getOperatorSpelling(Node.getOperator()) == Name; 565 } 566 567 /// \brief Returns true only if CXXMethodDecl represents an overloaded 568 /// operator and has the given operator name. 569 bool matchesSpecialized(const CXXMethodDecl &Node) const { 570 return Node.isOverloadedOperator() && 571 getOperatorSpelling(Node.getOverloadedOperator()) == Name; 572 } 573 574 std::string Name; 575}; 576 577/// \brief Matches declarations for QualType and CallExpr. 578/// 579/// Type argument DeclMatcherT is required by PolymorphicMatcherWithParam1 but 580/// not actually used. 581template <typename T, typename DeclMatcherT> 582class HasDeclarationMatcher : public MatcherInterface<T> { 583 TOOLING_COMPILE_ASSERT((llvm::is_same< DeclMatcherT, 584 Matcher<Decl> >::value), 585 instantiated_with_wrong_types); 586public: 587 explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher) 588 : InnerMatcher(InnerMatcher) {} 589 590 virtual bool matches(const T &Node, 591 ASTMatchFinder *Finder, 592 BoundNodesTreeBuilder *Builder) const { 593 return matchesSpecialized(Node, Finder, Builder); 594 } 595 596private: 597 /// \brief If getDecl exists as a member of U, returns whether the inner 598 /// matcher matches Node.getDecl(). 599 template <typename U> 600 bool matchesSpecialized( 601 const U &Node, ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder, 602 typename llvm::enable_if<has_getDecl<U>, int>::type = 0) const { 603 return matchesDecl(Node.getDecl(), Finder, Builder); 604 } 605 606 /// \brief Extracts the CXXRecordDecl or EnumDecl of a QualType and returns 607 /// whether the inner matcher matches on it. 608 bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder, 609 BoundNodesTreeBuilder *Builder) const { 610 /// FIXME: Add other ways to convert... 611 if (Node.isNull()) 612 return false; 613 if (const EnumType *AsEnum = dyn_cast<EnumType>(Node.getTypePtr())) 614 return matchesDecl(AsEnum->getDecl(), Finder, Builder); 615 return matchesDecl(Node->getAsCXXRecordDecl(), Finder, Builder); 616 } 617 618 /// \brief Gets the TemplateDecl from a TemplateSpecializationType 619 /// and returns whether the inner matches on it. 620 bool matchesSpecialized(const TemplateSpecializationType &Node, 621 ASTMatchFinder *Finder, 622 BoundNodesTreeBuilder *Builder) const { 623 return matchesDecl(Node.getTemplateName().getAsTemplateDecl(), 624 Finder, Builder); 625 } 626 627 /// \brief Extracts the Decl of the callee of a CallExpr and returns whether 628 /// the inner matcher matches on it. 629 bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder, 630 BoundNodesTreeBuilder *Builder) const { 631 return matchesDecl(Node.getCalleeDecl(), Finder, Builder); 632 } 633 634 /// \brief Extracts the Decl of the constructor call and returns whether the 635 /// inner matcher matches on it. 636 bool matchesSpecialized(const CXXConstructExpr &Node, 637 ASTMatchFinder *Finder, 638 BoundNodesTreeBuilder *Builder) const { 639 return matchesDecl(Node.getConstructor(), Finder, Builder); 640 } 641 642 /// \brief Extracts the \c ValueDecl a \c MemberExpr refers to and returns 643 /// whether the inner matcher matches on it. 644 bool matchesSpecialized(const MemberExpr &Node, 645 ASTMatchFinder *Finder, 646 BoundNodesTreeBuilder *Builder) const { 647 return matchesDecl(Node.getMemberDecl(), Finder, Builder); 648 } 649 650 /// \brief Returns whether the inner matcher \c Node. Returns false if \c Node 651 /// is \c NULL. 652 bool matchesDecl(const Decl *Node, 653 ASTMatchFinder *Finder, 654 BoundNodesTreeBuilder *Builder) const { 655 return Node != NULL && InnerMatcher.matches(*Node, Finder, Builder); 656 } 657 658 const Matcher<Decl> InnerMatcher; 659}; 660 661/// \brief IsBaseType<T>::value is true if T is a "base" type in the AST 662/// node class hierarchies. 663template <typename T> 664struct IsBaseType { 665 static const bool value = 666 (llvm::is_same<T, Decl>::value || 667 llvm::is_same<T, Stmt>::value || 668 llvm::is_same<T, QualType>::value || 669 llvm::is_same<T, Type>::value || 670 llvm::is_same<T, TypeLoc>::value || 671 llvm::is_same<T, NestedNameSpecifier>::value || 672 llvm::is_same<T, NestedNameSpecifierLoc>::value || 673 llvm::is_same<T, CXXCtorInitializer>::value); 674}; 675template <typename T> 676const bool IsBaseType<T>::value; 677 678/// \brief Interface that allows matchers to traverse the AST. 679/// FIXME: Find a better name. 680/// 681/// This provides three entry methods for each base node type in the AST: 682/// - \c matchesChildOf: 683/// Matches a matcher on every child node of the given node. Returns true 684/// if at least one child node could be matched. 685/// - \c matchesDescendantOf: 686/// Matches a matcher on all descendant nodes of the given node. Returns true 687/// if at least one descendant matched. 688/// - \c matchesAncestorOf: 689/// Matches a matcher on all ancestors of the given node. Returns true if 690/// at least one ancestor matched. 691/// 692/// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal. 693/// In the future, we wan to implement this for all nodes for which it makes 694/// sense. In the case of matchesAncestorOf, we'll want to implement it for 695/// all nodes, as all nodes have ancestors. 696class ASTMatchFinder { 697public: 698 /// \brief Defines how we descend a level in the AST when we pass 699 /// through expressions. 700 enum TraversalKind { 701 /// Will traverse any child nodes. 702 TK_AsIs, 703 /// Will not traverse implicit casts and parentheses. 704 TK_IgnoreImplicitCastsAndParentheses 705 }; 706 707 /// \brief Defines how bindings are processed on recursive matches. 708 enum BindKind { 709 /// Stop at the first match and only bind the first match. 710 BK_First, 711 /// Create results for all combinations of bindings that match. 712 BK_All 713 }; 714 715 /// \brief Defines which ancestors are considered for a match. 716 enum AncestorMatchMode { 717 /// All ancestors. 718 AMM_All, 719 /// Direct parent only. 720 AMM_ParentOnly 721 }; 722 723 virtual ~ASTMatchFinder() {} 724 725 /// \brief Returns true if the given class is directly or indirectly derived 726 /// from a base type matching \c base. 727 /// 728 /// A class is considered to be also derived from itself. 729 virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration, 730 const Matcher<NamedDecl> &Base, 731 BoundNodesTreeBuilder *Builder) = 0; 732 733 template <typename T> 734 bool matchesChildOf(const T &Node, 735 const DynTypedMatcher &Matcher, 736 BoundNodesTreeBuilder *Builder, 737 TraversalKind Traverse, 738 BindKind Bind) { 739 TOOLING_COMPILE_ASSERT( 740 (llvm::is_base_of<Decl, T>::value || 741 llvm::is_base_of<Stmt, T>::value || 742 llvm::is_base_of<NestedNameSpecifier, T>::value || 743 llvm::is_base_of<NestedNameSpecifierLoc, T>::value || 744 llvm::is_base_of<TypeLoc, T>::value || 745 llvm::is_base_of<QualType, T>::value), 746 unsupported_type_for_recursive_matching); 747 return matchesChildOf(ast_type_traits::DynTypedNode::create(Node), 748 Matcher, Builder, Traverse, Bind); 749 } 750 751 template <typename T> 752 bool matchesDescendantOf(const T &Node, 753 const DynTypedMatcher &Matcher, 754 BoundNodesTreeBuilder *Builder, 755 BindKind Bind) { 756 TOOLING_COMPILE_ASSERT( 757 (llvm::is_base_of<Decl, T>::value || 758 llvm::is_base_of<Stmt, T>::value || 759 llvm::is_base_of<NestedNameSpecifier, T>::value || 760 llvm::is_base_of<NestedNameSpecifierLoc, T>::value || 761 llvm::is_base_of<TypeLoc, T>::value || 762 llvm::is_base_of<QualType, T>::value), 763 unsupported_type_for_recursive_matching); 764 return matchesDescendantOf(ast_type_traits::DynTypedNode::create(Node), 765 Matcher, Builder, Bind); 766 } 767 768 // FIXME: Implement support for BindKind. 769 template <typename T> 770 bool matchesAncestorOf(const T &Node, 771 const DynTypedMatcher &Matcher, 772 BoundNodesTreeBuilder *Builder, 773 AncestorMatchMode MatchMode) { 774 TOOLING_COMPILE_ASSERT((llvm::is_base_of<Decl, T>::value || 775 llvm::is_base_of<Stmt, T>::value), 776 only_Decl_or_Stmt_allowed_for_recursive_matching); 777 return matchesAncestorOf(ast_type_traits::DynTypedNode::create(Node), 778 Matcher, Builder, MatchMode); 779 } 780 781 virtual ASTContext &getASTContext() const = 0; 782 783protected: 784 virtual bool matchesChildOf(const ast_type_traits::DynTypedNode &Node, 785 const DynTypedMatcher &Matcher, 786 BoundNodesTreeBuilder *Builder, 787 TraversalKind Traverse, 788 BindKind Bind) = 0; 789 790 virtual bool matchesDescendantOf(const ast_type_traits::DynTypedNode &Node, 791 const DynTypedMatcher &Matcher, 792 BoundNodesTreeBuilder *Builder, 793 BindKind Bind) = 0; 794 795 virtual bool matchesAncestorOf(const ast_type_traits::DynTypedNode &Node, 796 const DynTypedMatcher &Matcher, 797 BoundNodesTreeBuilder *Builder, 798 AncestorMatchMode MatchMode) = 0; 799}; 800 801/// \brief A simple type-list implementation. 802/// 803/// It is implemented as a flat struct with a maximum number of arguments to 804/// simplify compiler error messages. 805/// However, it is used as a "linked list" of types. 806/// 807/// Note: If you need to extend for more types, add them as template arguments 808/// and to the "typedef TypeList<...> tail" below. Nothing else is needed. 809template <typename T1 = void, typename T2 = void, typename T3 = void, 810 typename T4 = void, typename T5 = void, typename T6 = void, 811 typename T7 = void, typename T8 = void> 812struct TypeList { 813 /// \brief The first type on the list. 814 typedef T1 head; 815 816 /// \brief A sub list with the tail. ie everything but the head. 817 /// 818 /// This type is used to do recursion. TypeList<>/EmptyTypeList indicates the 819 /// end of the list. 820 typedef TypeList<T2, T3, T4, T5, T6, T7, T8> tail; 821 822 /// \brief Helper meta-function to determine if some type \c T is present or 823 /// a parent type in the list. 824 template <typename T> struct ContainsSuperOf { 825 static const bool value = llvm::is_base_of<head, T>::value || 826 tail::template ContainsSuperOf<T>::value; 827 }; 828}; 829 830/// \brief Specialization of ContainsSuperOf for the empty list. 831template <> template <typename T> struct TypeList<>::ContainsSuperOf { 832 static const bool value = false; 833}; 834 835/// \brief The empty type list. 836typedef TypeList<> EmptyTypeList; 837 838/// \brief A "type list" that contains all types. 839/// 840/// Useful for matchers like \c anything and \c unless. 841typedef TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc, 842 QualType, Type, TypeLoc, CXXCtorInitializer> AllNodeBaseTypes; 843 844/// \brief Helper meta-function to extract the argument out of a function of 845/// type void(Arg). 846/// 847/// See AST_POLYMORPHIC_SUPPORTED_TYPES_* for details. 848template <class T> struct ExtractFunctionArgMeta; 849template <class T> struct ExtractFunctionArgMeta<void(T)> { 850 typedef T type; 851}; 852 853/// \brief Default type lists for ArgumentAdaptingMatcher matchers. 854typedef AllNodeBaseTypes AdaptativeDefaultFromTypes; 855typedef TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc, 856 TypeLoc, QualType> AdaptativeDefaultToTypes; 857 858/// \brief Converts a \c Matcher<T> to a matcher of desired type \c To by 859/// "adapting" a \c To into a \c T. 860/// 861/// The \c ArgumentAdapterT argument specifies how the adaptation is done. 862/// 863/// For example: 864/// \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher); 865/// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher 866/// that is convertible into any matcher of type \c To by constructing 867/// \c HasMatcher<To, T>(InnerMatcher). 868/// 869/// If a matcher does not need knowledge about the inner type, prefer to use 870/// PolymorphicMatcherWithParam1. 871template <template <typename ToArg, typename FromArg> class ArgumentAdapterT, 872 typename FromTypes = AdaptativeDefaultFromTypes, 873 typename ToTypes = AdaptativeDefaultToTypes> 874struct ArgumentAdaptingMatcherFunc { 875 template <typename T> class Adaptor { 876 public: 877 explicit Adaptor(const Matcher<T> &InnerMatcher) 878 : InnerMatcher(InnerMatcher) {} 879 880 typedef ToTypes ReturnTypes; 881 882 template <typename To> operator Matcher<To>() const { 883 return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher)); 884 } 885 886 private: 887 const Matcher<T> InnerMatcher; 888 }; 889 890 template <typename T> 891 static Adaptor<T> create(const Matcher<T> &InnerMatcher) { 892 return Adaptor<T>(InnerMatcher); 893 } 894 895 template <typename T> 896 Adaptor<T> operator()(const Matcher<T> &InnerMatcher) const { 897 return create(InnerMatcher); 898 } 899}; 900 901/// \brief A PolymorphicMatcherWithParamN<MatcherT, P1, ..., PN> object can be 902/// created from N parameters p1, ..., pN (of type P1, ..., PN) and 903/// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN) 904/// can be constructed. 905/// 906/// For example: 907/// - PolymorphicMatcherWithParam0<IsDefinitionMatcher>() 908/// creates an object that can be used as a Matcher<T> for any type T 909/// where an IsDefinitionMatcher<T>() can be constructed. 910/// - PolymorphicMatcherWithParam1<ValueEqualsMatcher, int>(42) 911/// creates an object that can be used as a Matcher<T> for any type T 912/// where a ValueEqualsMatcher<T, int>(42) can be constructed. 913template <template <typename T> class MatcherT, 914 typename ReturnTypesF = void(AllNodeBaseTypes)> 915class PolymorphicMatcherWithParam0 { 916public: 917 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes; 918 template <typename T> 919 operator Matcher<T>() const { 920 TOOLING_COMPILE_ASSERT(ReturnTypes::template ContainsSuperOf<T>::value, 921 right_polymorphic_conversion); 922 return Matcher<T>(new MatcherT<T>()); 923 } 924}; 925 926template <template <typename T, typename P1> class MatcherT, 927 typename P1, 928 typename ReturnTypesF = void(AllNodeBaseTypes)> 929class PolymorphicMatcherWithParam1 { 930public: 931 explicit PolymorphicMatcherWithParam1(const P1 &Param1) 932 : Param1(Param1) {} 933 934 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes; 935 936 template <typename T> 937 operator Matcher<T>() const { 938 TOOLING_COMPILE_ASSERT(ReturnTypes::template ContainsSuperOf<T>::value, 939 right_polymorphic_conversion); 940 return Matcher<T>(new MatcherT<T, P1>(Param1)); 941 } 942 943private: 944 const P1 Param1; 945}; 946 947template <template <typename T, typename P1, typename P2> class MatcherT, 948 typename P1, typename P2, 949 typename ReturnTypesF = void(AllNodeBaseTypes)> 950class PolymorphicMatcherWithParam2 { 951public: 952 PolymorphicMatcherWithParam2(const P1 &Param1, const P2 &Param2) 953 : Param1(Param1), Param2(Param2) {} 954 955 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes; 956 957 template <typename T> 958 operator Matcher<T>() const { 959 TOOLING_COMPILE_ASSERT(ReturnTypes::template ContainsSuperOf<T>::value, 960 right_polymorphic_conversion); 961 return Matcher<T>(new MatcherT<T, P1, P2>(Param1, Param2)); 962 } 963 964private: 965 const P1 Param1; 966 const P2 Param2; 967}; 968 969/// \brief Matches any instance of the given NodeType. 970/// 971/// This is useful when a matcher syntactically requires a child matcher, 972/// but the context doesn't care. See for example: anything(). 973/// 974/// FIXME: Alternatively we could also create a IsAMatcher or something 975/// that checks that a dyn_cast is possible. This is purely needed for the 976/// difference between calling for example: 977/// record() 978/// and 979/// record(SomeMatcher) 980/// In the second case we need the correct type we were dyn_cast'ed to in order 981/// to get the right type for the inner matcher. In the first case we don't need 982/// that, but we use the type conversion anyway and insert a TrueMatcher. 983template <typename T> 984class TrueMatcher : public SingleNodeMatcherInterface<T> { 985public: 986 virtual bool matchesNode(const T &Node) const { 987 return true; 988 } 989}; 990 991/// \brief Matcher<T> that wraps an inner Matcher<T> and binds the matched node 992/// to an ID if the inner matcher matches on the node. 993template <typename T> 994class IdMatcher : public MatcherInterface<T> { 995public: 996 /// \brief Creates an IdMatcher that binds to 'ID' if 'InnerMatcher' matches 997 /// the node. 998 IdMatcher(StringRef ID, const Matcher<T> &InnerMatcher) 999 : ID(ID), InnerMatcher(InnerMatcher) {} 1000 1001 virtual bool matches(const T &Node, 1002 ASTMatchFinder *Finder, 1003 BoundNodesTreeBuilder *Builder) const { 1004 bool Result = InnerMatcher.matches(Node, Finder, Builder); 1005 if (Result) { 1006 Builder->setBinding(ID, &Node); 1007 } 1008 return Result; 1009 } 1010 1011private: 1012 const std::string ID; 1013 const Matcher<T> InnerMatcher; 1014}; 1015 1016/// \brief A Matcher that allows binding the node it matches to an id. 1017/// 1018/// BindableMatcher provides a \a bind() method that allows binding the 1019/// matched node to an id if the match was successful. 1020template <typename T> 1021class BindableMatcher : public Matcher<T> { 1022public: 1023 explicit BindableMatcher(const Matcher<T> &M) : Matcher<T>(M) {} 1024 explicit BindableMatcher(MatcherInterface<T> *Implementation) 1025 : Matcher<T>(Implementation) {} 1026 1027 /// \brief Returns a matcher that will bind the matched node on a match. 1028 /// 1029 /// The returned matcher is equivalent to this matcher, but will 1030 /// bind the matched node on a match. 1031 Matcher<T> bind(StringRef ID) const { 1032 return Matcher<T>(new IdMatcher<T>(ID, *this)); 1033 } 1034}; 1035 1036/// \brief Matches nodes of type T that have child nodes of type ChildT for 1037/// which a specified child matcher matches. 1038/// 1039/// ChildT must be an AST base type. 1040template <typename T, typename ChildT> 1041class HasMatcher : public MatcherInterface<T> { 1042 TOOLING_COMPILE_ASSERT(IsBaseType<ChildT>::value, 1043 has_only_accepts_base_type_matcher); 1044public: 1045 explicit HasMatcher(const Matcher<ChildT> &ChildMatcher) 1046 : ChildMatcher(ChildMatcher) {} 1047 1048 virtual bool matches(const T &Node, 1049 ASTMatchFinder *Finder, 1050 BoundNodesTreeBuilder *Builder) const { 1051 return Finder->matchesChildOf( 1052 Node, ChildMatcher, Builder, 1053 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses, 1054 ASTMatchFinder::BK_First); 1055 } 1056 1057 private: 1058 const Matcher<ChildT> ChildMatcher; 1059}; 1060 1061/// \brief Matches nodes of type T that have child nodes of type ChildT for 1062/// which a specified child matcher matches. ChildT must be an AST base 1063/// type. 1064/// As opposed to the HasMatcher, the ForEachMatcher will produce a match 1065/// for each child that matches. 1066template <typename T, typename ChildT> 1067class ForEachMatcher : public MatcherInterface<T> { 1068 TOOLING_COMPILE_ASSERT(IsBaseType<ChildT>::value, 1069 for_each_only_accepts_base_type_matcher); 1070 public: 1071 explicit ForEachMatcher(const Matcher<ChildT> &ChildMatcher) 1072 : ChildMatcher(ChildMatcher) {} 1073 1074 virtual bool matches(const T& Node, 1075 ASTMatchFinder* Finder, 1076 BoundNodesTreeBuilder* Builder) const { 1077 return Finder->matchesChildOf( 1078 Node, ChildMatcher, Builder, 1079 ASTMatchFinder::TK_IgnoreImplicitCastsAndParentheses, 1080 ASTMatchFinder::BK_All); 1081 } 1082 1083private: 1084 const Matcher<ChildT> ChildMatcher; 1085}; 1086 1087/// \brief Matches nodes of type T if the given Matcher<T> does not match. 1088/// 1089/// Type argument MatcherT is required by PolymorphicMatcherWithParam1 1090/// but not actually used. It will always be instantiated with a type 1091/// convertible to Matcher<T>. 1092template <typename T, typename MatcherT> 1093class NotMatcher : public MatcherInterface<T> { 1094public: 1095 explicit NotMatcher(const Matcher<T> &InnerMatcher) 1096 : InnerMatcher(InnerMatcher) {} 1097 1098 virtual bool matches(const T &Node, 1099 ASTMatchFinder *Finder, 1100 BoundNodesTreeBuilder *Builder) const { 1101 // The 'unless' matcher will always discard the result: 1102 // If the inner matcher doesn't match, unless returns true, 1103 // but the inner matcher cannot have bound anything. 1104 // If the inner matcher matches, the result is false, and 1105 // any possible binding will be discarded. 1106 // We still need to hand in all the bound nodes up to this 1107 // point so the inner matcher can depend on bound nodes, 1108 // and we need to actively discard the bound nodes, otherwise 1109 // the inner matcher will reset the bound nodes if it doesn't 1110 // match, but this would be inversed by 'unless'. 1111 BoundNodesTreeBuilder Discard(*Builder); 1112 return !InnerMatcher.matches(Node, Finder, &Discard); 1113 } 1114 1115private: 1116 const Matcher<T> InnerMatcher; 1117}; 1118 1119/// \brief VariadicOperatorMatcher related types. 1120/// @{ 1121 1122/// \brief Function signature for any variadic operator. It takes the inner 1123/// matchers as an array of DynTypedMatcher. 1124typedef bool (*VariadicOperatorFunction)( 1125 const ast_type_traits::DynTypedNode DynNode, ASTMatchFinder *Finder, 1126 BoundNodesTreeBuilder *Builder, ArrayRef<DynTypedMatcher> InnerMatchers); 1127 1128/// \brief \c MatcherInterface<T> implementation for an variadic operator. 1129template <typename T> 1130class VariadicOperatorMatcherInterface : public MatcherInterface<T> { 1131public: 1132 VariadicOperatorMatcherInterface(VariadicOperatorFunction Func, 1133 ArrayRef<const Matcher<T> *> InputMatchers) 1134 : Func(Func) { 1135 for (size_t i = 0, e = InputMatchers.size(); i != e; ++i) { 1136 InnerMatchers.push_back(*InputMatchers[i]); 1137 } 1138 } 1139 1140 virtual bool matches(const T &Node, ASTMatchFinder *Finder, 1141 BoundNodesTreeBuilder *Builder) const { 1142 return Func(ast_type_traits::DynTypedNode::create(Node), Finder, Builder, 1143 InnerMatchers); 1144 } 1145 1146private: 1147 const VariadicOperatorFunction Func; 1148 std::vector<DynTypedMatcher> InnerMatchers; 1149}; 1150 1151/// \brief "No argument" placeholder to use as template paratemers. 1152struct VariadicOperatorNoArg {}; 1153 1154/// \brief Polymorphic matcher object that uses a \c VariadicOperatorFunction 1155/// operator. 1156/// 1157/// Input matchers can have any type (including other polymorphic matcher 1158/// types), and the actual Matcher<T> is generated on demand with an implicit 1159/// coversion operator. 1160template <typename P1, typename P2, 1161 typename P3 = VariadicOperatorNoArg, 1162 typename P4 = VariadicOperatorNoArg, 1163 typename P5 = VariadicOperatorNoArg> 1164class VariadicOperatorMatcher { 1165public: 1166 VariadicOperatorMatcher(VariadicOperatorFunction Func, const P1 &Param1, 1167 const P2 &Param2, 1168 const P3 &Param3 = VariadicOperatorNoArg(), 1169 const P4 &Param4 = VariadicOperatorNoArg(), 1170 const P5 &Param5 = VariadicOperatorNoArg()) 1171 : Func(Func), Param1(Param1), Param2(Param2), Param3(Param3), 1172 Param4(Param4), Param5(Param5) {} 1173 1174 template <typename T> operator Matcher<T>() const { 1175 Matcher<T> *Array[5]; 1176 size_t Size = 0; 1177 1178 addMatcher<T>(Param1, Array, Size); 1179 addMatcher<T>(Param2, Array, Size); 1180 addMatcher<T>(Param3, Array, Size); 1181 addMatcher<T>(Param4, Array, Size); 1182 addMatcher<T>(Param5, Array, Size); 1183 Matcher<T> Result(new VariadicOperatorMatcherInterface<T>( 1184 Func, ArrayRef<const Matcher<T> *>(Array, Size))); 1185 for (size_t i = 0, e = Size; i != e; ++i) delete Array[i]; 1186 return Result; 1187 } 1188 1189private: 1190 template <typename T> 1191 static void addMatcher(const Matcher<T> &M, Matcher<T> **Array, 1192 size_t &Size) { 1193 Array[Size++] = new Matcher<T>(M); 1194 } 1195 1196 /// \brief Overload to ignore \c VariadicOperatorNoArg arguments. 1197 template <typename T> 1198 static void addMatcher(VariadicOperatorNoArg, Matcher<T> **Array, 1199 size_t &Size) {} 1200 1201 const VariadicOperatorFunction Func; 1202 const P1 Param1; 1203 const P2 Param2; 1204 const P3 Param3; 1205 const P4 Param4; 1206 const P5 Param5; 1207}; 1208 1209/// \brief Overloaded function object to generate VariadicOperatorMatcher 1210/// objects from arbitrary matchers. 1211/// 1212/// It supports 2-5 argument overloaded operator(). More can be added if needed. 1213struct VariadicOperatorMatcherFunc { 1214 VariadicOperatorFunction Func; 1215 1216 template <typename M1, typename M2> 1217 VariadicOperatorMatcher<M1, M2> operator()(const M1 &P1, const M2 &P2) const { 1218 return VariadicOperatorMatcher<M1, M2>(Func, P1, P2); 1219 } 1220 template <typename M1, typename M2, typename M3> 1221 VariadicOperatorMatcher<M1, M2, M3> operator()(const M1 &P1, const M2 &P2, 1222 const M3 &P3) const { 1223 return VariadicOperatorMatcher<M1, M2, M3>(Func, P1, P2, P3); 1224 } 1225 template <typename M1, typename M2, typename M3, typename M4> 1226 VariadicOperatorMatcher<M1, M2, M3, M4> 1227 operator()(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4) const { 1228 return VariadicOperatorMatcher<M1, M2, M3, M4>(Func, P1, P2, P3, P4); 1229 } 1230 template <typename M1, typename M2, typename M3, typename M4, typename M5> 1231 VariadicOperatorMatcher<M1, M2, M3, M4, M5> 1232 operator()(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4, 1233 const M5 &P5) const { 1234 return VariadicOperatorMatcher<M1, M2, M3, M4, M5>(Func, P1, P2, P3, P4, 1235 P5); 1236 } 1237}; 1238 1239/// @} 1240 1241/// \brief Matches nodes for which all provided matchers match. 1242bool AllOfVariadicOperator(const ast_type_traits::DynTypedNode DynNode, 1243 ASTMatchFinder *Finder, 1244 BoundNodesTreeBuilder *Builder, 1245 ArrayRef<DynTypedMatcher> InnerMatchers); 1246 1247/// \brief Matches nodes for which at least one of the provided matchers 1248/// matches, but doesn't stop at the first match. 1249bool EachOfVariadicOperator(const ast_type_traits::DynTypedNode DynNode, 1250 ASTMatchFinder *Finder, 1251 BoundNodesTreeBuilder *Builder, 1252 ArrayRef<DynTypedMatcher> InnerMatchers); 1253 1254/// \brief Matches nodes for which at least one of the provided matchers 1255/// matches. 1256bool AnyOfVariadicOperator(const ast_type_traits::DynTypedNode DynNode, 1257 ASTMatchFinder *Finder, 1258 BoundNodesTreeBuilder *Builder, 1259 ArrayRef<DynTypedMatcher> InnerMatchers); 1260 1261/// \brief Creates a Matcher<T> that matches if all inner matchers match. 1262template<typename T> 1263BindableMatcher<T> makeAllOfComposite( 1264 ArrayRef<const Matcher<T> *> InnerMatchers) { 1265 return BindableMatcher<T>(new VariadicOperatorMatcherInterface<T>( 1266 AllOfVariadicOperator, InnerMatchers)); 1267} 1268 1269/// \brief Creates a Matcher<T> that matches if 1270/// T is dyn_cast'able into InnerT and all inner matchers match. 1271/// 1272/// Returns BindableMatcher, as matchers that use dyn_cast have 1273/// the same object both to match on and to run submatchers on, 1274/// so there is no ambiguity with what gets bound. 1275template<typename T, typename InnerT> 1276BindableMatcher<T> makeDynCastAllOfComposite( 1277 ArrayRef<const Matcher<InnerT> *> InnerMatchers) { 1278 return BindableMatcher<T>(DynTypedMatcher(makeAllOfComposite(InnerMatchers)) 1279 .unconditionalConvertTo<T>()); 1280} 1281 1282/// \brief Matches nodes of type T that have at least one descendant node of 1283/// type DescendantT for which the given inner matcher matches. 1284/// 1285/// DescendantT must be an AST base type. 1286template <typename T, typename DescendantT> 1287class HasDescendantMatcher : public MatcherInterface<T> { 1288 TOOLING_COMPILE_ASSERT(IsBaseType<DescendantT>::value, 1289 has_descendant_only_accepts_base_type_matcher); 1290public: 1291 explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher) 1292 : DescendantMatcher(DescendantMatcher) {} 1293 1294 virtual bool matches(const T &Node, 1295 ASTMatchFinder *Finder, 1296 BoundNodesTreeBuilder *Builder) const { 1297 return Finder->matchesDescendantOf( 1298 Node, DescendantMatcher, Builder, ASTMatchFinder::BK_First); 1299 } 1300 1301 private: 1302 const Matcher<DescendantT> DescendantMatcher; 1303}; 1304 1305/// \brief Matches nodes of type \c T that have a parent node of type \c ParentT 1306/// for which the given inner matcher matches. 1307/// 1308/// \c ParentT must be an AST base type. 1309template <typename T, typename ParentT> 1310class HasParentMatcher : public MatcherInterface<T> { 1311 TOOLING_COMPILE_ASSERT(IsBaseType<ParentT>::value, 1312 has_parent_only_accepts_base_type_matcher); 1313public: 1314 explicit HasParentMatcher(const Matcher<ParentT> &ParentMatcher) 1315 : ParentMatcher(ParentMatcher) {} 1316 1317 virtual bool matches(const T &Node, 1318 ASTMatchFinder *Finder, 1319 BoundNodesTreeBuilder *Builder) const { 1320 return Finder->matchesAncestorOf( 1321 Node, ParentMatcher, Builder, ASTMatchFinder::AMM_ParentOnly); 1322 } 1323 1324 private: 1325 const Matcher<ParentT> ParentMatcher; 1326}; 1327 1328/// \brief Matches nodes of type \c T that have at least one ancestor node of 1329/// type \c AncestorT for which the given inner matcher matches. 1330/// 1331/// \c AncestorT must be an AST base type. 1332template <typename T, typename AncestorT> 1333class HasAncestorMatcher : public MatcherInterface<T> { 1334 TOOLING_COMPILE_ASSERT(IsBaseType<AncestorT>::value, 1335 has_ancestor_only_accepts_base_type_matcher); 1336public: 1337 explicit HasAncestorMatcher(const Matcher<AncestorT> &AncestorMatcher) 1338 : AncestorMatcher(AncestorMatcher) {} 1339 1340 virtual bool matches(const T &Node, 1341 ASTMatchFinder *Finder, 1342 BoundNodesTreeBuilder *Builder) const { 1343 return Finder->matchesAncestorOf( 1344 Node, AncestorMatcher, Builder, ASTMatchFinder::AMM_All); 1345 } 1346 1347 private: 1348 const Matcher<AncestorT> AncestorMatcher; 1349}; 1350 1351/// \brief Matches nodes of type T that have at least one descendant node of 1352/// type DescendantT for which the given inner matcher matches. 1353/// 1354/// DescendantT must be an AST base type. 1355/// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match 1356/// for each descendant node that matches instead of only for the first. 1357template <typename T, typename DescendantT> 1358class ForEachDescendantMatcher : public MatcherInterface<T> { 1359 TOOLING_COMPILE_ASSERT(IsBaseType<DescendantT>::value, 1360 for_each_descendant_only_accepts_base_type_matcher); 1361 public: 1362 explicit ForEachDescendantMatcher( 1363 const Matcher<DescendantT>& DescendantMatcher) 1364 : DescendantMatcher(DescendantMatcher) {} 1365 1366 virtual bool matches(const T& Node, 1367 ASTMatchFinder* Finder, 1368 BoundNodesTreeBuilder* Builder) const { 1369 return Finder->matchesDescendantOf(Node, DescendantMatcher, Builder, 1370 ASTMatchFinder::BK_All); 1371 } 1372 1373private: 1374 const Matcher<DescendantT> DescendantMatcher; 1375}; 1376 1377/// \brief Matches on nodes that have a getValue() method if getValue() equals 1378/// the value the ValueEqualsMatcher was constructed with. 1379template <typename T, typename ValueT> 1380class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> { 1381 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CharacterLiteral, T>::value || 1382 llvm::is_base_of<CXXBoolLiteralExpr, 1383 T>::value || 1384 llvm::is_base_of<FloatingLiteral, T>::value || 1385 llvm::is_base_of<IntegerLiteral, T>::value), 1386 the_node_must_have_a_getValue_method); 1387public: 1388 explicit ValueEqualsMatcher(const ValueT &ExpectedValue) 1389 : ExpectedValue(ExpectedValue) {} 1390 1391 virtual bool matchesNode(const T &Node) const { 1392 return Node.getValue() == ExpectedValue; 1393 } 1394 1395private: 1396 const ValueT ExpectedValue; 1397}; 1398 1399/// \brief A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a 1400/// variadic functor that takes a number of Matcher<TargetT> and returns a 1401/// Matcher<SourceT> that matches TargetT nodes that are matched by all of the 1402/// given matchers, if SourceT can be dynamically casted into TargetT. 1403/// 1404/// For example: 1405/// const VariadicDynCastAllOfMatcher< 1406/// Decl, CXXRecordDecl> record; 1407/// Creates a functor record(...) that creates a Matcher<Decl> given 1408/// a variable number of arguments of type Matcher<CXXRecordDecl>. 1409/// The returned matcher matches if the given Decl can by dynamically 1410/// casted to CXXRecordDecl and all given matchers match. 1411template <typename SourceT, typename TargetT> 1412class VariadicDynCastAllOfMatcher 1413 : public llvm::VariadicFunction< 1414 BindableMatcher<SourceT>, Matcher<TargetT>, 1415 makeDynCastAllOfComposite<SourceT, TargetT> > { 1416public: 1417 VariadicDynCastAllOfMatcher() {} 1418}; 1419 1420/// \brief A \c VariadicAllOfMatcher<T> object is a variadic functor that takes 1421/// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T 1422/// nodes that are matched by all of the given matchers. 1423/// 1424/// For example: 1425/// const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier; 1426/// Creates a functor nestedNameSpecifier(...) that creates a 1427/// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type 1428/// \c Matcher<NestedNameSpecifier>. 1429/// The returned matcher matches if all given matchers match. 1430template <typename T> 1431class VariadicAllOfMatcher : public llvm::VariadicFunction< 1432 BindableMatcher<T>, Matcher<T>, 1433 makeAllOfComposite<T> > { 1434public: 1435 VariadicAllOfMatcher() {} 1436}; 1437 1438/// \brief Matches nodes of type \c TLoc for which the inner 1439/// \c Matcher<T> matches. 1440template <typename TLoc, typename T> 1441class LocMatcher : public MatcherInterface<TLoc> { 1442public: 1443 explicit LocMatcher(const Matcher<T> &InnerMatcher) 1444 : InnerMatcher(InnerMatcher) {} 1445 1446 virtual bool matches(const TLoc &Node, 1447 ASTMatchFinder *Finder, 1448 BoundNodesTreeBuilder *Builder) const { 1449 if (!Node) 1450 return false; 1451 return InnerMatcher.matches(*extract(Node), Finder, Builder); 1452 } 1453 1454private: 1455 const NestedNameSpecifier *extract(const NestedNameSpecifierLoc &Loc) const { 1456 return Loc.getNestedNameSpecifier(); 1457 } 1458 1459 const Matcher<T> InnerMatcher; 1460}; 1461 1462/// \brief Matches \c TypeLocs based on an inner matcher matching a certain 1463/// \c QualType. 1464/// 1465/// Used to implement the \c loc() matcher. 1466class TypeLocTypeMatcher : public MatcherInterface<TypeLoc> { 1467public: 1468 explicit TypeLocTypeMatcher(const Matcher<QualType> &InnerMatcher) 1469 : InnerMatcher(InnerMatcher) {} 1470 1471 virtual bool matches(const TypeLoc &Node, 1472 ASTMatchFinder *Finder, 1473 BoundNodesTreeBuilder *Builder) const { 1474 if (!Node) 1475 return false; 1476 return InnerMatcher.matches(Node.getType(), Finder, Builder); 1477 } 1478 1479private: 1480 const Matcher<QualType> InnerMatcher; 1481}; 1482 1483/// \brief Matches nodes of type \c T for which the inner matcher matches on a 1484/// another node of type \c T that can be reached using a given traverse 1485/// function. 1486template <typename T> 1487class TypeTraverseMatcher : public MatcherInterface<T> { 1488public: 1489 explicit TypeTraverseMatcher(const Matcher<QualType> &InnerMatcher, 1490 QualType (T::*TraverseFunction)() const) 1491 : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {} 1492 1493 virtual bool matches(const T &Node, 1494 ASTMatchFinder *Finder, 1495 BoundNodesTreeBuilder *Builder) const { 1496 QualType NextNode = (Node.*TraverseFunction)(); 1497 if (NextNode.isNull()) 1498 return false; 1499 return InnerMatcher.matches(NextNode, Finder, Builder); 1500 } 1501 1502private: 1503 const Matcher<QualType> InnerMatcher; 1504 QualType (T::*TraverseFunction)() const; 1505}; 1506 1507/// \brief Matches nodes of type \c T in a ..Loc hierarchy, for which the inner 1508/// matcher matches on a another node of type \c T that can be reached using a 1509/// given traverse function. 1510template <typename T> 1511class TypeLocTraverseMatcher : public MatcherInterface<T> { 1512public: 1513 explicit TypeLocTraverseMatcher(const Matcher<TypeLoc> &InnerMatcher, 1514 TypeLoc (T::*TraverseFunction)() const) 1515 : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {} 1516 1517 virtual bool matches(const T &Node, 1518 ASTMatchFinder *Finder, 1519 BoundNodesTreeBuilder *Builder) const { 1520 TypeLoc NextNode = (Node.*TraverseFunction)(); 1521 if (!NextNode) 1522 return false; 1523 return InnerMatcher.matches(NextNode, Finder, Builder); 1524 } 1525 1526private: 1527 const Matcher<TypeLoc> InnerMatcher; 1528 TypeLoc (T::*TraverseFunction)() const; 1529}; 1530 1531/// \brief Converts a \c Matcher<InnerT> to a \c Matcher<OuterT>, where 1532/// \c OuterT is any type that is supported by \c Getter. 1533/// 1534/// \code Getter<OuterT>::value() \endcode returns a 1535/// \code InnerTBase (OuterT::*)() \endcode, which is used to adapt a \c OuterT 1536/// object into a \c InnerT 1537template <typename InnerTBase, 1538 template <typename OuterT> class Getter, 1539 template <typename OuterT> class MatcherImpl, 1540 typename ReturnTypesF> 1541class TypeTraversePolymorphicMatcher { 1542private: 1543 typedef TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl, 1544 ReturnTypesF> Self; 1545 static Self create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers); 1546 1547public: 1548 typedef typename ExtractFunctionArgMeta<ReturnTypesF>::type ReturnTypes; 1549 1550 explicit TypeTraversePolymorphicMatcher( 1551 ArrayRef<const Matcher<InnerTBase> *> InnerMatchers) 1552 : InnerMatcher(makeAllOfComposite(InnerMatchers)) {} 1553 1554 template <typename OuterT> operator Matcher<OuterT>() const { 1555 return Matcher<OuterT>( 1556 new MatcherImpl<OuterT>(InnerMatcher, Getter<OuterT>::value())); 1557 } 1558 1559 struct Func : public llvm::VariadicFunction<Self, Matcher<InnerTBase>, 1560 &Self::create> { 1561 Func() {} 1562 }; 1563 1564private: 1565 const Matcher<InnerTBase> InnerMatcher; 1566}; 1567 1568// Define the create() method out of line to silence a GCC warning about 1569// the struct "Func" having greater visibility than its base, which comes from 1570// using the flag -fvisibility-inlines-hidden. 1571template <typename InnerTBase, template <typename OuterT> class Getter, 1572 template <typename OuterT> class MatcherImpl, typename ReturnTypesF> 1573TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl, ReturnTypesF> 1574TypeTraversePolymorphicMatcher< 1575 InnerTBase, Getter, MatcherImpl, 1576 ReturnTypesF>::create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers) { 1577 return Self(InnerMatchers); 1578} 1579 1580} // end namespace internal 1581} // end namespace ast_matchers 1582} // end namespace clang 1583 1584#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_INTERNAL_H 1585