ASTMatchers.h revision 3f84bb341bfb1312842b09db71d76bc3898ba247
1//===--- ASTMatchers.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// This file implements matchers to be used together with the MatchFinder to 11// match AST nodes. 12// 13// Matchers are created by generator functions, which can be combined in 14// a functional in-language DSL to express queries over the C++ AST. 15// 16// For example, to match a class with a certain name, one would call: 17// recordDecl(hasName("MyClass")) 18// which returns a matcher that can be used to find all AST nodes that declare 19// a class named 'MyClass'. 20// 21// For more complicated match expressions we're often interested in accessing 22// multiple parts of the matched AST nodes once a match is found. In that case, 23// use the id(...) matcher around the match expressions that match the nodes 24// you want to access. 25// 26// For example, when we're interested in child classes of a certain class, we 27// would write: 28// recordDecl(hasName("MyClass"), hasChild(id("child", recordDecl()))) 29// When the match is found via the MatchFinder, a user provided callback will 30// be called with a BoundNodes instance that contains a mapping from the 31// strings that we provided for the id(...) calls to the nodes that were 32// matched. 33// In the given example, each time our matcher finds a match we get a callback 34// where "child" is bound to the CXXRecordDecl node of the matching child 35// class declaration. 36// 37// See ASTMatchersInternal.h for a more in-depth explanation of the 38// implementation details of the matcher framework. 39// 40// See ASTMatchFinder.h for how to use the generated matchers to run over 41// an AST. 42// 43//===----------------------------------------------------------------------===// 44 45#ifndef LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H 46#define LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H 47 48#include "clang/AST/DeclTemplate.h" 49#include "clang/ASTMatchers/ASTMatchersInternal.h" 50#include "clang/ASTMatchers/ASTMatchersMacros.h" 51#include "llvm/ADT/Twine.h" 52#include "llvm/Support/Regex.h" 53#include <iterator> 54 55namespace clang { 56namespace ast_matchers { 57 58/// \brief Maps string IDs to AST nodes matched by parts of a matcher. 59/// 60/// The bound nodes are generated by calling \c bind("id") on the node matchers 61/// of the nodes we want to access later. 62/// 63/// The instances of BoundNodes are created by \c MatchFinder when the user's 64/// callbacks are executed every time a match is found. 65class BoundNodes { 66public: 67 /// \brief Returns the AST node bound to \c ID. 68 /// 69 /// Returns NULL if there was no node bound to \c ID or if there is a node but 70 /// it cannot be converted to the specified type. 71 template <typename T> 72 const T *getNodeAs(StringRef ID) const { 73 return MyBoundNodes.getNodeAs<T>(ID); 74 } 75 76 /// \brief Deprecated. Please use \c getNodeAs instead. 77 /// @{ 78 template <typename T> 79 const T *getDeclAs(StringRef ID) const { 80 return getNodeAs<T>(ID); 81 } 82 template <typename T> 83 const T *getStmtAs(StringRef ID) const { 84 return getNodeAs<T>(ID); 85 } 86 /// @} 87 88private: 89 /// \brief Create BoundNodes from a pre-filled map of bindings. 90 BoundNodes(internal::BoundNodesMap &MyBoundNodes) 91 : MyBoundNodes(MyBoundNodes) {} 92 93 internal::BoundNodesMap MyBoundNodes; 94 95 friend class internal::BoundNodesTreeBuilder; 96}; 97 98/// \brief If the provided matcher matches a node, binds the node to \c ID. 99/// 100/// FIXME: Do we want to support this now that we have bind()? 101template <typename T> 102internal::Matcher<T> id(const std::string &ID, 103 const internal::BindableMatcher<T> &InnerMatcher) { 104 return InnerMatcher.bind(ID); 105} 106 107/// \brief Types of matchers for the top-level classes in the AST class 108/// hierarchy. 109/// @{ 110typedef internal::Matcher<Decl> DeclarationMatcher; 111typedef internal::Matcher<Stmt> StatementMatcher; 112typedef internal::Matcher<QualType> TypeMatcher; 113typedef internal::Matcher<TypeLoc> TypeLocMatcher; 114typedef internal::Matcher<NestedNameSpecifier> NestedNameSpecifierMatcher; 115typedef internal::Matcher<NestedNameSpecifierLoc> NestedNameSpecifierLocMatcher; 116/// @} 117 118/// \brief Matches any node. 119/// 120/// Useful when another matcher requires a child matcher, but there's no 121/// additional constraint. This will often be used with an explicit conversion 122/// to an \c internal::Matcher<> type such as \c TypeMatcher. 123/// 124/// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g., 125/// \code 126/// "int* p" and "void f()" in 127/// int* p; 128/// void f(); 129/// \endcode 130/// 131/// Usable as: Any Matcher 132inline internal::PolymorphicMatcherWithParam0<internal::TrueMatcher> 133anything() { 134 return internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>(); 135} 136 137/// \brief Matches declarations. 138/// 139/// Examples matches \c X, \c C, and the friend declaration inside \c C; 140/// \code 141/// void X(); 142/// class C { 143/// friend X; 144/// }; 145/// \endcode 146const internal::VariadicAllOfMatcher<Decl> decl; 147 148/// \brief Matches a declaration of anything that could have a name. 149/// 150/// Example matches \c X, \c S, the anonymous union type, \c i, and \c U; 151/// \code 152/// typedef int X; 153/// struct S { 154/// union { 155/// int i; 156/// } U; 157/// }; 158/// \endcode 159const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl; 160 161/// \brief Matches a declaration of a namespace. 162/// 163/// Given 164/// \code 165/// namespace {} 166/// namespace test {} 167/// \endcode 168/// namespaceDecl() 169/// matches "namespace {}" and "namespace test {}" 170const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl; 171 172/// \brief Matches C++ class declarations. 173/// 174/// Example matches \c X, \c Z 175/// \code 176/// class X; 177/// template<class T> class Z {}; 178/// \endcode 179const internal::VariadicDynCastAllOfMatcher< 180 Decl, 181 CXXRecordDecl> recordDecl; 182 183/// \brief Matches C++ class template declarations. 184/// 185/// Example matches \c Z 186/// \code 187/// template<class T> class Z {}; 188/// \endcode 189const internal::VariadicDynCastAllOfMatcher< 190 Decl, 191 ClassTemplateDecl> classTemplateDecl; 192 193/// \brief Matches C++ class template specializations. 194/// 195/// Given 196/// \code 197/// template<typename T> class A {}; 198/// template<> class A<double> {}; 199/// A<int> a; 200/// \endcode 201/// classTemplateSpecializationDecl() 202/// matches the specializations \c A<int> and \c A<double> 203const internal::VariadicDynCastAllOfMatcher< 204 Decl, 205 ClassTemplateSpecializationDecl> classTemplateSpecializationDecl; 206 207/// \brief Matches declarator declarations (field, variable, function 208/// and non-type template parameter declarations). 209/// 210/// Given 211/// \code 212/// class X { int y; }; 213/// \endcode 214/// declaratorDecl() 215/// matches \c int y. 216const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl> 217 declaratorDecl; 218 219/// \brief Matches parameter variable declarations. 220/// 221/// Given 222/// \code 223/// void f(int x); 224/// \endcode 225/// parmVarDecl() 226/// matches \c int x. 227const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl> parmVarDecl; 228 229/// \brief Matches C++ access specifier declarations. 230/// 231/// Given 232/// \code 233/// class C { 234/// public: 235/// int a; 236/// }; 237/// \endcode 238/// accessSpecDecl() 239/// matches 'public:' 240const internal::VariadicDynCastAllOfMatcher< 241 Decl, 242 AccessSpecDecl> accessSpecDecl; 243 244/// \brief Matches public C++ declarations. 245/// 246/// Given 247/// \code 248/// class C { 249/// public: int a; 250/// protected: int b; 251/// private: int c; 252/// }; 253/// \endcode 254/// fieldDecl(isPublic()) 255/// matches 'int a;' 256AST_MATCHER(Decl, isPublic) { 257 return Node.getAccess() == AS_public; 258} 259 260/// \brief Matches protected C++ declarations. 261/// 262/// Given 263/// \code 264/// class C { 265/// public: int a; 266/// protected: int b; 267/// private: int c; 268/// }; 269/// \endcode 270/// fieldDecl(isProtected()) 271/// matches 'int b;' 272AST_MATCHER(Decl, isProtected) { 273 return Node.getAccess() == AS_protected; 274} 275 276/// \brief Matches private C++ declarations. 277/// 278/// Given 279/// \code 280/// class C { 281/// public: int a; 282/// protected: int b; 283/// private: int c; 284/// }; 285/// \endcode 286/// fieldDecl(isPrivate()) 287/// matches 'int c;' 288AST_MATCHER(Decl, isPrivate) { 289 return Node.getAccess() == AS_private; 290} 291 292/// \brief Matches classTemplateSpecializations that have at least one 293/// TemplateArgument matching the given InnerMatcher. 294/// 295/// Given 296/// \code 297/// template<typename T> class A {}; 298/// template<> class A<double> {}; 299/// A<int> a; 300/// \endcode 301/// classTemplateSpecializationDecl(hasAnyTemplateArgument( 302/// refersToType(asString("int")))) 303/// matches the specialization \c A<int> 304AST_MATCHER_P(ClassTemplateSpecializationDecl, hasAnyTemplateArgument, 305 internal::Matcher<TemplateArgument>, InnerMatcher) { 306 llvm::ArrayRef<TemplateArgument> List = Node.getTemplateArgs().asArray(); 307 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder, 308 Builder); 309} 310 311/// \brief Matches expressions that match InnerMatcher after any implicit casts 312/// are stripped off. 313/// 314/// Parentheses and explicit casts are not discarded. 315/// Given 316/// \code 317/// int arr[5]; 318/// int a = 0; 319/// char b = 0; 320/// const int c = a; 321/// int *d = arr; 322/// long e = (long) 0l; 323/// \endcode 324/// The matchers 325/// \code 326/// varDecl(hasInitializer(ignoringImpCasts(integerLiteral()))) 327/// varDecl(hasInitializer(ignoringImpCasts(declRefExpr()))) 328/// \endcode 329/// would match the declarations for a, b, c, and d, but not e. 330/// While 331/// \code 332/// varDecl(hasInitializer(integerLiteral())) 333/// varDecl(hasInitializer(declRefExpr())) 334/// \endcode 335/// only match the declarations for b, c, and d. 336AST_MATCHER_P(Expr, ignoringImpCasts, 337 internal::Matcher<Expr>, InnerMatcher) { 338 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder); 339} 340 341/// \brief Matches expressions that match InnerMatcher after parentheses and 342/// casts are stripped off. 343/// 344/// Implicit and non-C Style casts are also discarded. 345/// Given 346/// \code 347/// int a = 0; 348/// char b = (0); 349/// void* c = reinterpret_cast<char*>(0); 350/// char d = char(0); 351/// \endcode 352/// The matcher 353/// varDecl(hasInitializer(ignoringParenCasts(integerLiteral()))) 354/// would match the declarations for a, b, c, and d. 355/// while 356/// varDecl(hasInitializer(integerLiteral())) 357/// only match the declaration for a. 358AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) { 359 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder); 360} 361 362/// \brief Matches expressions that match InnerMatcher after implicit casts and 363/// parentheses are stripped off. 364/// 365/// Explicit casts are not discarded. 366/// Given 367/// \code 368/// int arr[5]; 369/// int a = 0; 370/// char b = (0); 371/// const int c = a; 372/// int *d = (arr); 373/// long e = ((long) 0l); 374/// \endcode 375/// The matchers 376/// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral()))) 377/// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr()))) 378/// would match the declarations for a, b, c, and d, but not e. 379/// while 380/// varDecl(hasInitializer(integerLiteral())) 381/// varDecl(hasInitializer(declRefExpr())) 382/// would only match the declaration for a. 383AST_MATCHER_P(Expr, ignoringParenImpCasts, 384 internal::Matcher<Expr>, InnerMatcher) { 385 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder); 386} 387 388/// \brief Matches classTemplateSpecializations where the n'th TemplateArgument 389/// matches the given InnerMatcher. 390/// 391/// Given 392/// \code 393/// template<typename T, typename U> class A {}; 394/// A<bool, int> b; 395/// A<int, bool> c; 396/// \endcode 397/// classTemplateSpecializationDecl(hasTemplateArgument( 398/// 1, refersToType(asString("int")))) 399/// matches the specialization \c A<bool, int> 400AST_MATCHER_P2(ClassTemplateSpecializationDecl, hasTemplateArgument, 401 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) { 402 const TemplateArgumentList &List = Node.getTemplateArgs(); 403 if (List.size() <= N) 404 return false; 405 return InnerMatcher.matches(List.get(N), Finder, Builder); 406} 407 408/// \brief Matches a TemplateArgument that refers to a certain type. 409/// 410/// Given 411/// \code 412/// struct X {}; 413/// template<typename T> struct A {}; 414/// A<X> a; 415/// \endcode 416/// classTemplateSpecializationDecl(hasAnyTemplateArgument( 417/// refersToType(class(hasName("X"))))) 418/// matches the specialization \c A<X> 419AST_MATCHER_P(TemplateArgument, refersToType, 420 internal::Matcher<QualType>, InnerMatcher) { 421 if (Node.getKind() != TemplateArgument::Type) 422 return false; 423 return InnerMatcher.matches(Node.getAsType(), Finder, Builder); 424} 425 426/// \brief Matches a TemplateArgument that refers to a certain declaration. 427/// 428/// Given 429/// \code 430/// template<typename T> struct A {}; 431/// struct B { B* next; }; 432/// A<&B::next> a; 433/// \endcode 434/// classTemplateSpecializationDecl(hasAnyTemplateArgument( 435/// refersToDeclaration(fieldDecl(hasName("next")))) 436/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching 437/// \c B::next 438AST_MATCHER_P(TemplateArgument, refersToDeclaration, 439 internal::Matcher<Decl>, InnerMatcher) { 440 if (Node.getKind() == TemplateArgument::Declaration) 441 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder); 442 return false; 443} 444 445/// \brief Matches C++ constructor declarations. 446/// 447/// Example matches Foo::Foo() and Foo::Foo(int) 448/// \code 449/// class Foo { 450/// public: 451/// Foo(); 452/// Foo(int); 453/// int DoSomething(); 454/// }; 455/// \endcode 456const internal::VariadicDynCastAllOfMatcher< 457 Decl, 458 CXXConstructorDecl> constructorDecl; 459 460/// \brief Matches explicit C++ destructor declarations. 461/// 462/// Example matches Foo::~Foo() 463/// \code 464/// class Foo { 465/// public: 466/// virtual ~Foo(); 467/// }; 468/// \endcode 469const internal::VariadicDynCastAllOfMatcher< 470 Decl, 471 CXXDestructorDecl> destructorDecl; 472 473/// \brief Matches enum declarations. 474/// 475/// Example matches X 476/// \code 477/// enum X { 478/// A, B, C 479/// }; 480/// \endcode 481const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl; 482 483/// \brief Matches enum constants. 484/// 485/// Example matches A, B, C 486/// \code 487/// enum X { 488/// A, B, C 489/// }; 490/// \endcode 491const internal::VariadicDynCastAllOfMatcher< 492 Decl, 493 EnumConstantDecl> enumConstantDecl; 494 495/// \brief Matches method declarations. 496/// 497/// Example matches y 498/// \code 499/// class X { void y() }; 500/// \endcode 501const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> methodDecl; 502 503/// \brief Matches variable declarations. 504/// 505/// Note: this does not match declarations of member variables, which are 506/// "field" declarations in Clang parlance. 507/// 508/// Example matches a 509/// \code 510/// int a; 511/// \endcode 512const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl; 513 514/// \brief Matches field declarations. 515/// 516/// Given 517/// \code 518/// class X { int m; }; 519/// \endcode 520/// fieldDecl() 521/// matches 'm'. 522const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl; 523 524/// \brief Matches function declarations. 525/// 526/// Example matches f 527/// \code 528/// void f(); 529/// \endcode 530const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl; 531 532/// \brief Matches C++ function template declarations. 533/// 534/// Example matches f 535/// \code 536/// template<class T> void f(T t) {} 537/// \endcode 538const internal::VariadicDynCastAllOfMatcher< 539 Decl, 540 FunctionTemplateDecl> functionTemplateDecl; 541 542/// \brief Matches statements. 543/// 544/// Given 545/// \code 546/// { ++a; } 547/// \endcode 548/// stmt() 549/// matches both the compound statement '{ ++a; }' and '++a'. 550const internal::VariadicAllOfMatcher<Stmt> stmt; 551 552/// \brief Matches declaration statements. 553/// 554/// Given 555/// \code 556/// int a; 557/// \endcode 558/// declStmt() 559/// matches 'int a'. 560const internal::VariadicDynCastAllOfMatcher< 561 Stmt, 562 DeclStmt> declStmt; 563 564/// \brief Matches member expressions. 565/// 566/// Given 567/// \code 568/// class Y { 569/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 570/// int a; static int b; 571/// }; 572/// \endcode 573/// memberExpr() 574/// matches this->x, x, y.x, a, this->b 575const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr; 576 577/// \brief Matches call expressions. 578/// 579/// Example matches x.y() and y() 580/// \code 581/// X x; 582/// x.y(); 583/// y(); 584/// \endcode 585const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr; 586 587/// \brief Matches lambda expressions. 588/// 589/// Example matches [&](){return 5;} 590/// \code 591/// [&](){return 5;} 592/// \endcode 593const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr; 594 595/// \brief Matches member call expressions. 596/// 597/// Example matches x.y() 598/// \code 599/// X x; 600/// x.y(); 601/// \endcode 602const internal::VariadicDynCastAllOfMatcher< 603 Stmt, 604 CXXMemberCallExpr> memberCallExpr; 605 606/// \brief Matches init list expressions. 607/// 608/// Given 609/// \code 610/// int a[] = { 1, 2 }; 611/// struct B { int x, y; }; 612/// B b = { 5, 6 }; 613/// \endcode 614/// initList() 615/// matches "{ 1, 2 }" and "{ 5, 6 }" 616const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr; 617 618/// \brief Matches using declarations. 619/// 620/// Given 621/// \code 622/// namespace X { int x; } 623/// using X::x; 624/// \endcode 625/// usingDecl() 626/// matches \code using X::x \endcode 627const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl; 628 629/// \brief Matches constructor call expressions (including implicit ones). 630/// 631/// Example matches string(ptr, n) and ptr within arguments of f 632/// (matcher = constructExpr()) 633/// \code 634/// void f(const string &a, const string &b); 635/// char *ptr; 636/// int n; 637/// f(string(ptr, n), ptr); 638/// \endcode 639const internal::VariadicDynCastAllOfMatcher< 640 Stmt, 641 CXXConstructExpr> constructExpr; 642 643/// \brief Matches unresolved constructor call expressions. 644/// 645/// Example matches T(t) in return statement of f 646/// (matcher = unresolvedConstructExpr()) 647/// \code 648/// template <typename T> 649/// void f(const T& t) { return T(t); } 650/// \endcode 651const internal::VariadicDynCastAllOfMatcher< 652 Stmt, 653 CXXUnresolvedConstructExpr> unresolvedConstructExpr; 654 655/// \brief Matches implicit and explicit this expressions. 656/// 657/// Example matches the implicit this expression in "return i". 658/// (matcher = thisExpr()) 659/// \code 660/// struct foo { 661/// int i; 662/// int f() { return i; } 663/// }; 664/// \endcode 665const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> thisExpr; 666 667/// \brief Matches nodes where temporaries are created. 668/// 669/// Example matches FunctionTakesString(GetStringByValue()) 670/// (matcher = bindTemporaryExpr()) 671/// \code 672/// FunctionTakesString(GetStringByValue()); 673/// FunctionTakesStringByPointer(GetStringPointer()); 674/// \endcode 675const internal::VariadicDynCastAllOfMatcher< 676 Stmt, 677 CXXBindTemporaryExpr> bindTemporaryExpr; 678 679/// \brief Matches nodes where temporaries are materialized. 680/// 681/// Example: Given 682/// \code 683/// struct T {void func()}; 684/// T f(); 685/// void g(T); 686/// \endcode 687/// materializeTemporaryExpr() matches 'f()' in these statements 688/// \code 689/// T u(f()); 690/// g(f()); 691/// \endcode 692/// but does not match 693/// \code 694/// f(); 695/// f().func(); 696/// \endcode 697const internal::VariadicDynCastAllOfMatcher< 698 Stmt, 699 MaterializeTemporaryExpr> materializeTemporaryExpr; 700 701/// \brief Matches new expressions. 702/// 703/// Given 704/// \code 705/// new X; 706/// \endcode 707/// newExpr() 708/// matches 'new X'. 709const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> newExpr; 710 711/// \brief Matches delete expressions. 712/// 713/// Given 714/// \code 715/// delete X; 716/// \endcode 717/// deleteExpr() 718/// matches 'delete X'. 719const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> deleteExpr; 720 721/// \brief Matches array subscript expressions. 722/// 723/// Given 724/// \code 725/// int i = a[1]; 726/// \endcode 727/// arraySubscriptExpr() 728/// matches "a[1]" 729const internal::VariadicDynCastAllOfMatcher< 730 Stmt, 731 ArraySubscriptExpr> arraySubscriptExpr; 732 733/// \brief Matches the value of a default argument at the call site. 734/// 735/// Example matches the CXXDefaultArgExpr placeholder inserted for the 736/// default value of the second parameter in the call expression f(42) 737/// (matcher = defaultArgExpr()) 738/// \code 739/// void f(int x, int y = 0); 740/// f(42); 741/// \endcode 742const internal::VariadicDynCastAllOfMatcher< 743 Stmt, 744 CXXDefaultArgExpr> defaultArgExpr; 745 746/// \brief Matches overloaded operator calls. 747/// 748/// Note that if an operator isn't overloaded, it won't match. Instead, use 749/// binaryOperator matcher. 750/// Currently it does not match operators such as new delete. 751/// FIXME: figure out why these do not match? 752/// 753/// Example matches both operator<<((o << b), c) and operator<<(o, b) 754/// (matcher = operatorCallExpr()) 755/// \code 756/// ostream &operator<< (ostream &out, int i) { }; 757/// ostream &o; int b = 1, c = 1; 758/// o << b << c; 759/// \endcode 760const internal::VariadicDynCastAllOfMatcher< 761 Stmt, 762 CXXOperatorCallExpr> operatorCallExpr; 763 764/// \brief Matches expressions. 765/// 766/// Example matches x() 767/// \code 768/// void f() { x(); } 769/// \endcode 770const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr; 771 772/// \brief Matches expressions that refer to declarations. 773/// 774/// Example matches x in if (x) 775/// \code 776/// bool x; 777/// if (x) {} 778/// \endcode 779const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr; 780 781/// \brief Matches if statements. 782/// 783/// Example matches 'if (x) {}' 784/// \code 785/// if (x) {} 786/// \endcode 787const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt; 788 789/// \brief Matches for statements. 790/// 791/// Example matches 'for (;;) {}' 792/// \code 793/// for (;;) {} 794/// int i[] = {1, 2, 3}; for (auto a : i); 795/// \endcode 796const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt; 797 798/// \brief Matches range-based for statements. 799/// 800/// forRangeStmt() matches 'for (auto a : i)' 801/// \code 802/// int i[] = {1, 2, 3}; for (auto a : i); 803/// for(int j = 0; j < 5; ++j); 804/// \endcode 805const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt> forRangeStmt; 806 807/// \brief Matches the increment statement of a for loop. 808/// 809/// Example: 810/// forStmt(hasIncrement(unaryOperator(hasOperatorName("++")))) 811/// matches '++x' in 812/// \code 813/// for (x; x < N; ++x) { } 814/// \endcode 815AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>, 816 InnerMatcher) { 817 const Stmt *const Increment = Node.getInc(); 818 return (Increment != NULL && 819 InnerMatcher.matches(*Increment, Finder, Builder)); 820} 821 822/// \brief Matches the initialization statement of a for loop. 823/// 824/// Example: 825/// forStmt(hasLoopInit(declStmt())) 826/// matches 'int x = 0' in 827/// \code 828/// for (int x = 0; x < N; ++x) { } 829/// \endcode 830AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>, 831 InnerMatcher) { 832 const Stmt *const Init = Node.getInit(); 833 return (Init != NULL && InnerMatcher.matches(*Init, Finder, Builder)); 834} 835 836/// \brief Matches while statements. 837/// 838/// Given 839/// \code 840/// while (true) {} 841/// \endcode 842/// whileStmt() 843/// matches 'while (true) {}'. 844const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt; 845 846/// \brief Matches do statements. 847/// 848/// Given 849/// \code 850/// do {} while (true); 851/// \endcode 852/// doStmt() 853/// matches 'do {} while(true)' 854const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt; 855 856/// \brief Matches break statements. 857/// 858/// Given 859/// \code 860/// while (true) { break; } 861/// \endcode 862/// breakStmt() 863/// matches 'break' 864const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt; 865 866/// \brief Matches continue statements. 867/// 868/// Given 869/// \code 870/// while (true) { continue; } 871/// \endcode 872/// continueStmt() 873/// matches 'continue' 874const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt; 875 876/// \brief Matches return statements. 877/// 878/// Given 879/// \code 880/// return 1; 881/// \endcode 882/// returnStmt() 883/// matches 'return 1' 884const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt; 885 886/// \brief Matches goto statements. 887/// 888/// Given 889/// \code 890/// goto FOO; 891/// FOO: bar(); 892/// \endcode 893/// gotoStmt() 894/// matches 'goto FOO' 895const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt; 896 897/// \brief Matches label statements. 898/// 899/// Given 900/// \code 901/// goto FOO; 902/// FOO: bar(); 903/// \endcode 904/// labelStmt() 905/// matches 'FOO:' 906const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt; 907 908/// \brief Matches switch statements. 909/// 910/// Given 911/// \code 912/// switch(a) { case 42: break; default: break; } 913/// \endcode 914/// switchStmt() 915/// matches 'switch(a)'. 916const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt; 917 918/// \brief Matches case and default statements inside switch statements. 919/// 920/// Given 921/// \code 922/// switch(a) { case 42: break; default: break; } 923/// \endcode 924/// switchCase() 925/// matches 'case 42: break;' and 'default: break;'. 926const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase; 927 928/// \brief Matches case statements inside switch statements. 929/// 930/// Given 931/// \code 932/// switch(a) { case 42: break; default: break; } 933/// \endcode 934/// caseStmt() 935/// matches 'case 42: break;'. 936const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt; 937 938/// \brief Matches default statements inside switch statements. 939/// 940/// Given 941/// \code 942/// switch(a) { case 42: break; default: break; } 943/// \endcode 944/// defaultStmt() 945/// matches 'default: break;'. 946const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt> defaultStmt; 947 948/// \brief Matches compound statements. 949/// 950/// Example matches '{}' and '{{}}'in 'for (;;) {{}}' 951/// \code 952/// for (;;) {{}} 953/// \endcode 954const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt; 955 956/// \brief Matches catch statements. 957/// 958/// \code 959/// try {} catch(int i) {} 960/// \endcode 961/// catchStmt() 962/// matches 'catch(int i)' 963const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> catchStmt; 964 965/// \brief Matches try statements. 966/// 967/// \code 968/// try {} catch(int i) {} 969/// \endcode 970/// tryStmt() 971/// matches 'try {}' 972const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> tryStmt; 973 974/// \brief Matches throw expressions. 975/// 976/// \code 977/// try { throw 5; } catch(int i) {} 978/// \endcode 979/// throwExpr() 980/// matches 'throw 5' 981const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> throwExpr; 982 983/// \brief Matches null statements. 984/// 985/// \code 986/// foo();; 987/// \endcode 988/// nullStmt() 989/// matches the second ';' 990const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt; 991 992/// \brief Matches asm statements. 993/// 994/// \code 995/// int i = 100; 996/// __asm("mov al, 2"); 997/// \endcode 998/// asmStmt() 999/// matches '__asm("mov al, 2")' 1000const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt; 1001 1002/// \brief Matches bool literals. 1003/// 1004/// Example matches true 1005/// \code 1006/// true 1007/// \endcode 1008const internal::VariadicDynCastAllOfMatcher< 1009 Stmt, 1010 CXXBoolLiteralExpr> boolLiteral; 1011 1012/// \brief Matches string literals (also matches wide string literals). 1013/// 1014/// Example matches "abcd", L"abcd" 1015/// \code 1016/// char *s = "abcd"; wchar_t *ws = L"abcd" 1017/// \endcode 1018const internal::VariadicDynCastAllOfMatcher< 1019 Stmt, 1020 StringLiteral> stringLiteral; 1021 1022/// \brief Matches character literals (also matches wchar_t). 1023/// 1024/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral), 1025/// though. 1026/// 1027/// Example matches 'a', L'a' 1028/// \code 1029/// char ch = 'a'; wchar_t chw = L'a'; 1030/// \endcode 1031const internal::VariadicDynCastAllOfMatcher< 1032 Stmt, 1033 CharacterLiteral> characterLiteral; 1034 1035/// \brief Matches integer literals of all sizes / encodings. 1036/// 1037/// Not matching character-encoded integers such as L'a'. 1038/// 1039/// Example matches 1, 1L, 0x1, 1U 1040const internal::VariadicDynCastAllOfMatcher< 1041 Stmt, 1042 IntegerLiteral> integerLiteral; 1043 1044/// \brief Matches user defined literal operator call. 1045/// 1046/// Example match: "foo"_suffix 1047const internal::VariadicDynCastAllOfMatcher< 1048 Stmt, 1049 UserDefinedLiteral> userDefinedLiteral; 1050 1051/// \brief Matches compound (i.e. non-scalar) literals 1052/// 1053/// Example match: {1}, (1, 2) 1054/// \code 1055/// int array[4] = {1}; vector int myvec = (vector int)(1, 2); 1056/// \endcode 1057const internal::VariadicDynCastAllOfMatcher< 1058 Stmt, 1059 CompoundLiteralExpr> compoundLiteralExpr; 1060 1061/// \brief Matches nullptr literal. 1062const internal::VariadicDynCastAllOfMatcher< 1063 Stmt, 1064 CXXNullPtrLiteralExpr> nullPtrLiteralExpr; 1065 1066/// \brief Matches binary operator expressions. 1067/// 1068/// Example matches a || b 1069/// \code 1070/// !(a || b) 1071/// \endcode 1072const internal::VariadicDynCastAllOfMatcher< 1073 Stmt, 1074 BinaryOperator> binaryOperator; 1075 1076/// \brief Matches unary operator expressions. 1077/// 1078/// Example matches !a 1079/// \code 1080/// !a || b 1081/// \endcode 1082const internal::VariadicDynCastAllOfMatcher< 1083 Stmt, 1084 UnaryOperator> unaryOperator; 1085 1086/// \brief Matches conditional operator expressions. 1087/// 1088/// Example matches a ? b : c 1089/// \code 1090/// (a ? b : c) + 42 1091/// \endcode 1092const internal::VariadicDynCastAllOfMatcher< 1093 Stmt, 1094 ConditionalOperator> conditionalOperator; 1095 1096/// \brief Matches a reinterpret_cast expression. 1097/// 1098/// Either the source expression or the destination type can be matched 1099/// using has(), but hasDestinationType() is more specific and can be 1100/// more readable. 1101/// 1102/// Example matches reinterpret_cast<char*>(&p) in 1103/// \code 1104/// void* p = reinterpret_cast<char*>(&p); 1105/// \endcode 1106const internal::VariadicDynCastAllOfMatcher< 1107 Stmt, 1108 CXXReinterpretCastExpr> reinterpretCastExpr; 1109 1110/// \brief Matches a C++ static_cast expression. 1111/// 1112/// \see hasDestinationType 1113/// \see reinterpretCast 1114/// 1115/// Example: 1116/// staticCastExpr() 1117/// matches 1118/// static_cast<long>(8) 1119/// in 1120/// \code 1121/// long eight(static_cast<long>(8)); 1122/// \endcode 1123const internal::VariadicDynCastAllOfMatcher< 1124 Stmt, 1125 CXXStaticCastExpr> staticCastExpr; 1126 1127/// \brief Matches a dynamic_cast expression. 1128/// 1129/// Example: 1130/// dynamicCastExpr() 1131/// matches 1132/// dynamic_cast<D*>(&b); 1133/// in 1134/// \code 1135/// struct B { virtual ~B() {} }; struct D : B {}; 1136/// B b; 1137/// D* p = dynamic_cast<D*>(&b); 1138/// \endcode 1139const internal::VariadicDynCastAllOfMatcher< 1140 Stmt, 1141 CXXDynamicCastExpr> dynamicCastExpr; 1142 1143/// \brief Matches a const_cast expression. 1144/// 1145/// Example: Matches const_cast<int*>(&r) in 1146/// \code 1147/// int n = 42; 1148/// const int &r(n); 1149/// int* p = const_cast<int*>(&r); 1150/// \endcode 1151const internal::VariadicDynCastAllOfMatcher< 1152 Stmt, 1153 CXXConstCastExpr> constCastExpr; 1154 1155/// \brief Matches a C-style cast expression. 1156/// 1157/// Example: Matches (int*) 2.2f in 1158/// \code 1159/// int i = (int) 2.2f; 1160/// \endcode 1161const internal::VariadicDynCastAllOfMatcher< 1162 Stmt, 1163 CStyleCastExpr> cStyleCastExpr; 1164 1165/// \brief Matches explicit cast expressions. 1166/// 1167/// Matches any cast expression written in user code, whether it be a 1168/// C-style cast, a functional-style cast, or a keyword cast. 1169/// 1170/// Does not match implicit conversions. 1171/// 1172/// Note: the name "explicitCast" is chosen to match Clang's terminology, as 1173/// Clang uses the term "cast" to apply to implicit conversions as well as to 1174/// actual cast expressions. 1175/// 1176/// \see hasDestinationType. 1177/// 1178/// Example: matches all five of the casts in 1179/// \code 1180/// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42))))) 1181/// \endcode 1182/// but does not match the implicit conversion in 1183/// \code 1184/// long ell = 42; 1185/// \endcode 1186const internal::VariadicDynCastAllOfMatcher< 1187 Stmt, 1188 ExplicitCastExpr> explicitCastExpr; 1189 1190/// \brief Matches the implicit cast nodes of Clang's AST. 1191/// 1192/// This matches many different places, including function call return value 1193/// eliding, as well as any type conversions. 1194const internal::VariadicDynCastAllOfMatcher< 1195 Stmt, 1196 ImplicitCastExpr> implicitCastExpr; 1197 1198/// \brief Matches any cast nodes of Clang's AST. 1199/// 1200/// Example: castExpr() matches each of the following: 1201/// \code 1202/// (int) 3; 1203/// const_cast<Expr *>(SubExpr); 1204/// char c = 0; 1205/// \endcode 1206/// but does not match 1207/// \code 1208/// int i = (0); 1209/// int k = 0; 1210/// \endcode 1211const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr; 1212 1213/// \brief Matches functional cast expressions 1214/// 1215/// Example: Matches Foo(bar); 1216/// \code 1217/// Foo f = bar; 1218/// Foo g = (Foo) bar; 1219/// Foo h = Foo(bar); 1220/// \endcode 1221const internal::VariadicDynCastAllOfMatcher< 1222 Stmt, 1223 CXXFunctionalCastExpr> functionalCastExpr; 1224 1225/// \brief Matches \c QualTypes in the clang AST. 1226const internal::VariadicAllOfMatcher<QualType> qualType; 1227 1228/// \brief Matches \c Types in the clang AST. 1229const internal::VariadicAllOfMatcher<Type> type; 1230 1231/// \brief Matches \c TypeLocs in the clang AST. 1232const internal::VariadicAllOfMatcher<TypeLoc> typeLoc; 1233 1234/// \brief Matches if any of the given matchers matches. 1235/// 1236/// Unlike \c anyOf, \c eachOf will generate a match result for each 1237/// matching submatcher. 1238/// 1239/// For example, in: 1240/// \code 1241/// class A { int a; int b; }; 1242/// \endcode 1243/// The matcher: 1244/// \code 1245/// recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")), 1246/// has(fieldDecl(hasName("b")).bind("v")))) 1247/// \endcode 1248/// will generate two results binding "v", the first of which binds 1249/// the field declaration of \c a, the second the field declaration of 1250/// \c b. 1251/// 1252/// Usable as: Any Matcher 1253template <typename M1, typename M2> 1254internal::PolymorphicMatcherWithParam2<internal::EachOfMatcher, M1, M2> 1255eachOf(const M1 &P1, const M2 &P2) { 1256 return internal::PolymorphicMatcherWithParam2<internal::EachOfMatcher, M1, 1257 M2>(P1, P2); 1258} 1259 1260/// \brief Various overloads for the anyOf matcher. 1261/// @{ 1262 1263/// \brief Matches if any of the given matchers matches. 1264/// 1265/// Usable as: Any Matcher 1266template<typename M1, typename M2> 1267internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1, M2> 1268anyOf(const M1 &P1, const M2 &P2) { 1269 return internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 1270 M1, M2 >(P1, P2); 1271} 1272template<typename M1, typename M2, typename M3> 1273internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1, 1274 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2, M3> > 1275anyOf(const M1 &P1, const M2 &P2, const M3 &P3) { 1276 return anyOf(P1, anyOf(P2, P3)); 1277} 1278template<typename M1, typename M2, typename M3, typename M4> 1279internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1, 1280 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2, 1281 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 1282 M3, M4> > > 1283anyOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4) { 1284 return anyOf(P1, anyOf(P2, anyOf(P3, P4))); 1285} 1286template<typename M1, typename M2, typename M3, typename M4, typename M5> 1287internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1, 1288 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2, 1289 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M3, 1290 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 1291 M4, M5> > > > 1292anyOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4, const M5 &P5) { 1293 return anyOf(P1, anyOf(P2, anyOf(P3, anyOf(P4, P5)))); 1294} 1295 1296/// @} 1297 1298/// \brief Various overloads for the allOf matcher. 1299/// @{ 1300 1301/// \brief Matches if all given matchers match. 1302/// 1303/// Usable as: Any Matcher 1304template <typename M1, typename M2> 1305internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M1, M2> 1306allOf(const M1 &P1, const M2 &P2) { 1307 return internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M1, M2>( 1308 P1, P2); 1309} 1310template <typename M1, typename M2, typename M3> 1311internal::PolymorphicMatcherWithParam2< 1312 internal::AllOfMatcher, M1, 1313 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M2, M3> > 1314allOf(const M1 &P1, const M2 &P2, const M3 &P3) { 1315 return allOf(P1, allOf(P2, P3)); 1316} 1317template <typename M1, typename M2, typename M3, typename M4> 1318internal::PolymorphicMatcherWithParam2< 1319 internal::AllOfMatcher, M1, 1320 internal::PolymorphicMatcherWithParam2< 1321 internal::AllOfMatcher, M2, internal::PolymorphicMatcherWithParam2< 1322 internal::AllOfMatcher, M3, M4> > > 1323allOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4) { 1324 return allOf(P1, allOf(P2, P3, P4)); 1325} 1326template <typename M1, typename M2, typename M3, typename M4, typename M5> 1327internal::PolymorphicMatcherWithParam2< 1328 internal::AllOfMatcher, M1, 1329 internal::PolymorphicMatcherWithParam2< 1330 internal::AllOfMatcher, M2, 1331 internal::PolymorphicMatcherWithParam2< 1332 internal::AllOfMatcher, M3, 1333 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M4, 1334 M5> > > > 1335allOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4, const M5 &P5) { 1336 return allOf(P1, allOf(P2, P3, P4, P5)); 1337} 1338 1339/// @} 1340 1341/// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL) 1342/// 1343/// Given 1344/// \code 1345/// Foo x = bar; 1346/// int y = sizeof(x) + alignof(x); 1347/// \endcode 1348/// unaryExprOrTypeTraitExpr() 1349/// matches \c sizeof(x) and \c alignof(x) 1350const internal::VariadicDynCastAllOfMatcher< 1351 Stmt, 1352 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr; 1353 1354/// \brief Matches unary expressions that have a specific type of argument. 1355/// 1356/// Given 1357/// \code 1358/// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c); 1359/// \endcode 1360/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int")) 1361/// matches \c sizeof(a) and \c alignof(c) 1362AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType, 1363 internal::Matcher<QualType>, InnerMatcher) { 1364 const QualType ArgumentType = Node.getTypeOfArgument(); 1365 return InnerMatcher.matches(ArgumentType, Finder, Builder); 1366} 1367 1368/// \brief Matches unary expressions of a certain kind. 1369/// 1370/// Given 1371/// \code 1372/// int x; 1373/// int s = sizeof(x) + alignof(x) 1374/// \endcode 1375/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf)) 1376/// matches \c sizeof(x) 1377AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) { 1378 return Node.getKind() == Kind; 1379} 1380 1381/// \brief Same as unaryExprOrTypeTraitExpr, but only matching 1382/// alignof. 1383inline internal::Matcher<Stmt> alignOfExpr( 1384 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) { 1385 return stmt(unaryExprOrTypeTraitExpr(allOf( 1386 ofKind(UETT_AlignOf), InnerMatcher))); 1387} 1388 1389/// \brief Same as unaryExprOrTypeTraitExpr, but only matching 1390/// sizeof. 1391inline internal::Matcher<Stmt> sizeOfExpr( 1392 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) { 1393 return stmt(unaryExprOrTypeTraitExpr( 1394 allOf(ofKind(UETT_SizeOf), InnerMatcher))); 1395} 1396 1397/// \brief Matches NamedDecl nodes that have the specified name. 1398/// 1399/// Supports specifying enclosing namespaces or classes by prefixing the name 1400/// with '<enclosing>::'. 1401/// Does not match typedefs of an underlying type with the given name. 1402/// 1403/// Example matches X (Name == "X") 1404/// \code 1405/// class X; 1406/// \endcode 1407/// 1408/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X") 1409/// \code 1410/// namespace a { namespace b { class X; } } 1411/// \endcode 1412AST_MATCHER_P(NamedDecl, hasName, std::string, Name) { 1413 assert(!Name.empty()); 1414 const std::string FullNameString = "::" + Node.getQualifiedNameAsString(); 1415 const StringRef FullName = FullNameString; 1416 const StringRef Pattern = Name; 1417 if (Pattern.startswith("::")) { 1418 return FullName == Pattern; 1419 } else { 1420 return FullName.endswith(("::" + Pattern).str()); 1421 } 1422} 1423 1424/// \brief Matches NamedDecl nodes whose fully qualified names contain 1425/// a substring matched by the given RegExp. 1426/// 1427/// Supports specifying enclosing namespaces or classes by 1428/// prefixing the name with '<enclosing>::'. Does not match typedefs 1429/// of an underlying type with the given name. 1430/// 1431/// Example matches X (regexp == "::X") 1432/// \code 1433/// class X; 1434/// \endcode 1435/// 1436/// Example matches X (regexp is one of "::X", "^foo::.*X", among others) 1437/// \code 1438/// namespace foo { namespace bar { class X; } } 1439/// \endcode 1440AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) { 1441 assert(!RegExp.empty()); 1442 std::string FullNameString = "::" + Node.getQualifiedNameAsString(); 1443 llvm::Regex RE(RegExp); 1444 return RE.match(FullNameString); 1445} 1446 1447/// \brief Matches overloaded operator names. 1448/// 1449/// Matches overloaded operator names specified in strings without the 1450/// "operator" prefix: e.g. "<<". 1451/// 1452/// Given: 1453/// \code 1454/// class A { int operator*(); }; 1455/// const A &operator<<(const A &a, const A &b); 1456/// A a; 1457/// a << a; // <-- This matches 1458/// \endcode 1459/// 1460/// \c operatorCallExpr(hasOverloadedOperatorName("<<"))) matches the specified 1461/// line and \c recordDecl(hasMethod(hasOverloadedOperatorName("*"))) matches 1462/// the declaration of \c A. 1463/// 1464/// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<CXXMethodDecl> 1465inline internal::PolymorphicMatcherWithParam1< 1466 internal::HasOverloadedOperatorNameMatcher, StringRef, 1467 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CXXOperatorCallExpr, CXXMethodDecl)> 1468hasOverloadedOperatorName(const StringRef Name) { 1469 return internal::PolymorphicMatcherWithParam1< 1470 internal::HasOverloadedOperatorNameMatcher, StringRef, 1471 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CXXOperatorCallExpr, CXXMethodDecl)>( 1472 Name); 1473} 1474 1475/// \brief Matches C++ classes that are directly or indirectly derived from 1476/// a class matching \c Base. 1477/// 1478/// Note that a class is not considered to be derived from itself. 1479/// 1480/// Example matches Y, Z, C (Base == hasName("X")) 1481/// \code 1482/// class X; 1483/// class Y : public X {}; // directly derived 1484/// class Z : public Y {}; // indirectly derived 1485/// typedef X A; 1486/// typedef A B; 1487/// class C : public B {}; // derived from a typedef of X 1488/// \endcode 1489/// 1490/// In the following example, Bar matches isDerivedFrom(hasName("X")): 1491/// \code 1492/// class Foo; 1493/// typedef Foo X; 1494/// class Bar : public Foo {}; // derived from a type that X is a typedef of 1495/// \endcode 1496AST_MATCHER_P(CXXRecordDecl, isDerivedFrom, 1497 internal::Matcher<NamedDecl>, Base) { 1498 return Finder->classIsDerivedFrom(&Node, Base, Builder); 1499} 1500 1501/// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)). 1502inline internal::Matcher<CXXRecordDecl> isDerivedFrom(StringRef BaseName) { 1503 assert(!BaseName.empty()); 1504 return isDerivedFrom(hasName(BaseName)); 1505} 1506 1507/// \brief Similar to \c isDerivedFrom(), but also matches classes that directly 1508/// match \c Base. 1509inline internal::Matcher<CXXRecordDecl> isSameOrDerivedFrom( 1510 internal::Matcher<NamedDecl> Base) { 1511 return anyOf(Base, isDerivedFrom(Base)); 1512} 1513 1514/// \brief Overloaded method as shortcut for 1515/// \c isSameOrDerivedFrom(hasName(...)). 1516inline internal::Matcher<CXXRecordDecl> isSameOrDerivedFrom( 1517 StringRef BaseName) { 1518 assert(!BaseName.empty()); 1519 return isSameOrDerivedFrom(hasName(BaseName)); 1520} 1521 1522/// \brief Matches the first method of a class or struct that satisfies \c 1523/// InnerMatcher. 1524/// 1525/// Given: 1526/// \code 1527/// class A { void func(); }; 1528/// class B { void member(); }; 1529/// \code 1530/// 1531/// \c recordDecl(hasMethod(hasName("func"))) matches the declaration of \c A 1532/// but not \c B. 1533AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>, 1534 InnerMatcher) { 1535 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(), 1536 Node.method_end(), Finder, Builder); 1537} 1538 1539/// \brief Matches AST nodes that have child AST nodes that match the 1540/// provided matcher. 1541/// 1542/// Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X"))) 1543/// \code 1544/// class X {}; // Matches X, because X::X is a class of name X inside X. 1545/// class Y { class X {}; }; 1546/// class Z { class Y { class X {}; }; }; // Does not match Z. 1547/// \endcode 1548/// 1549/// ChildT must be an AST base type. 1550/// 1551/// Usable as: Any Matcher 1552template <typename ChildT> 1553internal::ArgumentAdaptingMatcher<internal::HasMatcher, ChildT> has( 1554 const internal::Matcher<ChildT> &ChildMatcher) { 1555 return internal::ArgumentAdaptingMatcher<internal::HasMatcher, 1556 ChildT>(ChildMatcher); 1557} 1558 1559/// \brief Matches AST nodes that have descendant AST nodes that match the 1560/// provided matcher. 1561/// 1562/// Example matches X, Y, Z 1563/// (matcher = recordDecl(hasDescendant(recordDecl(hasName("X"))))) 1564/// \code 1565/// class X {}; // Matches X, because X::X is a class of name X inside X. 1566/// class Y { class X {}; }; 1567/// class Z { class Y { class X {}; }; }; 1568/// \endcode 1569/// 1570/// DescendantT must be an AST base type. 1571/// 1572/// Usable as: Any Matcher 1573template <typename DescendantT> 1574internal::ArgumentAdaptingMatcher<internal::HasDescendantMatcher, DescendantT> 1575hasDescendant(const internal::Matcher<DescendantT> &DescendantMatcher) { 1576 return internal::ArgumentAdaptingMatcher< 1577 internal::HasDescendantMatcher, 1578 DescendantT>(DescendantMatcher); 1579} 1580 1581/// \brief Matches AST nodes that have child AST nodes that match the 1582/// provided matcher. 1583/// 1584/// Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X"))) 1585/// \code 1586/// class X {}; // Matches X, because X::X is a class of name X inside X. 1587/// class Y { class X {}; }; 1588/// class Z { class Y { class X {}; }; }; // Does not match Z. 1589/// \endcode 1590/// 1591/// ChildT must be an AST base type. 1592/// 1593/// As opposed to 'has', 'forEach' will cause a match for each result that 1594/// matches instead of only on the first one. 1595/// 1596/// Usable as: Any Matcher 1597template <typename ChildT> 1598internal::ArgumentAdaptingMatcher<internal::ForEachMatcher, ChildT> forEach( 1599 const internal::Matcher<ChildT> &ChildMatcher) { 1600 return internal::ArgumentAdaptingMatcher< 1601 internal::ForEachMatcher, 1602 ChildT>(ChildMatcher); 1603} 1604 1605/// \brief Matches AST nodes that have descendant AST nodes that match the 1606/// provided matcher. 1607/// 1608/// Example matches X, A, B, C 1609/// (matcher = recordDecl(forEachDescendant(recordDecl(hasName("X"))))) 1610/// \code 1611/// class X {}; // Matches X, because X::X is a class of name X inside X. 1612/// class A { class X {}; }; 1613/// class B { class C { class X {}; }; }; 1614/// \endcode 1615/// 1616/// DescendantT must be an AST base type. 1617/// 1618/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for 1619/// each result that matches instead of only on the first one. 1620/// 1621/// Note: Recursively combined ForEachDescendant can cause many matches: 1622/// recordDecl(forEachDescendant(recordDecl(forEachDescendant(recordDecl())))) 1623/// will match 10 times (plus injected class name matches) on: 1624/// \code 1625/// class A { class B { class C { class D { class E {}; }; }; }; }; 1626/// \endcode 1627/// 1628/// Usable as: Any Matcher 1629template <typename DescendantT> 1630internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, 1631 DescendantT> 1632forEachDescendant( 1633 const internal::Matcher<DescendantT> &DescendantMatcher) { 1634 return internal::ArgumentAdaptingMatcher< 1635 internal::ForEachDescendantMatcher, 1636 DescendantT>(DescendantMatcher); 1637} 1638 1639/// \brief Matches if the node or any descendant matches. 1640/// 1641/// Generates results for each match. 1642/// 1643/// For example, in: 1644/// \code 1645/// class A { class B {}; class C {}; }; 1646/// \endcode 1647/// The matcher: 1648/// \code 1649/// recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("m"))) 1650/// \endcode 1651/// will generate results for \c A, \c B and \c C. 1652/// 1653/// Usable as: Any Matcher 1654template <typename T> 1655internal::PolymorphicMatcherWithParam2< 1656 internal::EachOfMatcher, internal::Matcher<T>, 1657 internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, T> > 1658findAll(const internal::Matcher<T> &Matcher) { 1659 return eachOf(Matcher, forEachDescendant(Matcher)); 1660} 1661 1662/// \brief Matches AST nodes that have a parent that matches the provided 1663/// matcher. 1664/// 1665/// Given 1666/// \code 1667/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } } 1668/// \endcode 1669/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }". 1670/// 1671/// Usable as: Any Matcher 1672template <typename ParentT> 1673internal::ArgumentAdaptingMatcher<internal::HasParentMatcher, ParentT> 1674hasParent(const internal::Matcher<ParentT> &ParentMatcher) { 1675 return internal::ArgumentAdaptingMatcher< 1676 internal::HasParentMatcher, 1677 ParentT>(ParentMatcher); 1678} 1679 1680/// \brief Matches AST nodes that have an ancestor that matches the provided 1681/// matcher. 1682/// 1683/// Given 1684/// \code 1685/// void f() { if (true) { int x = 42; } } 1686/// void g() { for (;;) { int x = 43; } } 1687/// \endcode 1688/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43. 1689/// 1690/// Usable as: Any Matcher 1691template <typename AncestorT> 1692internal::ArgumentAdaptingMatcher<internal::HasAncestorMatcher, AncestorT> 1693hasAncestor(const internal::Matcher<AncestorT> &AncestorMatcher) { 1694 return internal::ArgumentAdaptingMatcher< 1695 internal::HasAncestorMatcher, 1696 AncestorT>(AncestorMatcher); 1697} 1698 1699/// \brief Matches if the provided matcher does not match. 1700/// 1701/// Example matches Y (matcher = recordDecl(unless(hasName("X")))) 1702/// \code 1703/// class X {}; 1704/// class Y {}; 1705/// \endcode 1706/// 1707/// Usable as: Any Matcher 1708template <typename M> 1709internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M> 1710unless(const M &InnerMatcher) { 1711 return internal::PolymorphicMatcherWithParam1< 1712 internal::NotMatcher, M>(InnerMatcher); 1713} 1714 1715/// \brief Matches a node if the declaration associated with that node 1716/// matches the given matcher. 1717/// 1718/// The associated declaration is: 1719/// - for type nodes, the declaration of the underlying type 1720/// - for CallExpr, the declaration of the callee 1721/// - for MemberExpr, the declaration of the referenced member 1722/// - for CXXConstructExpr, the declaration of the constructor 1723/// 1724/// Also usable as Matcher<T> for any T supporting the getDecl() member 1725/// function. e.g. various subtypes of clang::Type and various expressions. 1726/// FIXME: Add all node types for which this is matcher is usable due to 1727/// getDecl(). 1728/// 1729/// Usable as: Matcher<QualType>, Matcher<CallExpr>, Matcher<CXXConstructExpr>, 1730/// Matcher<MemberExpr>, Matcher<TypedefType>, 1731/// Matcher<TemplateSpecializationType> 1732inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher, 1733 internal::Matcher<Decl> > 1734 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) { 1735 return internal::PolymorphicMatcherWithParam1< 1736 internal::HasDeclarationMatcher, 1737 internal::Matcher<Decl> >(InnerMatcher); 1738} 1739 1740/// \brief Matches on the implicit object argument of a member call expression. 1741/// 1742/// Example matches y.x() (matcher = callExpr(on(hasType(recordDecl(hasName("Y")))))) 1743/// \code 1744/// class Y { public: void x(); }; 1745/// void z() { Y y; y.x(); }", 1746/// \endcode 1747/// 1748/// FIXME: Overload to allow directly matching types? 1749AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>, 1750 InnerMatcher) { 1751 const Expr *ExprNode = Node.getImplicitObjectArgument() 1752 ->IgnoreParenImpCasts(); 1753 return (ExprNode != NULL && 1754 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1755} 1756 1757/// \brief Matches if the call expression's callee expression matches. 1758/// 1759/// Given 1760/// \code 1761/// class Y { void x() { this->x(); x(); Y y; y.x(); } }; 1762/// void f() { f(); } 1763/// \endcode 1764/// callExpr(callee(expr())) 1765/// matches this->x(), x(), y.x(), f() 1766/// with callee(...) 1767/// matching this->x, x, y.x, f respectively 1768/// 1769/// Note: Callee cannot take the more general internal::Matcher<Expr> 1770/// because this introduces ambiguous overloads with calls to Callee taking a 1771/// internal::Matcher<Decl>, as the matcher hierarchy is purely 1772/// implemented in terms of implicit casts. 1773AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>, 1774 InnerMatcher) { 1775 const Expr *ExprNode = Node.getCallee(); 1776 return (ExprNode != NULL && 1777 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1778} 1779 1780/// \brief Matches if the call expression's callee's declaration matches the 1781/// given matcher. 1782/// 1783/// Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x"))))) 1784/// \code 1785/// class Y { public: void x(); }; 1786/// void z() { Y y; y.x(); 1787/// \endcode 1788inline internal::Matcher<CallExpr> callee( 1789 const internal::Matcher<Decl> &InnerMatcher) { 1790 return callExpr(hasDeclaration(InnerMatcher)); 1791} 1792 1793/// \brief Matches if the expression's or declaration's type matches a type 1794/// matcher. 1795/// 1796/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) 1797/// and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) 1798/// \code 1799/// class X {}; 1800/// void y(X &x) { x; X z; } 1801/// \endcode 1802AST_POLYMORPHIC_MATCHER_P(hasType, 1803 AST_POLYMORPHIC_SUPPORTED_TYPES_2(Expr, ValueDecl), 1804 internal::Matcher<QualType>, InnerMatcher) { 1805 return InnerMatcher.matches(Node.getType(), Finder, Builder); 1806} 1807 1808/// \brief Overloaded to match the declaration of the expression's or value 1809/// declaration's type. 1810/// 1811/// In case of a value declaration (for example a variable declaration), 1812/// this resolves one layer of indirection. For example, in the value 1813/// declaration "X x;", recordDecl(hasName("X")) matches the declaration of X, 1814/// while varDecl(hasType(recordDecl(hasName("X")))) matches the declaration 1815/// of x." 1816/// 1817/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) 1818/// and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) 1819/// \code 1820/// class X {}; 1821/// void y(X &x) { x; X z; } 1822/// \endcode 1823/// 1824/// Usable as: Matcher<Expr>, Matcher<ValueDecl> 1825inline internal::PolymorphicMatcherWithParam1< 1826 internal::matcher_hasType0Matcher, internal::Matcher<QualType>, 1827 AST_POLYMORPHIC_SUPPORTED_TYPES_2(Expr, ValueDecl)> 1828hasType(const internal::Matcher<Decl> &InnerMatcher) { 1829 return hasType(qualType(hasDeclaration(InnerMatcher))); 1830} 1831 1832/// \brief Matches if the type location of the declarator decl's type matches 1833/// the inner matcher. 1834/// 1835/// Given 1836/// \code 1837/// int x; 1838/// \endcode 1839/// declaratorDecl(hasTypeLoc(loc(asString("int")))) 1840/// matches int x 1841AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) { 1842 if (!Node.getTypeSourceInfo()) 1843 // This happens for example for implicit destructors. 1844 return false; 1845 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder); 1846} 1847 1848/// \brief Matches if the matched type is represented by the given string. 1849/// 1850/// Given 1851/// \code 1852/// class Y { public: void x(); }; 1853/// void z() { Y* y; y->x(); } 1854/// \endcode 1855/// callExpr(on(hasType(asString("class Y *")))) 1856/// matches y->x() 1857AST_MATCHER_P(QualType, asString, std::string, Name) { 1858 return Name == Node.getAsString(); 1859} 1860 1861/// \brief Matches if the matched type is a pointer type and the pointee type 1862/// matches the specified matcher. 1863/// 1864/// Example matches y->x() 1865/// (matcher = callExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))))) 1866/// \code 1867/// class Y { public: void x(); }; 1868/// void z() { Y *y; y->x(); } 1869/// \endcode 1870AST_MATCHER_P( 1871 QualType, pointsTo, internal::Matcher<QualType>, 1872 InnerMatcher) { 1873 return (!Node.isNull() && Node->isPointerType() && 1874 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1875} 1876 1877/// \brief Overloaded to match the pointee type's declaration. 1878inline internal::Matcher<QualType> pointsTo( 1879 const internal::Matcher<Decl> &InnerMatcher) { 1880 return pointsTo(qualType(hasDeclaration(InnerMatcher))); 1881} 1882 1883/// \brief Matches if the matched type is a reference type and the referenced 1884/// type matches the specified matcher. 1885/// 1886/// Example matches X &x and const X &y 1887/// (matcher = varDecl(hasType(references(recordDecl(hasName("X")))))) 1888/// \code 1889/// class X { 1890/// void a(X b) { 1891/// X &x = b; 1892/// const X &y = b; 1893/// }; 1894/// \endcode 1895AST_MATCHER_P(QualType, references, internal::Matcher<QualType>, 1896 InnerMatcher) { 1897 return (!Node.isNull() && Node->isReferenceType() && 1898 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1899} 1900 1901/// \brief Matches QualTypes whose canonical type matches InnerMatcher. 1902/// 1903/// Given: 1904/// \code 1905/// typedef int &int_ref; 1906/// int a; 1907/// int_ref b = a; 1908/// \code 1909/// 1910/// \c varDecl(hasType(qualType(referenceType()))))) will not match the 1911/// declaration of b but \c 1912/// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does. 1913AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>, 1914 InnerMatcher) { 1915 if (Node.isNull()) 1916 return false; 1917 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder); 1918} 1919 1920/// \brief Overloaded to match the referenced type's declaration. 1921inline internal::Matcher<QualType> references( 1922 const internal::Matcher<Decl> &InnerMatcher) { 1923 return references(qualType(hasDeclaration(InnerMatcher))); 1924} 1925 1926AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument, 1927 internal::Matcher<Expr>, InnerMatcher) { 1928 const Expr *ExprNode = Node.getImplicitObjectArgument(); 1929 return (ExprNode != NULL && 1930 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1931} 1932 1933/// \brief Matches if the expression's type either matches the specified 1934/// matcher, or is a pointer to a type that matches the InnerMatcher. 1935inline internal::Matcher<CXXMemberCallExpr> thisPointerType( 1936 const internal::Matcher<QualType> &InnerMatcher) { 1937 return onImplicitObjectArgument( 1938 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 1939} 1940 1941/// \brief Overloaded to match the type's declaration. 1942inline internal::Matcher<CXXMemberCallExpr> thisPointerType( 1943 const internal::Matcher<Decl> &InnerMatcher) { 1944 return onImplicitObjectArgument( 1945 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 1946} 1947 1948/// \brief Matches a DeclRefExpr that refers to a declaration that matches the 1949/// specified matcher. 1950/// 1951/// Example matches x in if(x) 1952/// (matcher = declRefExpr(to(varDecl(hasName("x"))))) 1953/// \code 1954/// bool x; 1955/// if (x) {} 1956/// \endcode 1957AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>, 1958 InnerMatcher) { 1959 const Decl *DeclNode = Node.getDecl(); 1960 return (DeclNode != NULL && 1961 InnerMatcher.matches(*DeclNode, Finder, Builder)); 1962} 1963 1964/// \brief Matches a \c DeclRefExpr that refers to a declaration through a 1965/// specific using shadow declaration. 1966/// 1967/// FIXME: This currently only works for functions. Fix. 1968/// 1969/// Given 1970/// \code 1971/// namespace a { void f() {} } 1972/// using a::f; 1973/// void g() { 1974/// f(); // Matches this .. 1975/// a::f(); // .. but not this. 1976/// } 1977/// \endcode 1978/// declRefExpr(throughUsingDeclaration(anything())) 1979/// matches \c f() 1980AST_MATCHER_P(DeclRefExpr, throughUsingDecl, 1981 internal::Matcher<UsingShadowDecl>, InnerMatcher) { 1982 const NamedDecl *FoundDecl = Node.getFoundDecl(); 1983 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl)) 1984 return InnerMatcher.matches(*UsingDecl, Finder, Builder); 1985 return false; 1986} 1987 1988/// \brief Matches the Decl of a DeclStmt which has a single declaration. 1989/// 1990/// Given 1991/// \code 1992/// int a, b; 1993/// int c; 1994/// \endcode 1995/// declStmt(hasSingleDecl(anything())) 1996/// matches 'int c;' but not 'int a, b;'. 1997AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) { 1998 if (Node.isSingleDecl()) { 1999 const Decl *FoundDecl = Node.getSingleDecl(); 2000 return InnerMatcher.matches(*FoundDecl, Finder, Builder); 2001 } 2002 return false; 2003} 2004 2005/// \brief Matches a variable declaration that has an initializer expression 2006/// that matches the given matcher. 2007/// 2008/// Example matches x (matcher = varDecl(hasInitializer(callExpr()))) 2009/// \code 2010/// bool y() { return true; } 2011/// bool x = y(); 2012/// \endcode 2013AST_MATCHER_P( 2014 VarDecl, hasInitializer, internal::Matcher<Expr>, 2015 InnerMatcher) { 2016 const Expr *Initializer = Node.getAnyInitializer(); 2017 return (Initializer != NULL && 2018 InnerMatcher.matches(*Initializer, Finder, Builder)); 2019} 2020 2021/// \brief Checks that a call expression or a constructor call expression has 2022/// a specific number of arguments (including absent default arguments). 2023/// 2024/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2))) 2025/// \code 2026/// void f(int x, int y); 2027/// f(0, 0); 2028/// \endcode 2029AST_POLYMORPHIC_MATCHER_P(argumentCountIs, AST_POLYMORPHIC_SUPPORTED_TYPES_2( 2030 CallExpr, CXXConstructExpr), 2031 unsigned, N) { 2032 return Node.getNumArgs() == N; 2033} 2034 2035/// \brief Matches the n'th argument of a call expression or a constructor 2036/// call expression. 2037/// 2038/// Example matches y in x(y) 2039/// (matcher = callExpr(hasArgument(0, declRefExpr()))) 2040/// \code 2041/// void x(int) { int y; x(y); } 2042/// \endcode 2043AST_POLYMORPHIC_MATCHER_P2( 2044 hasArgument, 2045 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CallExpr, CXXConstructExpr), 2046 unsigned, N, internal::Matcher<Expr>, InnerMatcher) { 2047 return (N < Node.getNumArgs() && 2048 InnerMatcher.matches( 2049 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder)); 2050} 2051 2052/// \brief Matches declaration statements that contain a specific number of 2053/// declarations. 2054/// 2055/// Example: Given 2056/// \code 2057/// int a, b; 2058/// int c; 2059/// int d = 2, e; 2060/// \endcode 2061/// declCountIs(2) 2062/// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'. 2063AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) { 2064 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N; 2065} 2066 2067/// \brief Matches the n'th declaration of a declaration statement. 2068/// 2069/// Note that this does not work for global declarations because the AST 2070/// breaks up multiple-declaration DeclStmt's into multiple single-declaration 2071/// DeclStmt's. 2072/// Example: Given non-global declarations 2073/// \code 2074/// int a, b = 0; 2075/// int c; 2076/// int d = 2, e; 2077/// \endcode 2078/// declStmt(containsDeclaration( 2079/// 0, varDecl(hasInitializer(anything())))) 2080/// matches only 'int d = 2, e;', and 2081/// declStmt(containsDeclaration(1, varDecl())) 2082/// \code 2083/// matches 'int a, b = 0' as well as 'int d = 2, e;' 2084/// but 'int c;' is not matched. 2085/// \endcode 2086AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N, 2087 internal::Matcher<Decl>, InnerMatcher) { 2088 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end()); 2089 if (N >= NumDecls) 2090 return false; 2091 DeclStmt::const_decl_iterator Iterator = Node.decl_begin(); 2092 std::advance(Iterator, N); 2093 return InnerMatcher.matches(**Iterator, Finder, Builder); 2094} 2095 2096/// \brief Matches a constructor initializer. 2097/// 2098/// Given 2099/// \code 2100/// struct Foo { 2101/// Foo() : foo_(1) { } 2102/// int foo_; 2103/// }; 2104/// \endcode 2105/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything())))) 2106/// record matches Foo, hasAnyConstructorInitializer matches foo_(1) 2107AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer, 2108 internal::Matcher<CXXCtorInitializer>, InnerMatcher) { 2109 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(), 2110 Node.init_end(), Finder, Builder); 2111} 2112 2113/// \brief Matches the field declaration of a constructor initializer. 2114/// 2115/// Given 2116/// \code 2117/// struct Foo { 2118/// Foo() : foo_(1) { } 2119/// int foo_; 2120/// }; 2121/// \endcode 2122/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer( 2123/// forField(hasName("foo_")))))) 2124/// matches Foo 2125/// with forField matching foo_ 2126AST_MATCHER_P(CXXCtorInitializer, forField, 2127 internal::Matcher<FieldDecl>, InnerMatcher) { 2128 const FieldDecl *NodeAsDecl = Node.getMember(); 2129 return (NodeAsDecl != NULL && 2130 InnerMatcher.matches(*NodeAsDecl, Finder, Builder)); 2131} 2132 2133/// \brief Matches the initializer expression of a constructor initializer. 2134/// 2135/// Given 2136/// \code 2137/// struct Foo { 2138/// Foo() : foo_(1) { } 2139/// int foo_; 2140/// }; 2141/// \endcode 2142/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer( 2143/// withInitializer(integerLiteral(equals(1))))))) 2144/// matches Foo 2145/// with withInitializer matching (1) 2146AST_MATCHER_P(CXXCtorInitializer, withInitializer, 2147 internal::Matcher<Expr>, InnerMatcher) { 2148 const Expr* NodeAsExpr = Node.getInit(); 2149 return (NodeAsExpr != NULL && 2150 InnerMatcher.matches(*NodeAsExpr, Finder, Builder)); 2151} 2152 2153/// \brief Matches a contructor initializer if it is explicitly written in 2154/// code (as opposed to implicitly added by the compiler). 2155/// 2156/// Given 2157/// \code 2158/// struct Foo { 2159/// Foo() { } 2160/// Foo(int) : foo_("A") { } 2161/// string foo_; 2162/// }; 2163/// \endcode 2164/// constructorDecl(hasAnyConstructorInitializer(isWritten())) 2165/// will match Foo(int), but not Foo() 2166AST_MATCHER(CXXCtorInitializer, isWritten) { 2167 return Node.isWritten(); 2168} 2169 2170/// \brief Matches a constructor declaration that has been implicitly added 2171/// by the compiler (eg. implicit default/copy constructors). 2172AST_MATCHER(CXXConstructorDecl, isImplicit) { 2173 return Node.isImplicit(); 2174} 2175 2176/// \brief Matches any argument of a call expression or a constructor call 2177/// expression. 2178/// 2179/// Given 2180/// \code 2181/// void x(int, int, int) { int y; x(1, y, 42); } 2182/// \endcode 2183/// callExpr(hasAnyArgument(declRefExpr())) 2184/// matches x(1, y, 42) 2185/// with hasAnyArgument(...) 2186/// matching y 2187/// 2188/// FIXME: Currently this will ignore parentheses and implicit casts on 2189/// the argument before applying the inner matcher. We'll want to remove 2190/// this to allow for greater control by the user once \c ignoreImplicit() 2191/// has been implemented. 2192AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, AST_POLYMORPHIC_SUPPORTED_TYPES_2( 2193 CallExpr, CXXConstructExpr), 2194 internal::Matcher<Expr>, InnerMatcher) { 2195 for (unsigned I = 0; I < Node.getNumArgs(); ++I) { 2196 BoundNodesTreeBuilder Result(*Builder); 2197 if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(), Finder, 2198 &Result)) { 2199 *Builder = Result; 2200 return true; 2201 } 2202 } 2203 return false; 2204} 2205 2206/// \brief Matches the n'th parameter of a function declaration. 2207/// 2208/// Given 2209/// \code 2210/// class X { void f(int x) {} }; 2211/// \endcode 2212/// methodDecl(hasParameter(0, hasType(varDecl()))) 2213/// matches f(int x) {} 2214/// with hasParameter(...) 2215/// matching int x 2216AST_MATCHER_P2(FunctionDecl, hasParameter, 2217 unsigned, N, internal::Matcher<ParmVarDecl>, 2218 InnerMatcher) { 2219 return (N < Node.getNumParams() && 2220 InnerMatcher.matches( 2221 *Node.getParamDecl(N), Finder, Builder)); 2222} 2223 2224/// \brief Matches any parameter of a function declaration. 2225/// 2226/// Does not match the 'this' parameter of a method. 2227/// 2228/// Given 2229/// \code 2230/// class X { void f(int x, int y, int z) {} }; 2231/// \endcode 2232/// methodDecl(hasAnyParameter(hasName("y"))) 2233/// matches f(int x, int y, int z) {} 2234/// with hasAnyParameter(...) 2235/// matching int y 2236AST_MATCHER_P(FunctionDecl, hasAnyParameter, 2237 internal::Matcher<ParmVarDecl>, InnerMatcher) { 2238 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(), 2239 Node.param_end(), Finder, Builder); 2240} 2241 2242/// \brief Matches \c FunctionDecls that have a specific parameter count. 2243/// 2244/// Given 2245/// \code 2246/// void f(int i) {} 2247/// void g(int i, int j) {} 2248/// \endcode 2249/// functionDecl(parameterCountIs(2)) 2250/// matches g(int i, int j) {} 2251AST_MATCHER_P(FunctionDecl, parameterCountIs, unsigned, N) { 2252 return Node.getNumParams() == N; 2253} 2254 2255/// \brief Matches the return type of a function declaration. 2256/// 2257/// Given: 2258/// \code 2259/// class X { int f() { return 1; } }; 2260/// \endcode 2261/// methodDecl(returns(asString("int"))) 2262/// matches int f() { return 1; } 2263AST_MATCHER_P(FunctionDecl, returns, 2264 internal::Matcher<QualType>, InnerMatcher) { 2265 return InnerMatcher.matches(Node.getResultType(), Finder, Builder); 2266} 2267 2268/// \brief Matches extern "C" function declarations. 2269/// 2270/// Given: 2271/// \code 2272/// extern "C" void f() {} 2273/// extern "C" { void g() {} } 2274/// void h() {} 2275/// \endcode 2276/// functionDecl(isExternC()) 2277/// matches the declaration of f and g, but not the declaration h 2278AST_MATCHER(FunctionDecl, isExternC) { 2279 return Node.isExternC(); 2280} 2281 2282/// \brief Matches the condition expression of an if statement, for loop, 2283/// or conditional operator. 2284/// 2285/// Example matches true (matcher = hasCondition(boolLiteral(equals(true)))) 2286/// \code 2287/// if (true) {} 2288/// \endcode 2289AST_POLYMORPHIC_MATCHER_P( 2290 hasCondition, AST_POLYMORPHIC_SUPPORTED_TYPES_5( 2291 IfStmt, ForStmt, WhileStmt, DoStmt, ConditionalOperator), 2292 internal::Matcher<Expr>, InnerMatcher) { 2293 const Expr *const Condition = Node.getCond(); 2294 return (Condition != NULL && 2295 InnerMatcher.matches(*Condition, Finder, Builder)); 2296} 2297 2298namespace internal { 2299struct NotEqualsBoundNodePredicate { 2300 bool operator()(const internal::BoundNodesMap &Nodes) const { 2301 return Nodes.getNode(ID) != Node; 2302 } 2303 std::string ID; 2304 ast_type_traits::DynTypedNode Node; 2305}; 2306} // namespace internal 2307 2308/// \brief Matches if a node equals a previously bound node. 2309/// 2310/// Matches a node if it equals the node previously bound to \p ID. 2311/// 2312/// Given 2313/// \code 2314/// class X { int a; int b; }; 2315/// \endcode 2316/// recordDecl( 2317/// has(fieldDecl(hasName("a"), hasType(type().bind("t")))), 2318/// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t")))))) 2319/// matches the class \c X, as \c a and \c b have the same type. 2320/// 2321/// Note that when multiple matches are involved via \c forEach* matchers, 2322/// \c equalsBoundNodes acts as a filter. 2323/// For example: 2324/// compoundStmt( 2325/// forEachDescendant(varDecl().bind("d")), 2326/// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))) 2327/// will trigger a match for each combination of variable declaration 2328/// and reference to that variable declaration within a compound statement. 2329AST_POLYMORPHIC_MATCHER_P(equalsBoundNode, AST_POLYMORPHIC_SUPPORTED_TYPES_4( 2330 Stmt, Decl, Type, QualType), 2331 std::string, ID) { 2332 // FIXME: Figure out whether it makes sense to allow this 2333 // on any other node types. 2334 // For *Loc it probably does not make sense, as those seem 2335 // unique. For NestedNameSepcifier it might make sense, as 2336 // those also have pointer identity, but I'm not sure whether 2337 // they're ever reused. 2338 internal::NotEqualsBoundNodePredicate Predicate; 2339 Predicate.ID = ID; 2340 Predicate.Node = ast_type_traits::DynTypedNode::create(Node); 2341 return Builder->removeBindings(Predicate); 2342} 2343 2344/// \brief Matches the condition variable statement in an if statement. 2345/// 2346/// Given 2347/// \code 2348/// if (A* a = GetAPointer()) {} 2349/// \endcode 2350/// hasConditionVariableStatment(...) 2351/// matches 'A* a = GetAPointer()'. 2352AST_MATCHER_P(IfStmt, hasConditionVariableStatement, 2353 internal::Matcher<DeclStmt>, InnerMatcher) { 2354 const DeclStmt* const DeclarationStatement = 2355 Node.getConditionVariableDeclStmt(); 2356 return DeclarationStatement != NULL && 2357 InnerMatcher.matches(*DeclarationStatement, Finder, Builder); 2358} 2359 2360/// \brief Matches the index expression of an array subscript expression. 2361/// 2362/// Given 2363/// \code 2364/// int i[5]; 2365/// void f() { i[1] = 42; } 2366/// \endcode 2367/// arraySubscriptExpression(hasIndex(integerLiteral())) 2368/// matches \c i[1] with the \c integerLiteral() matching \c 1 2369AST_MATCHER_P(ArraySubscriptExpr, hasIndex, 2370 internal::Matcher<Expr>, InnerMatcher) { 2371 if (const Expr* Expression = Node.getIdx()) 2372 return InnerMatcher.matches(*Expression, Finder, Builder); 2373 return false; 2374} 2375 2376/// \brief Matches the base expression of an array subscript expression. 2377/// 2378/// Given 2379/// \code 2380/// int i[5]; 2381/// void f() { i[1] = 42; } 2382/// \endcode 2383/// arraySubscriptExpression(hasBase(implicitCastExpr( 2384/// hasSourceExpression(declRefExpr())))) 2385/// matches \c i[1] with the \c declRefExpr() matching \c i 2386AST_MATCHER_P(ArraySubscriptExpr, hasBase, 2387 internal::Matcher<Expr>, InnerMatcher) { 2388 if (const Expr* Expression = Node.getBase()) 2389 return InnerMatcher.matches(*Expression, Finder, Builder); 2390 return false; 2391} 2392 2393/// \brief Matches a 'for', 'while', or 'do while' statement that has 2394/// a given body. 2395/// 2396/// Given 2397/// \code 2398/// for (;;) {} 2399/// \endcode 2400/// hasBody(compoundStmt()) 2401/// matches 'for (;;) {}' 2402/// with compoundStmt() 2403/// matching '{}' 2404AST_POLYMORPHIC_MATCHER_P( 2405 hasBody, AST_POLYMORPHIC_SUPPORTED_TYPES_3(DoStmt, ForStmt, WhileStmt), 2406 internal::Matcher<Stmt>, InnerMatcher) { 2407 const Stmt *const Statement = Node.getBody(); 2408 return (Statement != NULL && 2409 InnerMatcher.matches(*Statement, Finder, Builder)); 2410} 2411 2412/// \brief Matches compound statements where at least one substatement matches 2413/// a given matcher. 2414/// 2415/// Given 2416/// \code 2417/// { {}; 1+2; } 2418/// \endcode 2419/// hasAnySubstatement(compoundStmt()) 2420/// matches '{ {}; 1+2; }' 2421/// with compoundStmt() 2422/// matching '{}' 2423AST_MATCHER_P(CompoundStmt, hasAnySubstatement, 2424 internal::Matcher<Stmt>, InnerMatcher) { 2425 return matchesFirstInPointerRange(InnerMatcher, Node.body_begin(), 2426 Node.body_end(), Finder, Builder); 2427} 2428 2429/// \brief Checks that a compound statement contains a specific number of 2430/// child statements. 2431/// 2432/// Example: Given 2433/// \code 2434/// { for (;;) {} } 2435/// \endcode 2436/// compoundStmt(statementCountIs(0))) 2437/// matches '{}' 2438/// but does not match the outer compound statement. 2439AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) { 2440 return Node.size() == N; 2441} 2442 2443/// \brief Matches literals that are equal to the given value. 2444/// 2445/// Example matches true (matcher = boolLiteral(equals(true))) 2446/// \code 2447/// true 2448/// \endcode 2449/// 2450/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>, 2451/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral> 2452template <typename ValueT> 2453internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT> 2454equals(const ValueT &Value) { 2455 return internal::PolymorphicMatcherWithParam1< 2456 internal::ValueEqualsMatcher, 2457 ValueT>(Value); 2458} 2459 2460/// \brief Matches the operator Name of operator expressions (binary or 2461/// unary). 2462/// 2463/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||"))) 2464/// \code 2465/// !(a || b) 2466/// \endcode 2467AST_POLYMORPHIC_MATCHER_P(hasOperatorName, AST_POLYMORPHIC_SUPPORTED_TYPES_2( 2468 BinaryOperator, UnaryOperator), 2469 std::string, Name) { 2470 return Name == Node.getOpcodeStr(Node.getOpcode()); 2471} 2472 2473/// \brief Matches the left hand side of binary operator expressions. 2474/// 2475/// Example matches a (matcher = binaryOperator(hasLHS())) 2476/// \code 2477/// a || b 2478/// \endcode 2479AST_MATCHER_P(BinaryOperator, hasLHS, 2480 internal::Matcher<Expr>, InnerMatcher) { 2481 Expr *LeftHandSide = Node.getLHS(); 2482 return (LeftHandSide != NULL && 2483 InnerMatcher.matches(*LeftHandSide, Finder, Builder)); 2484} 2485 2486/// \brief Matches the right hand side of binary operator expressions. 2487/// 2488/// Example matches b (matcher = binaryOperator(hasRHS())) 2489/// \code 2490/// a || b 2491/// \endcode 2492AST_MATCHER_P(BinaryOperator, hasRHS, 2493 internal::Matcher<Expr>, InnerMatcher) { 2494 Expr *RightHandSide = Node.getRHS(); 2495 return (RightHandSide != NULL && 2496 InnerMatcher.matches(*RightHandSide, Finder, Builder)); 2497} 2498 2499/// \brief Matches if either the left hand side or the right hand side of a 2500/// binary operator matches. 2501inline internal::Matcher<BinaryOperator> hasEitherOperand( 2502 const internal::Matcher<Expr> &InnerMatcher) { 2503 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)); 2504} 2505 2506/// \brief Matches if the operand of a unary operator matches. 2507/// 2508/// Example matches true (matcher = hasUnaryOperand(boolLiteral(equals(true)))) 2509/// \code 2510/// !true 2511/// \endcode 2512AST_MATCHER_P(UnaryOperator, hasUnaryOperand, 2513 internal::Matcher<Expr>, InnerMatcher) { 2514 const Expr * const Operand = Node.getSubExpr(); 2515 return (Operand != NULL && 2516 InnerMatcher.matches(*Operand, Finder, Builder)); 2517} 2518 2519/// \brief Matches if the cast's source expression matches the given matcher. 2520/// 2521/// Example: matches "a string" (matcher = 2522/// hasSourceExpression(constructExpr())) 2523/// \code 2524/// class URL { URL(string); }; 2525/// URL url = "a string"; 2526AST_MATCHER_P(CastExpr, hasSourceExpression, 2527 internal::Matcher<Expr>, InnerMatcher) { 2528 const Expr* const SubExpression = Node.getSubExpr(); 2529 return (SubExpression != NULL && 2530 InnerMatcher.matches(*SubExpression, Finder, Builder)); 2531} 2532 2533/// \brief Matches casts whose destination type matches a given matcher. 2534/// 2535/// (Note: Clang's AST refers to other conversions as "casts" too, and calls 2536/// actual casts "explicit" casts.) 2537AST_MATCHER_P(ExplicitCastExpr, hasDestinationType, 2538 internal::Matcher<QualType>, InnerMatcher) { 2539 const QualType NodeType = Node.getTypeAsWritten(); 2540 return InnerMatcher.matches(NodeType, Finder, Builder); 2541} 2542 2543/// \brief Matches implicit casts whose destination type matches a given 2544/// matcher. 2545/// 2546/// FIXME: Unit test this matcher 2547AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType, 2548 internal::Matcher<QualType>, InnerMatcher) { 2549 return InnerMatcher.matches(Node.getType(), Finder, Builder); 2550} 2551 2552/// \brief Matches the true branch expression of a conditional operator. 2553/// 2554/// Example matches a 2555/// \code 2556/// condition ? a : b 2557/// \endcode 2558AST_MATCHER_P(ConditionalOperator, hasTrueExpression, 2559 internal::Matcher<Expr>, InnerMatcher) { 2560 Expr *Expression = Node.getTrueExpr(); 2561 return (Expression != NULL && 2562 InnerMatcher.matches(*Expression, Finder, Builder)); 2563} 2564 2565/// \brief Matches the false branch expression of a conditional operator. 2566/// 2567/// Example matches b 2568/// \code 2569/// condition ? a : b 2570/// \endcode 2571AST_MATCHER_P(ConditionalOperator, hasFalseExpression, 2572 internal::Matcher<Expr>, InnerMatcher) { 2573 Expr *Expression = Node.getFalseExpr(); 2574 return (Expression != NULL && 2575 InnerMatcher.matches(*Expression, Finder, Builder)); 2576} 2577 2578/// \brief Matches if a declaration has a body attached. 2579/// 2580/// Example matches A, va, fa 2581/// \code 2582/// class A {}; 2583/// class B; // Doesn't match, as it has no body. 2584/// int va; 2585/// extern int vb; // Doesn't match, as it doesn't define the variable. 2586/// void fa() {} 2587/// void fb(); // Doesn't match, as it has no body. 2588/// \endcode 2589/// 2590/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl> 2591AST_POLYMORPHIC_MATCHER(isDefinition, AST_POLYMORPHIC_SUPPORTED_TYPES_3( 2592 TagDecl, VarDecl, FunctionDecl)) { 2593 return Node.isThisDeclarationADefinition(); 2594} 2595 2596/// \brief Matches the class declaration that the given method declaration 2597/// belongs to. 2598/// 2599/// FIXME: Generalize this for other kinds of declarations. 2600/// FIXME: What other kind of declarations would we need to generalize 2601/// this to? 2602/// 2603/// Example matches A() in the last line 2604/// (matcher = constructExpr(hasDeclaration(methodDecl( 2605/// ofClass(hasName("A")))))) 2606/// \code 2607/// class A { 2608/// public: 2609/// A(); 2610/// }; 2611/// A a = A(); 2612/// \endcode 2613AST_MATCHER_P(CXXMethodDecl, ofClass, 2614 internal::Matcher<CXXRecordDecl>, InnerMatcher) { 2615 const CXXRecordDecl *Parent = Node.getParent(); 2616 return (Parent != NULL && 2617 InnerMatcher.matches(*Parent, Finder, Builder)); 2618} 2619 2620/// \brief Matches if the given method declaration is virtual. 2621/// 2622/// Given 2623/// \code 2624/// class A { 2625/// public: 2626/// virtual void x(); 2627/// }; 2628/// \endcode 2629/// matches A::x 2630AST_MATCHER(CXXMethodDecl, isVirtual) { 2631 return Node.isVirtual(); 2632} 2633 2634/// \brief Matches if the given method declaration is const. 2635/// 2636/// Given 2637/// \code 2638/// struct A { 2639/// void foo() const; 2640/// void bar(); 2641/// }; 2642/// \endcode 2643/// 2644/// methodDecl(isConst()) matches A::foo() but not A::bar() 2645AST_MATCHER(CXXMethodDecl, isConst) { 2646 return Node.isConst(); 2647} 2648 2649/// \brief Matches if the given method declaration overrides another method. 2650/// 2651/// Given 2652/// \code 2653/// class A { 2654/// public: 2655/// virtual void x(); 2656/// }; 2657/// class B : public A { 2658/// public: 2659/// virtual void x(); 2660/// }; 2661/// \endcode 2662/// matches B::x 2663AST_MATCHER(CXXMethodDecl, isOverride) { 2664 return Node.size_overridden_methods() > 0; 2665} 2666 2667/// \brief Matches member expressions that are called with '->' as opposed 2668/// to '.'. 2669/// 2670/// Member calls on the implicit this pointer match as called with '->'. 2671/// 2672/// Given 2673/// \code 2674/// class Y { 2675/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 2676/// int a; 2677/// static int b; 2678/// }; 2679/// \endcode 2680/// memberExpr(isArrow()) 2681/// matches this->x, x, y.x, a, this->b 2682AST_MATCHER(MemberExpr, isArrow) { 2683 return Node.isArrow(); 2684} 2685 2686/// \brief Matches QualType nodes that are of integer type. 2687/// 2688/// Given 2689/// \code 2690/// void a(int); 2691/// void b(long); 2692/// void c(double); 2693/// \endcode 2694/// functionDecl(hasAnyParameter(hasType(isInteger()))) 2695/// matches "a(int)", "b(long)", but not "c(double)". 2696AST_MATCHER(QualType, isInteger) { 2697 return Node->isIntegerType(); 2698} 2699 2700/// \brief Matches QualType nodes that are const-qualified, i.e., that 2701/// include "top-level" const. 2702/// 2703/// Given 2704/// \code 2705/// void a(int); 2706/// void b(int const); 2707/// void c(const int); 2708/// void d(const int*); 2709/// void e(int const) {}; 2710/// \endcode 2711/// functionDecl(hasAnyParameter(hasType(isConstQualified()))) 2712/// matches "void b(int const)", "void c(const int)" and 2713/// "void e(int const) {}". It does not match d as there 2714/// is no top-level const on the parameter type "const int *". 2715AST_MATCHER(QualType, isConstQualified) { 2716 return Node.isConstQualified(); 2717} 2718 2719/// \brief Matches QualType nodes that have local CV-qualifiers attached to 2720/// the node, not hidden within a typedef. 2721/// 2722/// Given 2723/// \code 2724/// typedef const int const_int; 2725/// const_int i; 2726/// int *const j; 2727/// int *volatile k; 2728/// int m; 2729/// \endcode 2730/// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k. 2731/// \c i is const-qualified but the qualifier is not local. 2732AST_MATCHER(QualType, hasLocalQualifiers) { 2733 return Node.hasLocalQualifiers(); 2734} 2735 2736/// \brief Matches a member expression where the member is matched by a 2737/// given matcher. 2738/// 2739/// Given 2740/// \code 2741/// struct { int first, second; } first, second; 2742/// int i(second.first); 2743/// int j(first.second); 2744/// \endcode 2745/// memberExpr(member(hasName("first"))) 2746/// matches second.first 2747/// but not first.second (because the member name there is "second"). 2748AST_MATCHER_P(MemberExpr, member, 2749 internal::Matcher<ValueDecl>, InnerMatcher) { 2750 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder); 2751} 2752 2753/// \brief Matches a member expression where the object expression is 2754/// matched by a given matcher. 2755/// 2756/// Given 2757/// \code 2758/// struct X { int m; }; 2759/// void f(X x) { x.m; m; } 2760/// \endcode 2761/// memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X"))))))) 2762/// matches "x.m" and "m" 2763/// with hasObjectExpression(...) 2764/// matching "x" and the implicit object expression of "m" which has type X*. 2765AST_MATCHER_P(MemberExpr, hasObjectExpression, 2766 internal::Matcher<Expr>, InnerMatcher) { 2767 return InnerMatcher.matches(*Node.getBase(), Finder, Builder); 2768} 2769 2770/// \brief Matches any using shadow declaration. 2771/// 2772/// Given 2773/// \code 2774/// namespace X { void b(); } 2775/// using X::b; 2776/// \endcode 2777/// usingDecl(hasAnyUsingShadowDecl(hasName("b")))) 2778/// matches \code using X::b \endcode 2779AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl, 2780 internal::Matcher<UsingShadowDecl>, InnerMatcher) { 2781 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(), 2782 Node.shadow_end(), Finder, Builder); 2783} 2784 2785/// \brief Matches a using shadow declaration where the target declaration is 2786/// matched by the given matcher. 2787/// 2788/// Given 2789/// \code 2790/// namespace X { int a; void b(); } 2791/// using X::a; 2792/// using X::b; 2793/// \endcode 2794/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl()))) 2795/// matches \code using X::b \endcode 2796/// but not \code using X::a \endcode 2797AST_MATCHER_P(UsingShadowDecl, hasTargetDecl, 2798 internal::Matcher<NamedDecl>, InnerMatcher) { 2799 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder); 2800} 2801 2802/// \brief Matches template instantiations of function, class, or static 2803/// member variable template instantiations. 2804/// 2805/// Given 2806/// \code 2807/// template <typename T> class X {}; class A {}; X<A> x; 2808/// \endcode 2809/// or 2810/// \code 2811/// template <typename T> class X {}; class A {}; template class X<A>; 2812/// \endcode 2813/// recordDecl(hasName("::X"), isTemplateInstantiation()) 2814/// matches the template instantiation of X<A>. 2815/// 2816/// But given 2817/// \code 2818/// template <typename T> class X {}; class A {}; 2819/// template <> class X<A> {}; X<A> x; 2820/// \endcode 2821/// recordDecl(hasName("::X"), isTemplateInstantiation()) 2822/// does not match, as X<A> is an explicit template specialization. 2823/// 2824/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> 2825AST_POLYMORPHIC_MATCHER( 2826 isTemplateInstantiation, 2827 AST_POLYMORPHIC_SUPPORTED_TYPES_3(FunctionDecl, VarDecl, CXXRecordDecl)) { 2828 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation || 2829 Node.getTemplateSpecializationKind() == 2830 TSK_ExplicitInstantiationDefinition); 2831} 2832 2833/// \brief Matches explicit template specializations of function, class, or 2834/// static member variable template instantiations. 2835/// 2836/// Given 2837/// \code 2838/// template<typename T> void A(T t) { } 2839/// template<> void A(int N) { } 2840/// \endcode 2841/// functionDecl(isExplicitTemplateSpecialization()) 2842/// matches the specialization A<int>(). 2843/// 2844/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> 2845AST_POLYMORPHIC_MATCHER( 2846 isExplicitTemplateSpecialization, 2847 AST_POLYMORPHIC_SUPPORTED_TYPES_3(FunctionDecl, VarDecl, CXXRecordDecl)) { 2848 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization); 2849} 2850 2851/// \brief Matches \c TypeLocs for which the given inner 2852/// QualType-matcher matches. 2853inline internal::BindableMatcher<TypeLoc> loc( 2854 const internal::Matcher<QualType> &InnerMatcher) { 2855 return internal::BindableMatcher<TypeLoc>( 2856 new internal::TypeLocTypeMatcher(InnerMatcher)); 2857} 2858 2859/// \brief Matches builtin Types. 2860/// 2861/// Given 2862/// \code 2863/// struct A {}; 2864/// A a; 2865/// int b; 2866/// float c; 2867/// bool d; 2868/// \endcode 2869/// builtinType() 2870/// matches "int b", "float c" and "bool d" 2871AST_TYPE_MATCHER(BuiltinType, builtinType); 2872 2873/// \brief Matches all kinds of arrays. 2874/// 2875/// Given 2876/// \code 2877/// int a[] = { 2, 3 }; 2878/// int b[4]; 2879/// void f() { int c[a[0]]; } 2880/// \endcode 2881/// arrayType() 2882/// matches "int a[]", "int b[4]" and "int c[a[0]]"; 2883AST_TYPE_MATCHER(ArrayType, arrayType); 2884 2885/// \brief Matches C99 complex types. 2886/// 2887/// Given 2888/// \code 2889/// _Complex float f; 2890/// \endcode 2891/// complexType() 2892/// matches "_Complex float f" 2893AST_TYPE_MATCHER(ComplexType, complexType); 2894 2895/// \brief Matches arrays and C99 complex types that have a specific element 2896/// type. 2897/// 2898/// Given 2899/// \code 2900/// struct A {}; 2901/// A a[7]; 2902/// int b[7]; 2903/// \endcode 2904/// arrayType(hasElementType(builtinType())) 2905/// matches "int b[7]" 2906/// 2907/// Usable as: Matcher<ArrayType>, Matcher<ComplexType> 2908AST_TYPELOC_TRAVERSE_MATCHER( 2909 hasElementType, getElement, 2910 AST_POLYMORPHIC_SUPPORTED_TYPES_2(ArrayType, ComplexType)); 2911 2912/// \brief Matches C arrays with a specified constant size. 2913/// 2914/// Given 2915/// \code 2916/// void() { 2917/// int a[2]; 2918/// int b[] = { 2, 3 }; 2919/// int c[b[0]]; 2920/// } 2921/// \endcode 2922/// constantArrayType() 2923/// matches "int a[2]" 2924AST_TYPE_MATCHER(ConstantArrayType, constantArrayType); 2925 2926/// \brief Matches \c ConstantArrayType nodes that have the specified size. 2927/// 2928/// Given 2929/// \code 2930/// int a[42]; 2931/// int b[2 * 21]; 2932/// int c[41], d[43]; 2933/// \endcode 2934/// constantArrayType(hasSize(42)) 2935/// matches "int a[42]" and "int b[2 * 21]" 2936AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) { 2937 return Node.getSize() == N; 2938} 2939 2940/// \brief Matches C++ arrays whose size is a value-dependent expression. 2941/// 2942/// Given 2943/// \code 2944/// template<typename T, int Size> 2945/// class array { 2946/// T data[Size]; 2947/// }; 2948/// \endcode 2949/// dependentSizedArrayType 2950/// matches "T data[Size]" 2951AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType); 2952 2953/// \brief Matches C arrays with unspecified size. 2954/// 2955/// Given 2956/// \code 2957/// int a[] = { 2, 3 }; 2958/// int b[42]; 2959/// void f(int c[]) { int d[a[0]]; }; 2960/// \endcode 2961/// incompleteArrayType() 2962/// matches "int a[]" and "int c[]" 2963AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType); 2964 2965/// \brief Matches C arrays with a specified size that is not an 2966/// integer-constant-expression. 2967/// 2968/// Given 2969/// \code 2970/// void f() { 2971/// int a[] = { 2, 3 } 2972/// int b[42]; 2973/// int c[a[0]]; 2974/// \endcode 2975/// variableArrayType() 2976/// matches "int c[a[0]]" 2977AST_TYPE_MATCHER(VariableArrayType, variableArrayType); 2978 2979/// \brief Matches \c VariableArrayType nodes that have a specific size 2980/// expression. 2981/// 2982/// Given 2983/// \code 2984/// void f(int b) { 2985/// int a[b]; 2986/// } 2987/// \endcode 2988/// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to( 2989/// varDecl(hasName("b"))))))) 2990/// matches "int a[b]" 2991AST_MATCHER_P(VariableArrayType, hasSizeExpr, 2992 internal::Matcher<Expr>, InnerMatcher) { 2993 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder); 2994} 2995 2996/// \brief Matches atomic types. 2997/// 2998/// Given 2999/// \code 3000/// _Atomic(int) i; 3001/// \endcode 3002/// atomicType() 3003/// matches "_Atomic(int) i" 3004AST_TYPE_MATCHER(AtomicType, atomicType); 3005 3006/// \brief Matches atomic types with a specific value type. 3007/// 3008/// Given 3009/// \code 3010/// _Atomic(int) i; 3011/// _Atomic(float) f; 3012/// \endcode 3013/// atomicType(hasValueType(isInteger())) 3014/// matches "_Atomic(int) i" 3015/// 3016/// Usable as: Matcher<AtomicType> 3017AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue, 3018 AST_POLYMORPHIC_SUPPORTED_TYPES_1(AtomicType)); 3019 3020/// \brief Matches types nodes representing C++11 auto types. 3021/// 3022/// Given: 3023/// \code 3024/// auto n = 4; 3025/// int v[] = { 2, 3 } 3026/// for (auto i : v) { } 3027/// \endcode 3028/// autoType() 3029/// matches "auto n" and "auto i" 3030AST_TYPE_MATCHER(AutoType, autoType); 3031 3032/// \brief Matches \c AutoType nodes where the deduced type is a specific type. 3033/// 3034/// Note: There is no \c TypeLoc for the deduced type and thus no 3035/// \c getDeducedLoc() matcher. 3036/// 3037/// Given 3038/// \code 3039/// auto a = 1; 3040/// auto b = 2.0; 3041/// \endcode 3042/// autoType(hasDeducedType(isInteger())) 3043/// matches "auto a" 3044/// 3045/// Usable as: Matcher<AutoType> 3046AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType, 3047 AST_POLYMORPHIC_SUPPORTED_TYPES_1(AutoType)); 3048 3049/// \brief Matches \c FunctionType nodes. 3050/// 3051/// Given 3052/// \code 3053/// int (*f)(int); 3054/// void g(); 3055/// \endcode 3056/// functionType() 3057/// matches "int (*f)(int)" and the type of "g". 3058AST_TYPE_MATCHER(FunctionType, functionType); 3059 3060/// \brief Matches \c ParenType nodes. 3061/// 3062/// Given 3063/// \code 3064/// int (*ptr_to_array)[4]; 3065/// int *array_of_ptrs[4]; 3066/// \endcode 3067/// 3068/// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not 3069/// \c array_of_ptrs. 3070AST_TYPE_MATCHER(ParenType, parenType); 3071 3072/// \brief Matches \c ParenType nodes where the inner type is a specific type. 3073/// 3074/// Given 3075/// \code 3076/// int (*ptr_to_array)[4]; 3077/// int (*ptr_to_func)(int); 3078/// \endcode 3079/// 3080/// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches 3081/// \c ptr_to_func but not \c ptr_to_array. 3082/// 3083/// Usable as: Matcher<ParenType> 3084AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType, 3085 AST_POLYMORPHIC_SUPPORTED_TYPES_1(ParenType)); 3086 3087/// \brief Matches block pointer types, i.e. types syntactically represented as 3088/// "void (^)(int)". 3089/// 3090/// The \c pointee is always required to be a \c FunctionType. 3091AST_TYPE_MATCHER(BlockPointerType, blockPointerType); 3092 3093/// \brief Matches member pointer types. 3094/// Given 3095/// \code 3096/// struct A { int i; } 3097/// A::* ptr = A::i; 3098/// \endcode 3099/// memberPointerType() 3100/// matches "A::* ptr" 3101AST_TYPE_MATCHER(MemberPointerType, memberPointerType); 3102 3103/// \brief Matches pointer types. 3104/// 3105/// Given 3106/// \code 3107/// int *a; 3108/// int &b = *a; 3109/// int c = 5; 3110/// \endcode 3111/// pointerType() 3112/// matches "int *a" 3113AST_TYPE_MATCHER(PointerType, pointerType); 3114 3115/// \brief Matches both lvalue and rvalue reference types. 3116/// 3117/// Given 3118/// \code 3119/// int *a; 3120/// int &b = *a; 3121/// int &&c = 1; 3122/// auto &d = b; 3123/// auto &&e = c; 3124/// auto &&f = 2; 3125/// int g = 5; 3126/// \endcode 3127/// 3128/// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f. 3129AST_TYPE_MATCHER(ReferenceType, referenceType); 3130 3131/// \brief Matches lvalue reference types. 3132/// 3133/// Given: 3134/// \code 3135/// int *a; 3136/// int &b = *a; 3137/// int &&c = 1; 3138/// auto &d = b; 3139/// auto &&e = c; 3140/// auto &&f = 2; 3141/// int g = 5; 3142/// \endcode 3143/// 3144/// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is 3145/// matched since the type is deduced as int& by reference collapsing rules. 3146AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType); 3147 3148/// \brief Matches rvalue reference types. 3149/// 3150/// Given: 3151/// \code 3152/// int *a; 3153/// int &b = *a; 3154/// int &&c = 1; 3155/// auto &d = b; 3156/// auto &&e = c; 3157/// auto &&f = 2; 3158/// int g = 5; 3159/// \endcode 3160/// 3161/// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not 3162/// matched as it is deduced to int& by reference collapsing rules. 3163AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType); 3164 3165/// \brief Narrows PointerType (and similar) matchers to those where the 3166/// \c pointee matches a given matcher. 3167/// 3168/// Given 3169/// \code 3170/// int *a; 3171/// int const *b; 3172/// float const *f; 3173/// \endcode 3174/// pointerType(pointee(isConstQualified(), isInteger())) 3175/// matches "int const *b" 3176/// 3177/// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>, 3178/// Matcher<PointerType>, Matcher<ReferenceType> 3179AST_TYPELOC_TRAVERSE_MATCHER( 3180 pointee, getPointee, 3181 AST_POLYMORPHIC_SUPPORTED_TYPES_4(BlockPointerType, MemberPointerType, 3182 PointerType, ReferenceType)); 3183 3184/// \brief Matches typedef types. 3185/// 3186/// Given 3187/// \code 3188/// typedef int X; 3189/// \endcode 3190/// typedefType() 3191/// matches "typedef int X" 3192AST_TYPE_MATCHER(TypedefType, typedefType); 3193 3194/// \brief Matches template specialization types. 3195/// 3196/// Given 3197/// \code 3198/// template <typename T> 3199/// class C { }; 3200/// 3201/// template class C<int>; // A 3202/// C<char> var; // B 3203/// \code 3204/// 3205/// \c templateSpecializationType() matches the type of the explicit 3206/// instantiation in \c A and the type of the variable declaration in \c B. 3207AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType); 3208 3209/// \brief Matches types nodes representing unary type transformations. 3210/// 3211/// Given: 3212/// \code 3213/// typedef __underlying_type(T) type; 3214/// \endcode 3215/// unaryTransformType() 3216/// matches "__underlying_type(T)" 3217AST_TYPE_MATCHER(UnaryTransformType, unaryTransformType); 3218 3219/// \brief Matches record types (e.g. structs, classes). 3220/// 3221/// Given 3222/// \code 3223/// class C {}; 3224/// struct S {}; 3225/// 3226/// C c; 3227/// S s; 3228/// \code 3229/// 3230/// \c recordType() matches the type of the variable declarations of both \c c 3231/// and \c s. 3232AST_TYPE_MATCHER(RecordType, recordType); 3233 3234/// \brief Matches types specified with an elaborated type keyword or with a 3235/// qualified name. 3236/// 3237/// Given 3238/// \code 3239/// namespace N { 3240/// namespace M { 3241/// class D {}; 3242/// } 3243/// } 3244/// class C {}; 3245/// 3246/// class C c; 3247/// N::M::D d; 3248/// \code 3249/// 3250/// \c elaboratedType() matches the type of the variable declarations of both 3251/// \c c and \c d. 3252AST_TYPE_MATCHER(ElaboratedType, elaboratedType); 3253 3254/// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier, 3255/// matches \c InnerMatcher if the qualifier exists. 3256/// 3257/// Given 3258/// \code 3259/// namespace N { 3260/// namespace M { 3261/// class D {}; 3262/// } 3263/// } 3264/// N::M::D d; 3265/// \code 3266/// 3267/// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))) 3268/// matches the type of the variable declaration of \c d. 3269AST_MATCHER_P(ElaboratedType, hasQualifier, 3270 internal::Matcher<NestedNameSpecifier>, InnerMatcher) { 3271 if (const NestedNameSpecifier *Qualifier = Node.getQualifier()) 3272 return InnerMatcher.matches(*Qualifier, Finder, Builder); 3273 3274 return false; 3275} 3276 3277/// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher. 3278/// 3279/// Given 3280/// \code 3281/// namespace N { 3282/// namespace M { 3283/// class D {}; 3284/// } 3285/// } 3286/// N::M::D d; 3287/// \code 3288/// 3289/// \c elaboratedType(namesType(recordType( 3290/// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable 3291/// declaration of \c d. 3292AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>, 3293 InnerMatcher) { 3294 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder); 3295} 3296 3297/// \brief Matches declarations whose declaration context, interpreted as a 3298/// Decl, matches \c InnerMatcher. 3299/// 3300/// Given 3301/// \code 3302/// namespace N { 3303/// namespace M { 3304/// class D {}; 3305/// } 3306/// } 3307/// \code 3308/// 3309/// \c recordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the 3310/// declaration of \c class \c D. 3311AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) { 3312 return InnerMatcher.matches(*Decl::castFromDeclContext(Node.getDeclContext()), 3313 Finder, Builder); 3314} 3315 3316/// \brief Matches nested name specifiers. 3317/// 3318/// Given 3319/// \code 3320/// namespace ns { 3321/// struct A { static void f(); }; 3322/// void A::f() {} 3323/// void g() { A::f(); } 3324/// } 3325/// ns::A a; 3326/// \endcode 3327/// nestedNameSpecifier() 3328/// matches "ns::" and both "A::" 3329const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier; 3330 3331/// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc. 3332const internal::VariadicAllOfMatcher< 3333 NestedNameSpecifierLoc> nestedNameSpecifierLoc; 3334 3335/// \brief Matches \c NestedNameSpecifierLocs for which the given inner 3336/// NestedNameSpecifier-matcher matches. 3337inline internal::BindableMatcher<NestedNameSpecifierLoc> loc( 3338 const internal::Matcher<NestedNameSpecifier> &InnerMatcher) { 3339 return internal::BindableMatcher<NestedNameSpecifierLoc>( 3340 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>( 3341 InnerMatcher)); 3342} 3343 3344/// \brief Matches nested name specifiers that specify a type matching the 3345/// given \c QualType matcher without qualifiers. 3346/// 3347/// Given 3348/// \code 3349/// struct A { struct B { struct C {}; }; }; 3350/// A::B::C c; 3351/// \endcode 3352/// nestedNameSpecifier(specifiesType(hasDeclaration(recordDecl(hasName("A"))))) 3353/// matches "A::" 3354AST_MATCHER_P(NestedNameSpecifier, specifiesType, 3355 internal::Matcher<QualType>, InnerMatcher) { 3356 if (Node.getAsType() == NULL) 3357 return false; 3358 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder); 3359} 3360 3361/// \brief Matches nested name specifier locs that specify a type matching the 3362/// given \c TypeLoc. 3363/// 3364/// Given 3365/// \code 3366/// struct A { struct B { struct C {}; }; }; 3367/// A::B::C c; 3368/// \endcode 3369/// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type( 3370/// hasDeclaration(recordDecl(hasName("A"))))))) 3371/// matches "A::" 3372AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc, 3373 internal::Matcher<TypeLoc>, InnerMatcher) { 3374 return InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder); 3375} 3376 3377/// \brief Matches on the prefix of a \c NestedNameSpecifier. 3378/// 3379/// Given 3380/// \code 3381/// struct A { struct B { struct C {}; }; }; 3382/// A::B::C c; 3383/// \endcode 3384/// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and 3385/// matches "A::" 3386AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix, 3387 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 3388 0) { 3389 NestedNameSpecifier *NextNode = Node.getPrefix(); 3390 if (NextNode == NULL) 3391 return false; 3392 return InnerMatcher.matches(*NextNode, Finder, Builder); 3393} 3394 3395/// \brief Matches on the prefix of a \c NestedNameSpecifierLoc. 3396/// 3397/// Given 3398/// \code 3399/// struct A { struct B { struct C {}; }; }; 3400/// A::B::C c; 3401/// \endcode 3402/// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A"))))) 3403/// matches "A::" 3404AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix, 3405 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher, 3406 1) { 3407 NestedNameSpecifierLoc NextNode = Node.getPrefix(); 3408 if (!NextNode) 3409 return false; 3410 return InnerMatcher.matches(NextNode, Finder, Builder); 3411} 3412 3413/// \brief Matches nested name specifiers that specify a namespace matching the 3414/// given namespace matcher. 3415/// 3416/// Given 3417/// \code 3418/// namespace ns { struct A {}; } 3419/// ns::A a; 3420/// \endcode 3421/// nestedNameSpecifier(specifiesNamespace(hasName("ns"))) 3422/// matches "ns::" 3423AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace, 3424 internal::Matcher<NamespaceDecl>, InnerMatcher) { 3425 if (Node.getAsNamespace() == NULL) 3426 return false; 3427 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder); 3428} 3429 3430/// \brief Overloads for the \c equalsNode matcher. 3431/// FIXME: Implement for other node types. 3432/// @{ 3433 3434/// \brief Matches if a node equals another node. 3435/// 3436/// \c Decl has pointer identity in the AST. 3437AST_MATCHER_P_OVERLOAD(Decl, equalsNode, Decl*, Other, 0) { 3438 return &Node == Other; 3439} 3440/// \brief Matches if a node equals another node. 3441/// 3442/// \c Stmt has pointer identity in the AST. 3443/// 3444AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, Stmt*, Other, 1) { 3445 return &Node == Other; 3446} 3447 3448/// @} 3449 3450/// \brief Matches each case or default statement belonging to the given switch 3451/// statement. This matcher may produce multiple matches. 3452/// 3453/// Given 3454/// \code 3455/// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } } 3456/// \endcode 3457/// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s") 3458/// matches four times, with "c" binding each of "case 1:", "case 2:", 3459/// "case 3:" and "case 4:", and "s" respectively binding "switch (1)", 3460/// "switch (1)", "switch (2)" and "switch (2)". 3461AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>, 3462 InnerMatcher) { 3463 BoundNodesTreeBuilder Result; 3464 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable 3465 // iteration order. We should use the more general iterating matchers once 3466 // they are capable of expressing this matcher (for example, it should ignore 3467 // case statements belonging to nested switch statements). 3468 bool Matched = false; 3469 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC; 3470 SC = SC->getNextSwitchCase()) { 3471 BoundNodesTreeBuilder CaseBuilder(*Builder); 3472 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder); 3473 if (CaseMatched) { 3474 Matched = true; 3475 Result.addMatch(CaseBuilder); 3476 } 3477 } 3478 *Builder = Result; 3479 return Matched; 3480} 3481 3482/// \brief If the given case statement does not use the GNU case range 3483/// extension, matches the constant given in the statement. 3484/// 3485/// Given 3486/// \code 3487/// switch (1) { case 1: case 1+1: case 3 ... 4: ; } 3488/// \endcode 3489/// caseStmt(hasCaseConstant(integerLiteral())) 3490/// matches "case 1:" 3491AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>, 3492 InnerMatcher) { 3493 if (Node.getRHS()) 3494 return false; 3495 3496 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder); 3497} 3498 3499} // end namespace ast_matchers 3500} // end namespace clang 3501 3502#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H 3503