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