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