ASTMatchers.h revision f3197e9eb02120522c1f60f88dacc1cfe5b210f0
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, such as "<<", for OverloadedOperatorCall's. 1388/// 1389/// Example matches a << b 1390/// (matcher == operatorCallExpr(hasOverloadedOperatorName("<<"))) 1391/// \code 1392/// a << b; 1393/// c && d; // assuming both operator<< 1394/// // and operator&& are overloaded somewhere. 1395/// \endcode 1396AST_MATCHER_P(CXXOperatorCallExpr, 1397 hasOverloadedOperatorName, std::string, Name) { 1398 return getOperatorSpelling(Node.getOperator()) == Name; 1399} 1400 1401/// \brief Matches C++ classes that are directly or indirectly derived from 1402/// a class matching \c Base. 1403/// 1404/// Note that a class is not considered to be derived from itself. 1405/// 1406/// Example matches Y, Z, C (Base == hasName("X")) 1407/// \code 1408/// class X; 1409/// class Y : public X {}; // directly derived 1410/// class Z : public Y {}; // indirectly derived 1411/// typedef X A; 1412/// typedef A B; 1413/// class C : public B {}; // derived from a typedef of X 1414/// \endcode 1415/// 1416/// In the following example, Bar matches isDerivedFrom(hasName("X")): 1417/// \code 1418/// class Foo; 1419/// typedef Foo X; 1420/// class Bar : public Foo {}; // derived from a type that X is a typedef of 1421/// \endcode 1422AST_MATCHER_P(CXXRecordDecl, isDerivedFrom, 1423 internal::Matcher<NamedDecl>, Base) { 1424 return Finder->classIsDerivedFrom(&Node, Base, Builder); 1425} 1426 1427/// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)). 1428inline internal::Matcher<CXXRecordDecl> isDerivedFrom(StringRef BaseName) { 1429 assert(!BaseName.empty()); 1430 return isDerivedFrom(hasName(BaseName)); 1431} 1432 1433/// \brief Similar to \c isDerivedFrom(), but also matches classes that directly 1434/// match \c Base. 1435inline internal::Matcher<CXXRecordDecl> isSameOrDerivedFrom( 1436 internal::Matcher<NamedDecl> Base) { 1437 return anyOf(Base, isDerivedFrom(Base)); 1438} 1439 1440/// \brief Overloaded method as shortcut for 1441/// \c isSameOrDerivedFrom(hasName(...)). 1442inline internal::Matcher<CXXRecordDecl> isSameOrDerivedFrom( 1443 StringRef BaseName) { 1444 assert(!BaseName.empty()); 1445 return isSameOrDerivedFrom(hasName(BaseName)); 1446} 1447 1448/// \brief Matches AST nodes that have child AST nodes that match the 1449/// provided matcher. 1450/// 1451/// Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X"))) 1452/// \code 1453/// class X {}; // Matches X, because X::X is a class of name X inside X. 1454/// class Y { class X {}; }; 1455/// class Z { class Y { class X {}; }; }; // Does not match Z. 1456/// \endcode 1457/// 1458/// ChildT must be an AST base type. 1459/// 1460/// Usable as: Any Matcher 1461template <typename ChildT> 1462internal::ArgumentAdaptingMatcher<internal::HasMatcher, ChildT> has( 1463 const internal::Matcher<ChildT> &ChildMatcher) { 1464 return internal::ArgumentAdaptingMatcher<internal::HasMatcher, 1465 ChildT>(ChildMatcher); 1466} 1467 1468/// \brief Matches AST nodes that have descendant AST nodes that match the 1469/// provided matcher. 1470/// 1471/// Example matches X, Y, Z 1472/// (matcher = recordDecl(hasDescendant(recordDecl(hasName("X"))))) 1473/// \code 1474/// class X {}; // Matches X, because X::X is a class of name X inside X. 1475/// class Y { class X {}; }; 1476/// class Z { class Y { class X {}; }; }; 1477/// \endcode 1478/// 1479/// DescendantT must be an AST base type. 1480/// 1481/// Usable as: Any Matcher 1482template <typename DescendantT> 1483internal::ArgumentAdaptingMatcher<internal::HasDescendantMatcher, DescendantT> 1484hasDescendant(const internal::Matcher<DescendantT> &DescendantMatcher) { 1485 return internal::ArgumentAdaptingMatcher< 1486 internal::HasDescendantMatcher, 1487 DescendantT>(DescendantMatcher); 1488} 1489 1490/// \brief Matches AST nodes that have child AST nodes that match the 1491/// provided matcher. 1492/// 1493/// Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X"))) 1494/// \code 1495/// class X {}; // Matches X, because X::X is a class of name X inside X. 1496/// class Y { class X {}; }; 1497/// class Z { class Y { class X {}; }; }; // Does not match Z. 1498/// \endcode 1499/// 1500/// ChildT must be an AST base type. 1501/// 1502/// As opposed to 'has', 'forEach' will cause a match for each result that 1503/// matches instead of only on the first one. 1504/// 1505/// Usable as: Any Matcher 1506template <typename ChildT> 1507internal::ArgumentAdaptingMatcher<internal::ForEachMatcher, ChildT> forEach( 1508 const internal::Matcher<ChildT> &ChildMatcher) { 1509 return internal::ArgumentAdaptingMatcher< 1510 internal::ForEachMatcher, 1511 ChildT>(ChildMatcher); 1512} 1513 1514/// \brief Matches AST nodes that have descendant AST nodes that match the 1515/// provided matcher. 1516/// 1517/// Example matches X, A, B, C 1518/// (matcher = recordDecl(forEachDescendant(recordDecl(hasName("X"))))) 1519/// \code 1520/// class X {}; // Matches X, because X::X is a class of name X inside X. 1521/// class A { class X {}; }; 1522/// class B { class C { class X {}; }; }; 1523/// \endcode 1524/// 1525/// DescendantT must be an AST base type. 1526/// 1527/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for 1528/// each result that matches instead of only on the first one. 1529/// 1530/// Note: Recursively combined ForEachDescendant can cause many matches: 1531/// recordDecl(forEachDescendant(recordDecl(forEachDescendant(recordDecl())))) 1532/// will match 10 times (plus injected class name matches) on: 1533/// \code 1534/// class A { class B { class C { class D { class E {}; }; }; }; }; 1535/// \endcode 1536/// 1537/// Usable as: Any Matcher 1538template <typename DescendantT> 1539internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, 1540 DescendantT> 1541forEachDescendant( 1542 const internal::Matcher<DescendantT> &DescendantMatcher) { 1543 return internal::ArgumentAdaptingMatcher< 1544 internal::ForEachDescendantMatcher, 1545 DescendantT>(DescendantMatcher); 1546} 1547 1548/// \brief Matches if the node or any descendant matches. 1549/// 1550/// Generates results for each match. 1551/// 1552/// For example, in: 1553/// \code 1554/// class A { class B {}; class C {}; }; 1555/// \endcode 1556/// The matcher: 1557/// \code 1558/// recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("m"))) 1559/// \endcode 1560/// will generate results for \c A, \c B and \c C. 1561/// 1562/// Usable as: Any Matcher 1563template <typename T> 1564internal::PolymorphicMatcherWithParam2< 1565 internal::EachOfMatcher, internal::Matcher<T>, 1566 internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, T> > 1567findAll(const internal::Matcher<T> &Matcher) { 1568 return eachOf(Matcher, forEachDescendant(Matcher)); 1569} 1570 1571/// \brief Matches AST nodes that have a parent that matches the provided 1572/// matcher. 1573/// 1574/// Given 1575/// \code 1576/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } } 1577/// \endcode 1578/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }". 1579/// 1580/// Usable as: Any Matcher 1581template <typename ParentT> 1582internal::ArgumentAdaptingMatcher<internal::HasParentMatcher, ParentT> 1583hasParent(const internal::Matcher<ParentT> &ParentMatcher) { 1584 return internal::ArgumentAdaptingMatcher< 1585 internal::HasParentMatcher, 1586 ParentT>(ParentMatcher); 1587} 1588 1589/// \brief Matches AST nodes that have an ancestor that matches the provided 1590/// matcher. 1591/// 1592/// Given 1593/// \code 1594/// void f() { if (true) { int x = 42; } } 1595/// void g() { for (;;) { int x = 43; } } 1596/// \endcode 1597/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43. 1598/// 1599/// Usable as: Any Matcher 1600template <typename AncestorT> 1601internal::ArgumentAdaptingMatcher<internal::HasAncestorMatcher, AncestorT> 1602hasAncestor(const internal::Matcher<AncestorT> &AncestorMatcher) { 1603 return internal::ArgumentAdaptingMatcher< 1604 internal::HasAncestorMatcher, 1605 AncestorT>(AncestorMatcher); 1606} 1607 1608/// \brief Matches if the provided matcher does not match. 1609/// 1610/// Example matches Y (matcher = recordDecl(unless(hasName("X")))) 1611/// \code 1612/// class X {}; 1613/// class Y {}; 1614/// \endcode 1615/// 1616/// Usable as: Any Matcher 1617template <typename M> 1618internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M> 1619unless(const M &InnerMatcher) { 1620 return internal::PolymorphicMatcherWithParam1< 1621 internal::NotMatcher, M>(InnerMatcher); 1622} 1623 1624/// \brief Matches a type if the declaration of the type matches the given 1625/// matcher. 1626/// 1627/// In addition to being usable as Matcher<TypedefType>, also usable as 1628/// Matcher<T> for any T supporting the getDecl() member function. e.g. various 1629/// subtypes of clang::Type. 1630/// 1631/// Usable as: Matcher<QualType>, Matcher<CallExpr>, Matcher<CXXConstructExpr>, 1632/// Matcher<MemberExpr>, Matcher<TypedefType> 1633inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher, 1634 internal::Matcher<Decl> > 1635 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) { 1636 return internal::PolymorphicMatcherWithParam1< 1637 internal::HasDeclarationMatcher, 1638 internal::Matcher<Decl> >(InnerMatcher); 1639} 1640 1641/// \brief Matches on the implicit object argument of a member call expression. 1642/// 1643/// Example matches y.x() (matcher = callExpr(on(hasType(recordDecl(hasName("Y")))))) 1644/// \code 1645/// class Y { public: void x(); }; 1646/// void z() { Y y; y.x(); }", 1647/// \endcode 1648/// 1649/// FIXME: Overload to allow directly matching types? 1650AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>, 1651 InnerMatcher) { 1652 const Expr *ExprNode = Node.getImplicitObjectArgument() 1653 ->IgnoreParenImpCasts(); 1654 return (ExprNode != NULL && 1655 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1656} 1657 1658/// \brief Matches if the call expression's callee expression matches. 1659/// 1660/// Given 1661/// \code 1662/// class Y { void x() { this->x(); x(); Y y; y.x(); } }; 1663/// void f() { f(); } 1664/// \endcode 1665/// callExpr(callee(expr())) 1666/// matches this->x(), x(), y.x(), f() 1667/// with callee(...) 1668/// matching this->x, x, y.x, f respectively 1669/// 1670/// Note: Callee cannot take the more general internal::Matcher<Expr> 1671/// because this introduces ambiguous overloads with calls to Callee taking a 1672/// internal::Matcher<Decl>, as the matcher hierarchy is purely 1673/// implemented in terms of implicit casts. 1674AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>, 1675 InnerMatcher) { 1676 const Expr *ExprNode = Node.getCallee(); 1677 return (ExprNode != NULL && 1678 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1679} 1680 1681/// \brief Matches if the call expression's callee's declaration matches the 1682/// given matcher. 1683/// 1684/// Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x"))))) 1685/// \code 1686/// class Y { public: void x(); }; 1687/// void z() { Y y; y.x(); 1688/// \endcode 1689inline internal::Matcher<CallExpr> callee( 1690 const internal::Matcher<Decl> &InnerMatcher) { 1691 return callExpr(hasDeclaration(InnerMatcher)); 1692} 1693 1694/// \brief Matches if the expression's or declaration's type matches a type 1695/// matcher. 1696/// 1697/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) 1698/// and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) 1699/// \code 1700/// class X {}; 1701/// void y(X &x) { x; X z; } 1702/// \endcode 1703AST_POLYMORPHIC_MATCHER_P(hasType, internal::Matcher<QualType>, 1704 InnerMatcher) { 1705 TOOLING_COMPILE_ASSERT((llvm::is_base_of<Expr, NodeType>::value || 1706 llvm::is_base_of<ValueDecl, NodeType>::value), 1707 instantiated_with_wrong_types); 1708 return InnerMatcher.matches(Node.getType(), Finder, Builder); 1709} 1710 1711/// \brief Overloaded to match the declaration of the expression's or value 1712/// declaration's type. 1713/// 1714/// In case of a value declaration (for example a variable declaration), 1715/// this resolves one layer of indirection. For example, in the value 1716/// declaration "X x;", recordDecl(hasName("X")) matches the declaration of X, 1717/// while varDecl(hasType(recordDecl(hasName("X")))) matches the declaration 1718/// of x." 1719/// 1720/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) 1721/// and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) 1722/// \code 1723/// class X {}; 1724/// void y(X &x) { x; X z; } 1725/// \endcode 1726/// 1727/// Usable as: Matcher<Expr>, Matcher<ValueDecl> 1728inline internal::PolymorphicMatcherWithParam1< 1729 internal::matcher_hasType0Matcher, 1730 internal::Matcher<QualType> > 1731hasType(const internal::Matcher<Decl> &InnerMatcher) { 1732 return hasType(qualType(hasDeclaration(InnerMatcher))); 1733} 1734 1735/// \brief Matches if the matched type is represented by the given string. 1736/// 1737/// Given 1738/// \code 1739/// class Y { public: void x(); }; 1740/// void z() { Y* y; y->x(); } 1741/// \endcode 1742/// callExpr(on(hasType(asString("class Y *")))) 1743/// matches y->x() 1744AST_MATCHER_P(QualType, asString, std::string, Name) { 1745 return Name == Node.getAsString(); 1746} 1747 1748/// \brief Matches if the matched type is a pointer type and the pointee type 1749/// matches the specified matcher. 1750/// 1751/// Example matches y->x() 1752/// (matcher = callExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))))) 1753/// \code 1754/// class Y { public: void x(); }; 1755/// void z() { Y *y; y->x(); } 1756/// \endcode 1757AST_MATCHER_P( 1758 QualType, pointsTo, internal::Matcher<QualType>, 1759 InnerMatcher) { 1760 return (!Node.isNull() && Node->isPointerType() && 1761 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1762} 1763 1764/// \brief Overloaded to match the pointee type's declaration. 1765inline internal::Matcher<QualType> pointsTo( 1766 const internal::Matcher<Decl> &InnerMatcher) { 1767 return pointsTo(qualType(hasDeclaration(InnerMatcher))); 1768} 1769 1770/// \brief Matches if the matched type is a reference type and the referenced 1771/// type matches the specified matcher. 1772/// 1773/// Example matches X &x and const X &y 1774/// (matcher = varDecl(hasType(references(recordDecl(hasName("X")))))) 1775/// \code 1776/// class X { 1777/// void a(X b) { 1778/// X &x = b; 1779/// const X &y = b; 1780/// }; 1781/// \endcode 1782AST_MATCHER_P(QualType, references, internal::Matcher<QualType>, 1783 InnerMatcher) { 1784 return (!Node.isNull() && Node->isReferenceType() && 1785 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1786} 1787 1788/// \brief Overloaded to match the referenced type's declaration. 1789inline internal::Matcher<QualType> references( 1790 const internal::Matcher<Decl> &InnerMatcher) { 1791 return references(qualType(hasDeclaration(InnerMatcher))); 1792} 1793 1794AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument, 1795 internal::Matcher<Expr>, InnerMatcher) { 1796 const Expr *ExprNode = Node.getImplicitObjectArgument(); 1797 return (ExprNode != NULL && 1798 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1799} 1800 1801/// \brief Matches if the expression's type either matches the specified 1802/// matcher, or is a pointer to a type that matches the InnerMatcher. 1803inline internal::Matcher<CXXMemberCallExpr> thisPointerType( 1804 const internal::Matcher<QualType> &InnerMatcher) { 1805 return onImplicitObjectArgument( 1806 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 1807} 1808 1809/// \brief Overloaded to match the type's declaration. 1810inline internal::Matcher<CXXMemberCallExpr> thisPointerType( 1811 const internal::Matcher<Decl> &InnerMatcher) { 1812 return onImplicitObjectArgument( 1813 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 1814} 1815 1816/// \brief Matches a DeclRefExpr that refers to a declaration that matches the 1817/// specified matcher. 1818/// 1819/// Example matches x in if(x) 1820/// (matcher = declRefExpr(to(varDecl(hasName("x"))))) 1821/// \code 1822/// bool x; 1823/// if (x) {} 1824/// \endcode 1825AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>, 1826 InnerMatcher) { 1827 const Decl *DeclNode = Node.getDecl(); 1828 return (DeclNode != NULL && 1829 InnerMatcher.matches(*DeclNode, Finder, Builder)); 1830} 1831 1832/// \brief Matches a \c DeclRefExpr that refers to a declaration through a 1833/// specific using shadow declaration. 1834/// 1835/// FIXME: This currently only works for functions. Fix. 1836/// 1837/// Given 1838/// \code 1839/// namespace a { void f() {} } 1840/// using a::f; 1841/// void g() { 1842/// f(); // Matches this .. 1843/// a::f(); // .. but not this. 1844/// } 1845/// \endcode 1846/// declRefExpr(throughUsingDeclaration(anything())) 1847/// matches \c f() 1848AST_MATCHER_P(DeclRefExpr, throughUsingDecl, 1849 internal::Matcher<UsingShadowDecl>, InnerMatcher) { 1850 const NamedDecl *FoundDecl = Node.getFoundDecl(); 1851 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl)) 1852 return InnerMatcher.matches(*UsingDecl, Finder, Builder); 1853 return false; 1854} 1855 1856/// \brief Matches the Decl of a DeclStmt which has a single declaration. 1857/// 1858/// Given 1859/// \code 1860/// int a, b; 1861/// int c; 1862/// \endcode 1863/// declStmt(hasSingleDecl(anything())) 1864/// matches 'int c;' but not 'int a, b;'. 1865AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) { 1866 if (Node.isSingleDecl()) { 1867 const Decl *FoundDecl = Node.getSingleDecl(); 1868 return InnerMatcher.matches(*FoundDecl, Finder, Builder); 1869 } 1870 return false; 1871} 1872 1873/// \brief Matches a variable declaration that has an initializer expression 1874/// that matches the given matcher. 1875/// 1876/// Example matches x (matcher = varDecl(hasInitializer(callExpr()))) 1877/// \code 1878/// bool y() { return true; } 1879/// bool x = y(); 1880/// \endcode 1881AST_MATCHER_P( 1882 VarDecl, hasInitializer, internal::Matcher<Expr>, 1883 InnerMatcher) { 1884 const Expr *Initializer = Node.getAnyInitializer(); 1885 return (Initializer != NULL && 1886 InnerMatcher.matches(*Initializer, Finder, Builder)); 1887} 1888 1889/// \brief Checks that a call expression or a constructor call expression has 1890/// a specific number of arguments (including absent default arguments). 1891/// 1892/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2))) 1893/// \code 1894/// void f(int x, int y); 1895/// f(0, 0); 1896/// \endcode 1897AST_POLYMORPHIC_MATCHER_P(argumentCountIs, unsigned, N) { 1898 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 1899 llvm::is_base_of<CXXConstructExpr, 1900 NodeType>::value), 1901 instantiated_with_wrong_types); 1902 return Node.getNumArgs() == N; 1903} 1904 1905/// \brief Matches the n'th argument of a call expression or a constructor 1906/// call expression. 1907/// 1908/// Example matches y in x(y) 1909/// (matcher = callExpr(hasArgument(0, declRefExpr()))) 1910/// \code 1911/// void x(int) { int y; x(y); } 1912/// \endcode 1913AST_POLYMORPHIC_MATCHER_P2( 1914 hasArgument, unsigned, N, internal::Matcher<Expr>, InnerMatcher) { 1915 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 1916 llvm::is_base_of<CXXConstructExpr, 1917 NodeType>::value), 1918 instantiated_with_wrong_types); 1919 return (N < Node.getNumArgs() && 1920 InnerMatcher.matches( 1921 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder)); 1922} 1923 1924/// \brief Matches declaration statements that contain a specific number of 1925/// declarations. 1926/// 1927/// Example: Given 1928/// \code 1929/// int a, b; 1930/// int c; 1931/// int d = 2, e; 1932/// \endcode 1933/// declCountIs(2) 1934/// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'. 1935AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) { 1936 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N; 1937} 1938 1939/// \brief Matches the n'th declaration of a declaration statement. 1940/// 1941/// Note that this does not work for global declarations because the AST 1942/// breaks up multiple-declaration DeclStmt's into multiple single-declaration 1943/// DeclStmt's. 1944/// Example: Given non-global declarations 1945/// \code 1946/// int a, b = 0; 1947/// int c; 1948/// int d = 2, e; 1949/// \endcode 1950/// declStmt(containsDeclaration( 1951/// 0, varDecl(hasInitializer(anything())))) 1952/// matches only 'int d = 2, e;', and 1953/// declStmt(containsDeclaration(1, varDecl())) 1954/// \code 1955/// matches 'int a, b = 0' as well as 'int d = 2, e;' 1956/// but 'int c;' is not matched. 1957/// \endcode 1958AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N, 1959 internal::Matcher<Decl>, InnerMatcher) { 1960 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end()); 1961 if (N >= NumDecls) 1962 return false; 1963 DeclStmt::const_decl_iterator Iterator = Node.decl_begin(); 1964 std::advance(Iterator, N); 1965 return InnerMatcher.matches(**Iterator, Finder, Builder); 1966} 1967 1968/// \brief Matches a constructor initializer. 1969/// 1970/// Given 1971/// \code 1972/// struct Foo { 1973/// Foo() : foo_(1) { } 1974/// int foo_; 1975/// }; 1976/// \endcode 1977/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything())))) 1978/// record matches Foo, hasAnyConstructorInitializer matches foo_(1) 1979AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer, 1980 internal::Matcher<CXXCtorInitializer>, InnerMatcher) { 1981 for (CXXConstructorDecl::init_const_iterator I = Node.init_begin(); 1982 I != Node.init_end(); ++I) { 1983 if (InnerMatcher.matches(**I, Finder, Builder)) { 1984 return true; 1985 } 1986 } 1987 return false; 1988} 1989 1990/// \brief Matches the field declaration of a constructor initializer. 1991/// 1992/// Given 1993/// \code 1994/// struct Foo { 1995/// Foo() : foo_(1) { } 1996/// int foo_; 1997/// }; 1998/// \endcode 1999/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer( 2000/// forField(hasName("foo_")))))) 2001/// matches Foo 2002/// with forField matching foo_ 2003AST_MATCHER_P(CXXCtorInitializer, forField, 2004 internal::Matcher<FieldDecl>, InnerMatcher) { 2005 const FieldDecl *NodeAsDecl = Node.getMember(); 2006 return (NodeAsDecl != NULL && 2007 InnerMatcher.matches(*NodeAsDecl, Finder, Builder)); 2008} 2009 2010/// \brief Matches the initializer expression of a constructor initializer. 2011/// 2012/// Given 2013/// \code 2014/// struct Foo { 2015/// Foo() : foo_(1) { } 2016/// int foo_; 2017/// }; 2018/// \endcode 2019/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer( 2020/// withInitializer(integerLiteral(equals(1))))))) 2021/// matches Foo 2022/// with withInitializer matching (1) 2023AST_MATCHER_P(CXXCtorInitializer, withInitializer, 2024 internal::Matcher<Expr>, InnerMatcher) { 2025 const Expr* NodeAsExpr = Node.getInit(); 2026 return (NodeAsExpr != NULL && 2027 InnerMatcher.matches(*NodeAsExpr, Finder, Builder)); 2028} 2029 2030/// \brief Matches a contructor initializer if it is explicitly written in 2031/// code (as opposed to implicitly added by the compiler). 2032/// 2033/// Given 2034/// \code 2035/// struct Foo { 2036/// Foo() { } 2037/// Foo(int) : foo_("A") { } 2038/// string foo_; 2039/// }; 2040/// \endcode 2041/// constructorDecl(hasAnyConstructorInitializer(isWritten())) 2042/// will match Foo(int), but not Foo() 2043AST_MATCHER(CXXCtorInitializer, isWritten) { 2044 return Node.isWritten(); 2045} 2046 2047/// \brief Matches a constructor declaration that has been implicitly added 2048/// by the compiler (eg. implicit default/copy constructors). 2049AST_MATCHER(CXXConstructorDecl, isImplicit) { 2050 return Node.isImplicit(); 2051} 2052 2053/// \brief Matches any argument of a call expression or a constructor call 2054/// expression. 2055/// 2056/// Given 2057/// \code 2058/// void x(int, int, int) { int y; x(1, y, 42); } 2059/// \endcode 2060/// callExpr(hasAnyArgument(declRefExpr())) 2061/// matches x(1, y, 42) 2062/// with hasAnyArgument(...) 2063/// matching y 2064AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, internal::Matcher<Expr>, 2065 InnerMatcher) { 2066 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 2067 llvm::is_base_of<CXXConstructExpr, 2068 NodeType>::value), 2069 instantiated_with_wrong_types); 2070 for (unsigned I = 0; I < Node.getNumArgs(); ++I) { 2071 if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(), 2072 Finder, Builder)) { 2073 return true; 2074 } 2075 } 2076 return false; 2077} 2078 2079/// \brief Matches the n'th parameter of a function declaration. 2080/// 2081/// Given 2082/// \code 2083/// class X { void f(int x) {} }; 2084/// \endcode 2085/// methodDecl(hasParameter(0, hasType(varDecl()))) 2086/// matches f(int x) {} 2087/// with hasParameter(...) 2088/// matching int x 2089AST_MATCHER_P2(FunctionDecl, hasParameter, 2090 unsigned, N, internal::Matcher<ParmVarDecl>, 2091 InnerMatcher) { 2092 return (N < Node.getNumParams() && 2093 InnerMatcher.matches( 2094 *Node.getParamDecl(N), Finder, Builder)); 2095} 2096 2097/// \brief Matches any parameter of a function declaration. 2098/// 2099/// Does not match the 'this' parameter of a method. 2100/// 2101/// Given 2102/// \code 2103/// class X { void f(int x, int y, int z) {} }; 2104/// \endcode 2105/// methodDecl(hasAnyParameter(hasName("y"))) 2106/// matches f(int x, int y, int z) {} 2107/// with hasAnyParameter(...) 2108/// matching int y 2109AST_MATCHER_P(FunctionDecl, hasAnyParameter, 2110 internal::Matcher<ParmVarDecl>, InnerMatcher) { 2111 for (unsigned I = 0; I < Node.getNumParams(); ++I) { 2112 if (InnerMatcher.matches(*Node.getParamDecl(I), Finder, Builder)) { 2113 return true; 2114 } 2115 } 2116 return false; 2117} 2118 2119/// \brief Matches \c FunctionDecls that have a specific parameter count. 2120/// 2121/// Given 2122/// \code 2123/// void f(int i) {} 2124/// void g(int i, int j) {} 2125/// \endcode 2126/// functionDecl(parameterCountIs(2)) 2127/// matches g(int i, int j) {} 2128AST_MATCHER_P(FunctionDecl, parameterCountIs, unsigned, N) { 2129 return Node.getNumParams() == N; 2130} 2131 2132/// \brief Matches the return type of a function declaration. 2133/// 2134/// Given: 2135/// \code 2136/// class X { int f() { return 1; } }; 2137/// \endcode 2138/// methodDecl(returns(asString("int"))) 2139/// matches int f() { return 1; } 2140AST_MATCHER_P(FunctionDecl, returns, 2141 internal::Matcher<QualType>, InnerMatcher) { 2142 return InnerMatcher.matches(Node.getResultType(), Finder, Builder); 2143} 2144 2145/// \brief Matches extern "C" function declarations. 2146/// 2147/// Given: 2148/// \code 2149/// extern "C" void f() {} 2150/// extern "C" { void g() {} } 2151/// void h() {} 2152/// \endcode 2153/// functionDecl(isExternC()) 2154/// matches the declaration of f and g, but not the declaration h 2155AST_MATCHER(FunctionDecl, isExternC) { 2156 return Node.isExternC(); 2157} 2158 2159/// \brief Matches the condition expression of an if statement, for loop, 2160/// or conditional operator. 2161/// 2162/// Example matches true (matcher = hasCondition(boolLiteral(equals(true)))) 2163/// \code 2164/// if (true) {} 2165/// \endcode 2166AST_POLYMORPHIC_MATCHER_P(hasCondition, internal::Matcher<Expr>, 2167 InnerMatcher) { 2168 TOOLING_COMPILE_ASSERT( 2169 (llvm::is_base_of<IfStmt, NodeType>::value) || 2170 (llvm::is_base_of<ForStmt, NodeType>::value) || 2171 (llvm::is_base_of<WhileStmt, NodeType>::value) || 2172 (llvm::is_base_of<DoStmt, NodeType>::value) || 2173 (llvm::is_base_of<ConditionalOperator, NodeType>::value), 2174 has_condition_requires_if_statement_conditional_operator_or_loop); 2175 const Expr *const Condition = Node.getCond(); 2176 return (Condition != NULL && 2177 InnerMatcher.matches(*Condition, Finder, Builder)); 2178} 2179 2180/// \brief Matches the condition variable statement in an if statement. 2181/// 2182/// Given 2183/// \code 2184/// if (A* a = GetAPointer()) {} 2185/// \endcode 2186/// hasConditionVariableStatment(...) 2187/// matches 'A* a = GetAPointer()'. 2188AST_MATCHER_P(IfStmt, hasConditionVariableStatement, 2189 internal::Matcher<DeclStmt>, InnerMatcher) { 2190 const DeclStmt* const DeclarationStatement = 2191 Node.getConditionVariableDeclStmt(); 2192 return DeclarationStatement != NULL && 2193 InnerMatcher.matches(*DeclarationStatement, Finder, Builder); 2194} 2195 2196/// \brief Matches the index expression of an array subscript expression. 2197/// 2198/// Given 2199/// \code 2200/// int i[5]; 2201/// void f() { i[1] = 42; } 2202/// \endcode 2203/// arraySubscriptExpression(hasIndex(integerLiteral())) 2204/// matches \c i[1] with the \c integerLiteral() matching \c 1 2205AST_MATCHER_P(ArraySubscriptExpr, hasIndex, 2206 internal::Matcher<Expr>, InnerMatcher) { 2207 if (const Expr* Expression = Node.getIdx()) 2208 return InnerMatcher.matches(*Expression, Finder, Builder); 2209 return false; 2210} 2211 2212/// \brief Matches the base expression of an array subscript expression. 2213/// 2214/// Given 2215/// \code 2216/// int i[5]; 2217/// void f() { i[1] = 42; } 2218/// \endcode 2219/// arraySubscriptExpression(hasBase(implicitCastExpr( 2220/// hasSourceExpression(declRefExpr())))) 2221/// matches \c i[1] with the \c declRefExpr() matching \c i 2222AST_MATCHER_P(ArraySubscriptExpr, hasBase, 2223 internal::Matcher<Expr>, InnerMatcher) { 2224 if (const Expr* Expression = Node.getBase()) 2225 return InnerMatcher.matches(*Expression, Finder, Builder); 2226 return false; 2227} 2228 2229/// \brief Matches a 'for', 'while', or 'do while' statement that has 2230/// a given body. 2231/// 2232/// Given 2233/// \code 2234/// for (;;) {} 2235/// \endcode 2236/// hasBody(compoundStmt()) 2237/// matches 'for (;;) {}' 2238/// with compoundStmt() 2239/// matching '{}' 2240AST_POLYMORPHIC_MATCHER_P(hasBody, internal::Matcher<Stmt>, 2241 InnerMatcher) { 2242 TOOLING_COMPILE_ASSERT( 2243 (llvm::is_base_of<DoStmt, NodeType>::value) || 2244 (llvm::is_base_of<ForStmt, NodeType>::value) || 2245 (llvm::is_base_of<WhileStmt, NodeType>::value), 2246 has_body_requires_for_while_or_do_statement); 2247 const Stmt *const Statement = Node.getBody(); 2248 return (Statement != NULL && 2249 InnerMatcher.matches(*Statement, Finder, Builder)); 2250} 2251 2252/// \brief Matches compound statements where at least one substatement matches 2253/// a given matcher. 2254/// 2255/// Given 2256/// \code 2257/// { {}; 1+2; } 2258/// \endcode 2259/// hasAnySubstatement(compoundStmt()) 2260/// matches '{ {}; 1+2; }' 2261/// with compoundStmt() 2262/// matching '{}' 2263AST_MATCHER_P(CompoundStmt, hasAnySubstatement, 2264 internal::Matcher<Stmt>, InnerMatcher) { 2265 for (CompoundStmt::const_body_iterator It = Node.body_begin(); 2266 It != Node.body_end(); 2267 ++It) { 2268 if (InnerMatcher.matches(**It, Finder, Builder)) return true; 2269 } 2270 return false; 2271} 2272 2273/// \brief Checks that a compound statement contains a specific number of 2274/// child statements. 2275/// 2276/// Example: Given 2277/// \code 2278/// { for (;;) {} } 2279/// \endcode 2280/// compoundStmt(statementCountIs(0))) 2281/// matches '{}' 2282/// but does not match the outer compound statement. 2283AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) { 2284 return Node.size() == N; 2285} 2286 2287/// \brief Matches literals that are equal to the given value. 2288/// 2289/// Example matches true (matcher = boolLiteral(equals(true))) 2290/// \code 2291/// true 2292/// \endcode 2293/// 2294/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>, 2295/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral> 2296template <typename ValueT> 2297internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT> 2298equals(const ValueT &Value) { 2299 return internal::PolymorphicMatcherWithParam1< 2300 internal::ValueEqualsMatcher, 2301 ValueT>(Value); 2302} 2303 2304/// \brief Matches the operator Name of operator expressions (binary or 2305/// unary). 2306/// 2307/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||"))) 2308/// \code 2309/// !(a || b) 2310/// \endcode 2311AST_POLYMORPHIC_MATCHER_P(hasOperatorName, std::string, Name) { 2312 TOOLING_COMPILE_ASSERT( 2313 (llvm::is_base_of<BinaryOperator, NodeType>::value) || 2314 (llvm::is_base_of<UnaryOperator, NodeType>::value), 2315 has_condition_requires_if_statement_or_conditional_operator); 2316 return Name == Node.getOpcodeStr(Node.getOpcode()); 2317} 2318 2319/// \brief Matches the left hand side of binary operator expressions. 2320/// 2321/// Example matches a (matcher = binaryOperator(hasLHS())) 2322/// \code 2323/// a || b 2324/// \endcode 2325AST_MATCHER_P(BinaryOperator, hasLHS, 2326 internal::Matcher<Expr>, InnerMatcher) { 2327 Expr *LeftHandSide = Node.getLHS(); 2328 return (LeftHandSide != NULL && 2329 InnerMatcher.matches(*LeftHandSide, Finder, Builder)); 2330} 2331 2332/// \brief Matches the right hand side of binary operator expressions. 2333/// 2334/// Example matches b (matcher = binaryOperator(hasRHS())) 2335/// \code 2336/// a || b 2337/// \endcode 2338AST_MATCHER_P(BinaryOperator, hasRHS, 2339 internal::Matcher<Expr>, InnerMatcher) { 2340 Expr *RightHandSide = Node.getRHS(); 2341 return (RightHandSide != NULL && 2342 InnerMatcher.matches(*RightHandSide, Finder, Builder)); 2343} 2344 2345/// \brief Matches if either the left hand side or the right hand side of a 2346/// binary operator matches. 2347inline internal::Matcher<BinaryOperator> hasEitherOperand( 2348 const internal::Matcher<Expr> &InnerMatcher) { 2349 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)); 2350} 2351 2352/// \brief Matches if the operand of a unary operator matches. 2353/// 2354/// Example matches true (matcher = hasUnaryOperand(boolLiteral(equals(true)))) 2355/// \code 2356/// !true 2357/// \endcode 2358AST_MATCHER_P(UnaryOperator, hasUnaryOperand, 2359 internal::Matcher<Expr>, InnerMatcher) { 2360 const Expr * const Operand = Node.getSubExpr(); 2361 return (Operand != NULL && 2362 InnerMatcher.matches(*Operand, Finder, Builder)); 2363} 2364 2365/// \brief Matches if the cast's source expression matches the given matcher. 2366/// 2367/// Example: matches "a string" (matcher = 2368/// hasSourceExpression(constructExpr())) 2369/// \code 2370/// class URL { URL(string); }; 2371/// URL url = "a string"; 2372AST_MATCHER_P(CastExpr, hasSourceExpression, 2373 internal::Matcher<Expr>, InnerMatcher) { 2374 const Expr* const SubExpression = Node.getSubExpr(); 2375 return (SubExpression != NULL && 2376 InnerMatcher.matches(*SubExpression, Finder, Builder)); 2377} 2378 2379/// \brief Matches casts whose destination type matches a given matcher. 2380/// 2381/// (Note: Clang's AST refers to other conversions as "casts" too, and calls 2382/// actual casts "explicit" casts.) 2383AST_MATCHER_P(ExplicitCastExpr, hasDestinationType, 2384 internal::Matcher<QualType>, InnerMatcher) { 2385 const QualType NodeType = Node.getTypeAsWritten(); 2386 return InnerMatcher.matches(NodeType, Finder, Builder); 2387} 2388 2389/// \brief Matches implicit casts whose destination type matches a given 2390/// matcher. 2391/// 2392/// FIXME: Unit test this matcher 2393AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType, 2394 internal::Matcher<QualType>, InnerMatcher) { 2395 return InnerMatcher.matches(Node.getType(), Finder, Builder); 2396} 2397 2398/// \brief Matches the true branch expression of a conditional operator. 2399/// 2400/// Example matches a 2401/// \code 2402/// condition ? a : b 2403/// \endcode 2404AST_MATCHER_P(ConditionalOperator, hasTrueExpression, 2405 internal::Matcher<Expr>, InnerMatcher) { 2406 Expr *Expression = Node.getTrueExpr(); 2407 return (Expression != NULL && 2408 InnerMatcher.matches(*Expression, Finder, Builder)); 2409} 2410 2411/// \brief Matches the false branch expression of a conditional operator. 2412/// 2413/// Example matches b 2414/// \code 2415/// condition ? a : b 2416/// \endcode 2417AST_MATCHER_P(ConditionalOperator, hasFalseExpression, 2418 internal::Matcher<Expr>, InnerMatcher) { 2419 Expr *Expression = Node.getFalseExpr(); 2420 return (Expression != NULL && 2421 InnerMatcher.matches(*Expression, Finder, Builder)); 2422} 2423 2424/// \brief Matches if a declaration has a body attached. 2425/// 2426/// Example matches A, va, fa 2427/// \code 2428/// class A {}; 2429/// class B; // Doesn't match, as it has no body. 2430/// int va; 2431/// extern int vb; // Doesn't match, as it doesn't define the variable. 2432/// void fa() {} 2433/// void fb(); // Doesn't match, as it has no body. 2434/// \endcode 2435/// 2436/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl> 2437AST_POLYMORPHIC_MATCHER(isDefinition) { 2438 TOOLING_COMPILE_ASSERT( 2439 (llvm::is_base_of<TagDecl, NodeType>::value) || 2440 (llvm::is_base_of<VarDecl, NodeType>::value) || 2441 (llvm::is_base_of<FunctionDecl, NodeType>::value), 2442 is_definition_requires_isThisDeclarationADefinition_method); 2443 return Node.isThisDeclarationADefinition(); 2444} 2445 2446/// \brief Matches the class declaration that the given method declaration 2447/// belongs to. 2448/// 2449/// FIXME: Generalize this for other kinds of declarations. 2450/// FIXME: What other kind of declarations would we need to generalize 2451/// this to? 2452/// 2453/// Example matches A() in the last line 2454/// (matcher = constructExpr(hasDeclaration(methodDecl( 2455/// ofClass(hasName("A")))))) 2456/// \code 2457/// class A { 2458/// public: 2459/// A(); 2460/// }; 2461/// A a = A(); 2462/// \endcode 2463AST_MATCHER_P(CXXMethodDecl, ofClass, 2464 internal::Matcher<CXXRecordDecl>, InnerMatcher) { 2465 const CXXRecordDecl *Parent = Node.getParent(); 2466 return (Parent != NULL && 2467 InnerMatcher.matches(*Parent, Finder, Builder)); 2468} 2469 2470/// \brief Matches member expressions that are called with '->' as opposed 2471/// to '.'. 2472/// 2473/// Member calls on the implicit this pointer match as called with '->'. 2474/// 2475/// Given 2476/// \code 2477/// class Y { 2478/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 2479/// int a; 2480/// static int b; 2481/// }; 2482/// \endcode 2483/// memberExpr(isArrow()) 2484/// matches this->x, x, y.x, a, this->b 2485AST_MATCHER(MemberExpr, isArrow) { 2486 return Node.isArrow(); 2487} 2488 2489/// \brief Matches QualType nodes that are of integer type. 2490/// 2491/// Given 2492/// \code 2493/// void a(int); 2494/// void b(long); 2495/// void c(double); 2496/// \endcode 2497/// functionDecl(hasAnyParameter(hasType(isInteger()))) 2498/// matches "a(int)", "b(long)", but not "c(double)". 2499AST_MATCHER(QualType, isInteger) { 2500 return Node->isIntegerType(); 2501} 2502 2503/// \brief Matches QualType nodes that are const-qualified, i.e., that 2504/// include "top-level" const. 2505/// 2506/// Given 2507/// \code 2508/// void a(int); 2509/// void b(int const); 2510/// void c(const int); 2511/// void d(const int*); 2512/// void e(int const) {}; 2513/// \endcode 2514/// functionDecl(hasAnyParameter(hasType(isConstQualified()))) 2515/// matches "void b(int const)", "void c(const int)" and 2516/// "void e(int const) {}". It does not match d as there 2517/// is no top-level const on the parameter type "const int *". 2518AST_MATCHER(QualType, isConstQualified) { 2519 return Node.isConstQualified(); 2520} 2521 2522/// \brief Matches a member expression where the member is matched by a 2523/// given matcher. 2524/// 2525/// Given 2526/// \code 2527/// struct { int first, second; } first, second; 2528/// int i(second.first); 2529/// int j(first.second); 2530/// \endcode 2531/// memberExpr(member(hasName("first"))) 2532/// matches second.first 2533/// but not first.second (because the member name there is "second"). 2534AST_MATCHER_P(MemberExpr, member, 2535 internal::Matcher<ValueDecl>, InnerMatcher) { 2536 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder); 2537} 2538 2539/// \brief Matches a member expression where the object expression is 2540/// matched by a given matcher. 2541/// 2542/// Given 2543/// \code 2544/// struct X { int m; }; 2545/// void f(X x) { x.m; m; } 2546/// \endcode 2547/// memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X"))))))) 2548/// matches "x.m" and "m" 2549/// with hasObjectExpression(...) 2550/// matching "x" and the implicit object expression of "m" which has type X*. 2551AST_MATCHER_P(MemberExpr, hasObjectExpression, 2552 internal::Matcher<Expr>, InnerMatcher) { 2553 return InnerMatcher.matches(*Node.getBase(), Finder, Builder); 2554} 2555 2556/// \brief Matches any using shadow declaration. 2557/// 2558/// Given 2559/// \code 2560/// namespace X { void b(); } 2561/// using X::b; 2562/// \endcode 2563/// usingDecl(hasAnyUsingShadowDecl(hasName("b")))) 2564/// matches \code using X::b \endcode 2565AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl, 2566 internal::Matcher<UsingShadowDecl>, InnerMatcher) { 2567 for (UsingDecl::shadow_iterator II = Node.shadow_begin(); 2568 II != Node.shadow_end(); ++II) { 2569 if (InnerMatcher.matches(**II, Finder, Builder)) 2570 return true; 2571 } 2572 return false; 2573} 2574 2575/// \brief Matches a using shadow declaration where the target declaration is 2576/// matched by the given matcher. 2577/// 2578/// Given 2579/// \code 2580/// namespace X { int a; void b(); } 2581/// using X::a; 2582/// using X::b; 2583/// \endcode 2584/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl()))) 2585/// matches \code using X::b \endcode 2586/// but not \code using X::a \endcode 2587AST_MATCHER_P(UsingShadowDecl, hasTargetDecl, 2588 internal::Matcher<NamedDecl>, InnerMatcher) { 2589 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder); 2590} 2591 2592/// \brief Matches template instantiations of function, class, or static 2593/// member variable template instantiations. 2594/// 2595/// Given 2596/// \code 2597/// template <typename T> class X {}; class A {}; X<A> x; 2598/// \endcode 2599/// or 2600/// \code 2601/// template <typename T> class X {}; class A {}; template class X<A>; 2602/// \endcode 2603/// recordDecl(hasName("::X"), isTemplateInstantiation()) 2604/// matches the template instantiation of X<A>. 2605/// 2606/// But given 2607/// \code 2608/// template <typename T> class X {}; class A {}; 2609/// template <> class X<A> {}; X<A> x; 2610/// \endcode 2611/// recordDecl(hasName("::X"), isTemplateInstantiation()) 2612/// does not match, as X<A> is an explicit template specialization. 2613/// 2614/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> 2615AST_POLYMORPHIC_MATCHER(isTemplateInstantiation) { 2616 TOOLING_COMPILE_ASSERT((llvm::is_base_of<FunctionDecl, NodeType>::value) || 2617 (llvm::is_base_of<VarDecl, NodeType>::value) || 2618 (llvm::is_base_of<CXXRecordDecl, NodeType>::value), 2619 requires_getTemplateSpecializationKind_method); 2620 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation || 2621 Node.getTemplateSpecializationKind() == 2622 TSK_ExplicitInstantiationDefinition); 2623} 2624 2625/// \brief Matches explicit template specializations of function, class, or 2626/// static member variable template instantiations. 2627/// 2628/// Given 2629/// \code 2630/// template<typename T> void A(T t) { } 2631/// template<> void A(int N) { } 2632/// \endcode 2633/// functionDecl(isExplicitTemplateSpecialization()) 2634/// matches the specialization A<int>(). 2635/// 2636/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> 2637AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization) { 2638 TOOLING_COMPILE_ASSERT((llvm::is_base_of<FunctionDecl, NodeType>::value) || 2639 (llvm::is_base_of<VarDecl, NodeType>::value) || 2640 (llvm::is_base_of<CXXRecordDecl, NodeType>::value), 2641 requires_getTemplateSpecializationKind_method); 2642 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization); 2643} 2644 2645/// \brief Matches \c TypeLocs for which the given inner 2646/// QualType-matcher matches. 2647inline internal::BindableMatcher<TypeLoc> loc( 2648 const internal::Matcher<QualType> &InnerMatcher) { 2649 return internal::BindableMatcher<TypeLoc>( 2650 new internal::TypeLocTypeMatcher(InnerMatcher)); 2651} 2652 2653/// \brief Matches builtin Types. 2654/// 2655/// Given 2656/// \code 2657/// struct A {}; 2658/// A a; 2659/// int b; 2660/// float c; 2661/// bool d; 2662/// \endcode 2663/// builtinType() 2664/// matches "int b", "float c" and "bool d" 2665AST_TYPE_MATCHER(BuiltinType, builtinType); 2666 2667/// \brief Matches all kinds of arrays. 2668/// 2669/// Given 2670/// \code 2671/// int a[] = { 2, 3 }; 2672/// int b[4]; 2673/// void f() { int c[a[0]]; } 2674/// \endcode 2675/// arrayType() 2676/// matches "int a[]", "int b[4]" and "int c[a[0]]"; 2677AST_TYPE_MATCHER(ArrayType, arrayType); 2678 2679/// \brief Matches C99 complex types. 2680/// 2681/// Given 2682/// \code 2683/// _Complex float f; 2684/// \endcode 2685/// complexType() 2686/// matches "_Complex float f" 2687AST_TYPE_MATCHER(ComplexType, complexType); 2688 2689/// \brief Matches arrays and C99 complex types that have a specific element 2690/// type. 2691/// 2692/// Given 2693/// \code 2694/// struct A {}; 2695/// A a[7]; 2696/// int b[7]; 2697/// \endcode 2698/// arrayType(hasElementType(builtinType())) 2699/// matches "int b[7]" 2700/// 2701/// Usable as: Matcher<ArrayType>, Matcher<ComplexType> 2702AST_TYPELOC_TRAVERSE_MATCHER(hasElementType, getElement); 2703 2704/// \brief Matches C arrays with a specified constant size. 2705/// 2706/// Given 2707/// \code 2708/// void() { 2709/// int a[2]; 2710/// int b[] = { 2, 3 }; 2711/// int c[b[0]]; 2712/// } 2713/// \endcode 2714/// constantArrayType() 2715/// matches "int a[2]" 2716AST_TYPE_MATCHER(ConstantArrayType, constantArrayType); 2717 2718/// \brief Matches \c ConstantArrayType nodes that have the specified size. 2719/// 2720/// Given 2721/// \code 2722/// int a[42]; 2723/// int b[2 * 21]; 2724/// int c[41], d[43]; 2725/// \endcode 2726/// constantArrayType(hasSize(42)) 2727/// matches "int a[42]" and "int b[2 * 21]" 2728AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) { 2729 return Node.getSize() == N; 2730} 2731 2732/// \brief Matches C++ arrays whose size is a value-dependent expression. 2733/// 2734/// Given 2735/// \code 2736/// template<typename T, int Size> 2737/// class array { 2738/// T data[Size]; 2739/// }; 2740/// \endcode 2741/// dependentSizedArrayType 2742/// matches "T data[Size]" 2743AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType); 2744 2745/// \brief Matches C arrays with unspecified size. 2746/// 2747/// Given 2748/// \code 2749/// int a[] = { 2, 3 }; 2750/// int b[42]; 2751/// void f(int c[]) { int d[a[0]]; }; 2752/// \endcode 2753/// incompleteArrayType() 2754/// matches "int a[]" and "int c[]" 2755AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType); 2756 2757/// \brief Matches C arrays with a specified size that is not an 2758/// integer-constant-expression. 2759/// 2760/// Given 2761/// \code 2762/// void f() { 2763/// int a[] = { 2, 3 } 2764/// int b[42]; 2765/// int c[a[0]]; 2766/// \endcode 2767/// variableArrayType() 2768/// matches "int c[a[0]]" 2769AST_TYPE_MATCHER(VariableArrayType, variableArrayType); 2770 2771/// \brief Matches \c VariableArrayType nodes that have a specific size 2772/// expression. 2773/// 2774/// Given 2775/// \code 2776/// void f(int b) { 2777/// int a[b]; 2778/// } 2779/// \endcode 2780/// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to( 2781/// varDecl(hasName("b"))))))) 2782/// matches "int a[b]" 2783AST_MATCHER_P(VariableArrayType, hasSizeExpr, 2784 internal::Matcher<Expr>, InnerMatcher) { 2785 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder); 2786} 2787 2788/// \brief Matches atomic types. 2789/// 2790/// Given 2791/// \code 2792/// _Atomic(int) i; 2793/// \endcode 2794/// atomicType() 2795/// matches "_Atomic(int) i" 2796AST_TYPE_MATCHER(AtomicType, atomicType); 2797 2798/// \brief Matches atomic types with a specific value type. 2799/// 2800/// Given 2801/// \code 2802/// _Atomic(int) i; 2803/// _Atomic(float) f; 2804/// \endcode 2805/// atomicType(hasValueType(isInteger())) 2806/// matches "_Atomic(int) i" 2807/// 2808/// Usable as: Matcher<AtomicType> 2809AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue); 2810 2811/// \brief Matches types nodes representing C++11 auto types. 2812/// 2813/// Given: 2814/// \code 2815/// auto n = 4; 2816/// int v[] = { 2, 3 } 2817/// for (auto i : v) { } 2818/// \endcode 2819/// autoType() 2820/// matches "auto n" and "auto i" 2821AST_TYPE_MATCHER(AutoType, autoType); 2822 2823/// \brief Matches \c AutoType nodes where the deduced type is a specific type. 2824/// 2825/// Note: There is no \c TypeLoc for the deduced type and thus no 2826/// \c getDeducedLoc() matcher. 2827/// 2828/// Given 2829/// \code 2830/// auto a = 1; 2831/// auto b = 2.0; 2832/// \endcode 2833/// autoType(hasDeducedType(isInteger())) 2834/// matches "auto a" 2835/// 2836/// Usable as: Matcher<AutoType> 2837AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType); 2838 2839/// \brief Matches \c FunctionType nodes. 2840/// 2841/// Given 2842/// \code 2843/// int (*f)(int); 2844/// void g(); 2845/// \endcode 2846/// functionType() 2847/// matches "int (*f)(int)" and the type of "g". 2848AST_TYPE_MATCHER(FunctionType, functionType); 2849 2850/// \brief Matches block pointer types, i.e. types syntactically represented as 2851/// "void (^)(int)". 2852/// 2853/// The \c pointee is always required to be a \c FunctionType. 2854AST_TYPE_MATCHER(BlockPointerType, blockPointerType); 2855 2856/// \brief Matches member pointer types. 2857/// Given 2858/// \code 2859/// struct A { int i; } 2860/// A::* ptr = A::i; 2861/// \endcode 2862/// memberPointerType() 2863/// matches "A::* ptr" 2864AST_TYPE_MATCHER(MemberPointerType, memberPointerType); 2865 2866/// \brief Matches pointer types. 2867/// 2868/// Given 2869/// \code 2870/// int *a; 2871/// int &b = *a; 2872/// int c = 5; 2873/// \endcode 2874/// pointerType() 2875/// matches "int *a" 2876AST_TYPE_MATCHER(PointerType, pointerType); 2877 2878/// \brief Matches reference types. 2879/// 2880/// Given 2881/// \code 2882/// int *a; 2883/// int &b = *a; 2884/// int c = 5; 2885/// \endcode 2886/// pointerType() 2887/// matches "int &b" 2888AST_TYPE_MATCHER(ReferenceType, referenceType); 2889 2890/// \brief Narrows PointerType (and similar) matchers to those where the 2891/// \c pointee matches a given matcher. 2892/// 2893/// Given 2894/// \code 2895/// int *a; 2896/// int const *b; 2897/// float const *f; 2898/// \endcode 2899/// pointerType(pointee(isConstQualified(), isInteger())) 2900/// matches "int const *b" 2901/// 2902/// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>, 2903/// Matcher<PointerType>, Matcher<ReferenceType> 2904AST_TYPELOC_TRAVERSE_MATCHER(pointee, getPointee); 2905 2906/// \brief Matches typedef types. 2907/// 2908/// Given 2909/// \code 2910/// typedef int X; 2911/// \endcode 2912/// typedefType() 2913/// matches "typedef int X" 2914AST_TYPE_MATCHER(TypedefType, typedefType); 2915 2916/// \brief Matches nested name specifiers. 2917/// 2918/// Given 2919/// \code 2920/// namespace ns { 2921/// struct A { static void f(); }; 2922/// void A::f() {} 2923/// void g() { A::f(); } 2924/// } 2925/// ns::A a; 2926/// \endcode 2927/// nestedNameSpecifier() 2928/// matches "ns::" and both "A::" 2929const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier; 2930 2931/// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc. 2932const internal::VariadicAllOfMatcher< 2933 NestedNameSpecifierLoc> nestedNameSpecifierLoc; 2934 2935/// \brief Matches \c NestedNameSpecifierLocs for which the given inner 2936/// NestedNameSpecifier-matcher matches. 2937inline internal::BindableMatcher<NestedNameSpecifierLoc> loc( 2938 const internal::Matcher<NestedNameSpecifier> &InnerMatcher) { 2939 return internal::BindableMatcher<NestedNameSpecifierLoc>( 2940 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>( 2941 InnerMatcher)); 2942} 2943 2944/// \brief Matches nested name specifiers that specify a type matching the 2945/// given \c QualType matcher without qualifiers. 2946/// 2947/// Given 2948/// \code 2949/// struct A { struct B { struct C {}; }; }; 2950/// A::B::C c; 2951/// \endcode 2952/// nestedNameSpecifier(specifiesType(hasDeclaration(recordDecl(hasName("A"))))) 2953/// matches "A::" 2954AST_MATCHER_P(NestedNameSpecifier, specifiesType, 2955 internal::Matcher<QualType>, InnerMatcher) { 2956 if (Node.getAsType() == NULL) 2957 return false; 2958 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder); 2959} 2960 2961/// \brief Matches nested name specifier locs that specify a type matching the 2962/// given \c TypeLoc. 2963/// 2964/// Given 2965/// \code 2966/// struct A { struct B { struct C {}; }; }; 2967/// A::B::C c; 2968/// \endcode 2969/// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type( 2970/// hasDeclaration(recordDecl(hasName("A"))))))) 2971/// matches "A::" 2972AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc, 2973 internal::Matcher<TypeLoc>, InnerMatcher) { 2974 return InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder); 2975} 2976 2977/// \brief Matches on the prefix of a \c NestedNameSpecifier. 2978/// 2979/// Given 2980/// \code 2981/// struct A { struct B { struct C {}; }; }; 2982/// A::B::C c; 2983/// \endcode 2984/// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and 2985/// matches "A::" 2986AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix, 2987 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 2988 0) { 2989 NestedNameSpecifier *NextNode = Node.getPrefix(); 2990 if (NextNode == NULL) 2991 return false; 2992 return InnerMatcher.matches(*NextNode, Finder, Builder); 2993} 2994 2995/// \brief Matches on the prefix of a \c NestedNameSpecifierLoc. 2996/// 2997/// Given 2998/// \code 2999/// struct A { struct B { struct C {}; }; }; 3000/// A::B::C c; 3001/// \endcode 3002/// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A"))))) 3003/// matches "A::" 3004AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix, 3005 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher, 3006 1) { 3007 NestedNameSpecifierLoc NextNode = Node.getPrefix(); 3008 if (!NextNode) 3009 return false; 3010 return InnerMatcher.matches(NextNode, Finder, Builder); 3011} 3012 3013/// \brief Matches nested name specifiers that specify a namespace matching the 3014/// given namespace matcher. 3015/// 3016/// Given 3017/// \code 3018/// namespace ns { struct A {}; } 3019/// ns::A a; 3020/// \endcode 3021/// nestedNameSpecifier(specifiesNamespace(hasName("ns"))) 3022/// matches "ns::" 3023AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace, 3024 internal::Matcher<NamespaceDecl>, InnerMatcher) { 3025 if (Node.getAsNamespace() == NULL) 3026 return false; 3027 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder); 3028} 3029 3030/// \brief Overloads for the \c equalsNode matcher. 3031/// FIXME: Implement for other node types. 3032/// @{ 3033 3034/// \brief Matches if a node equals another node. 3035/// 3036/// \c Decl has pointer identity in the AST. 3037AST_MATCHER_P_OVERLOAD(Decl, equalsNode, Decl*, Other, 0) { 3038 return &Node == Other; 3039} 3040/// \brief Matches if a node equals another node. 3041/// 3042/// \c Stmt has pointer identity in the AST. 3043/// 3044AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, Stmt*, Other, 1) { 3045 return &Node == Other; 3046} 3047 3048/// @} 3049 3050} // end namespace ast_matchers 3051} // end namespace clang 3052 3053#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H 3054