ASTMatchers.h revision 8cc7efa2da2c6be43cbd3d09a9ae01353bb921d2
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// record(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// record(hasName("MyClass"), hasChild(id("child", record()))) 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 54namespace clang { 55namespace ast_matchers { 56 57/// \brief Maps string IDs to AST nodes matched by parts of a matcher. 58/// 59/// The bound nodes are generated by adding id(...) matchers into the 60/// match expression around the matchers for the nodes we want to access later. 61/// 62/// The instances of BoundNodes are created by MatchFinder when the user's 63/// callbacks are executed every time a match is found. 64class BoundNodes { 65public: 66 /// \brief Returns the AST node bound to 'ID'. 67 /// Returns NULL if there was no node bound to 'ID' or if there is a node but 68 /// it cannot be converted to the specified type. 69 /// FIXME: We'll need one of those for every base type. 70 /// @{ 71 template <typename T> 72 const T *getDeclAs(StringRef ID) const { 73 return getNodeAs<T>(DeclBindings, ID); 74 } 75 template <typename T> 76 const T *getStmtAs(StringRef ID) const { 77 return getNodeAs<T>(StmtBindings, ID); 78 } 79 /// @} 80 81private: 82 /// \brief Create BoundNodes from a pre-filled map of bindings. 83 BoundNodes(const std::map<std::string, const Decl*> &DeclBindings, 84 const std::map<std::string, const Stmt*> &StmtBindings) 85 : DeclBindings(DeclBindings), StmtBindings(StmtBindings) {} 86 87 template <typename T, typename MapT> 88 const T *getNodeAs(const MapT &Bindings, StringRef ID) const { 89 typename MapT::const_iterator It = Bindings.find(ID); 90 if (It == Bindings.end()) { 91 return NULL; 92 } 93 return llvm::dyn_cast<T>(It->second); 94 } 95 96 std::map<std::string, const Decl*> DeclBindings; 97 std::map<std::string, const Stmt*> StmtBindings; 98 99 friend class internal::BoundNodesTree; 100}; 101 102/// \brief If the provided matcher matches a node, binds the node to 'ID'. 103/// 104/// FIXME: Add example for accessing it. 105template <typename T> 106internal::Matcher<T> id(const std::string &ID, 107 const internal::BindableMatcher<T> &InnerMatcher) { 108 return InnerMatcher.bind(ID); 109} 110 111/// \brief Types of matchers for the top-level classes in the AST class 112/// hierarchy. 113/// @{ 114typedef internal::Matcher<Decl> DeclarationMatcher; 115typedef internal::Matcher<QualType> TypeMatcher; 116typedef internal::Matcher<Stmt> StatementMatcher; 117/// @} 118 119/// \brief Matches any node. 120/// 121/// Useful when another matcher requires a child matcher, but there's no 122/// additional constraint. This will often be used with an explicit conversion 123/// to a internal::Matcher<> type such as TypeMatcher. 124/// 125/// Example: DeclarationMatcher(anything()) matches all declarations, e.g., 126/// "int* p" and "void f()" in 127/// int* p; 128/// void f(); 129inline internal::PolymorphicMatcherWithParam0<internal::TrueMatcher> anything() { 130 return internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>(); 131} 132 133/// \brief Matches declarations. 134/// 135/// Examples matches \c X, \c C, and the friend declaration inside \c C; 136/// \code 137/// void X(); 138/// class C { 139/// friend X; 140/// }; 141/// \endcode 142const internal::VariadicDynCastAllOfMatcher<Decl, Decl> decl; 143 144/// \brief Matches a declaration of anything that could have a name. 145/// 146/// Example matches X, S, the anonymous union type, i, and U; 147/// typedef int X; 148/// struct S { 149/// union { 150/// int i; 151/// } U; 152/// }; 153const internal::VariadicDynCastAllOfMatcher< 154 Decl, 155 NamedDecl> nameableDeclaration; 156 157/// \brief Matches C++ class declarations. 158/// 159/// Example matches X, Z 160/// class X; 161/// template<class T> class Z {}; 162const internal::VariadicDynCastAllOfMatcher< 163 Decl, 164 CXXRecordDecl> record; 165 166/// \brief Matches C++ class template specializations. 167/// 168/// Given 169/// template<typename T> class A {}; 170/// template<> class A<double> {}; 171/// A<int> a; 172/// classTemplateSpecialization() 173/// matches the specializations \c A<int> and \c A<double> 174const internal::VariadicDynCastAllOfMatcher< 175 Decl, 176 ClassTemplateSpecializationDecl> classTemplateSpecialization; 177 178/// \brief Matches classTemplateSpecializations that have at least one 179/// TemplateArgument matching the given Matcher. 180/// 181/// Given 182/// template<typename T> class A {}; 183/// template<> class A<double> {}; 184/// A<int> a; 185/// classTemplateSpecialization(hasAnyTemplateArgument( 186/// refersToType(asString("int")))) 187/// matches the specialization \c A<int> 188AST_MATCHER_P(ClassTemplateSpecializationDecl, hasAnyTemplateArgument, 189 internal::Matcher<TemplateArgument>, Matcher) { 190 const TemplateArgumentList &List = Node.getTemplateArgs(); 191 for (unsigned i = 0; i < List.size(); ++i) { 192 if (Matcher.matches(List.get(i), Finder, Builder)) 193 return true; 194 } 195 return false; 196} 197 198/// \brief Matches classTemplateSpecializations where the n'th TemplateArgument 199/// matches the given Matcher. 200/// 201/// Given 202/// template<typename T, typename U> class A {}; 203/// A<bool, int> b; 204/// A<int, bool> c; 205/// classTemplateSpecialization(hasTemplateArgument( 206/// 1, refersToType(asString("int")))) 207/// matches the specialization \c A<bool, int> 208AST_MATCHER_P2(ClassTemplateSpecializationDecl, hasTemplateArgument, 209 unsigned, N, internal::Matcher<TemplateArgument>, Matcher) { 210 const TemplateArgumentList &List = Node.getTemplateArgs(); 211 if (List.size() <= N) 212 return false; 213 return Matcher.matches(List.get(N), Finder, Builder); 214} 215 216/// \brief Matches a TemplateArgument that refers to a certain type. 217/// 218/// Given 219/// struct X {}; 220/// template<typename T> struct A {}; 221/// A<X> a; 222/// classTemplateSpecialization(hasAnyTemplateArgument( 223/// refersToType(class(hasName("X"))))) 224/// matches the specialization \c A<X> 225AST_MATCHER_P(TemplateArgument, refersToType, 226 internal::Matcher<QualType>, Matcher) { 227 if (Node.getKind() != TemplateArgument::Type) 228 return false; 229 return Matcher.matches(Node.getAsType(), Finder, Builder); 230} 231 232/// \brief Matches a TemplateArgument that refers to a certain declaration. 233/// 234/// Given 235/// template<typename T> struct A {}; 236/// struct B { B* next; }; 237/// A<&B::next> a; 238/// classTemplateSpecialization(hasAnyTemplateArgument( 239/// refersToDeclaration(field(hasName("next")))) 240/// matches the specialization \c A<&B::next> with \c field(...) matching 241/// \c B::next 242AST_MATCHER_P(TemplateArgument, refersToDeclaration, 243 internal::Matcher<Decl>, Matcher) { 244 if (const Decl *Declaration = Node.getAsDecl()) 245 return Matcher.matches(*Declaration, Finder, Builder); 246 return false; 247} 248 249/// \brief Matches C++ constructor declarations. 250/// 251/// Example matches Foo::Foo() and Foo::Foo(int) 252/// class Foo { 253/// public: 254/// Foo(); 255/// Foo(int); 256/// int DoSomething(); 257/// }; 258const internal::VariadicDynCastAllOfMatcher< 259 Decl, 260 CXXConstructorDecl> constructor; 261 262/// \brief Matches explicit C++ destructor declarations. 263/// 264/// Example matches Foo::~Foo() 265/// class Foo { 266/// public: 267/// virtual ~Foo(); 268/// }; 269const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl> destructor; 270 271/// \brief Matches enum declarations. 272/// 273/// Example matches X 274/// enum X { 275/// A, B, C 276/// }; 277const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl; 278 279/// \brief Matches enum constants. 280/// 281/// Example matches A, B, C 282/// enum X { 283/// A, B, C 284/// }; 285const internal::VariadicDynCastAllOfMatcher< 286 Decl, 287 EnumConstantDecl> enumConstant; 288 289/// \brief Matches method declarations. 290/// 291/// Example matches y 292/// class X { void y() }; 293const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> method; 294 295/// \brief Matches variable declarations. 296/// 297/// Note: this does not match declarations of member variables, which are 298/// "field" declarations in Clang parlance. 299/// 300/// Example matches a 301/// int a; 302const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> variable; 303 304/// \brief Matches field declarations. 305/// 306/// Given 307/// class X { int m; }; 308/// field() 309/// matches 'm'. 310const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> field; 311 312/// \brief Matches function declarations. 313/// 314/// Example matches f 315/// void f(); 316const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> function; 317 318 319/// \brief Matches statements. 320/// 321/// Given 322/// { ++a; } 323/// statement() 324/// matches both the compound statement '{ ++a; }' and '++a'. 325const internal::VariadicDynCastAllOfMatcher<Stmt, Stmt> statement; 326 327/// \brief Matches declaration statements. 328/// 329/// Given 330/// int a; 331/// declarationStatement() 332/// matches 'int a'. 333const internal::VariadicDynCastAllOfMatcher< 334 Stmt, 335 DeclStmt> declarationStatement; 336 337/// \brief Matches member expressions. 338/// 339/// Given 340/// class Y { 341/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 342/// int a; static int b; 343/// }; 344/// memberExpression() 345/// matches this->x, x, y.x, a, this->b 346const internal::VariadicDynCastAllOfMatcher< 347 Stmt, 348 MemberExpr> memberExpression; 349 350/// \brief Matches call expressions. 351/// 352/// Example matches x.y() and y() 353/// X x; 354/// x.y(); 355/// y(); 356const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> call; 357 358/// \brief Matches member call expressions. 359/// 360/// Example matches x.y() 361/// X x; 362/// x.y(); 363const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr> memberCall; 364 365/// \brief Matches init list expressions. 366/// 367/// Given 368/// int a[] = { 1, 2 }; 369/// struct B { int x, y; }; 370/// B b = { 5, 6 }; 371/// initList() 372/// matches "{ 1, 2 }" and "{ 5, 6 }" 373const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr; 374 375/// \brief Matches using declarations. 376/// 377/// Given 378/// namespace X { int x; } 379/// using X::x; 380/// usingDecl() 381/// matches \code using X::x \endcode 382const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl; 383 384/// \brief Matches constructor call expressions (including implicit ones). 385/// 386/// Example matches string(ptr, n) and ptr within arguments of f 387/// (matcher = constructorCall()) 388/// void f(const string &a, const string &b); 389/// char *ptr; 390/// int n; 391/// f(string(ptr, n), ptr); 392const internal::VariadicDynCastAllOfMatcher< 393 Stmt, 394 CXXConstructExpr> constructorCall; 395 396/// \brief Matches nodes where temporaries are created. 397/// 398/// Example matches FunctionTakesString(GetStringByValue()) 399/// (matcher = bindTemporaryExpression()) 400/// FunctionTakesString(GetStringByValue()); 401/// FunctionTakesStringByPointer(GetStringPointer()); 402const internal::VariadicDynCastAllOfMatcher< 403 Stmt, 404 CXXBindTemporaryExpr> bindTemporaryExpression; 405 406/// \brief Matches new expressions. 407/// 408/// Given 409/// new X; 410/// newExpression() 411/// matches 'new X'. 412const internal::VariadicDynCastAllOfMatcher< 413 Stmt, 414 CXXNewExpr> newExpression; 415 416/// \brief Matches delete expressions. 417/// 418/// Given 419/// delete X; 420/// deleteExpression() 421/// matches 'delete X'. 422const internal::VariadicDynCastAllOfMatcher< 423 Stmt, 424 CXXDeleteExpr> deleteExpression; 425 426/// \brief Matches array subscript expressions. 427/// 428/// Given 429/// int i = a[1]; 430/// arraySubscriptExpr() 431/// matches "a[1]" 432const internal::VariadicDynCastAllOfMatcher< 433 Stmt, 434 ArraySubscriptExpr> arraySubscriptExpr; 435 436/// \brief Matches the value of a default argument at the call site. 437/// 438/// Example matches the CXXDefaultArgExpr placeholder inserted for the 439/// default value of the second parameter in the call expression f(42) 440/// (matcher = defaultArgument()) 441/// void f(int x, int y = 0); 442/// f(42); 443const internal::VariadicDynCastAllOfMatcher< 444 Stmt, 445 CXXDefaultArgExpr> defaultArgument; 446 447/// \brief Matches overloaded operator calls. 448/// 449/// Note that if an operator isn't overloaded, it won't match. Instead, use 450/// binaryOperator matcher. 451/// Currently it does not match operators such as new delete. 452/// FIXME: figure out why these do not match? 453/// 454/// Example matches both operator<<((o << b), c) and operator<<(o, b) 455/// (matcher = overloadedOperatorCall()) 456/// ostream &operator<< (ostream &out, int i) { }; 457/// ostream &o; int b = 1, c = 1; 458/// o << b << c; 459const internal::VariadicDynCastAllOfMatcher< 460 Stmt, 461 CXXOperatorCallExpr> overloadedOperatorCall; 462 463/// \brief Matches expressions. 464/// 465/// Example matches x() 466/// void f() { x(); } 467const internal::VariadicDynCastAllOfMatcher< 468 Stmt, 469 Expr> expression; 470 471/// \brief Matches expressions that refer to declarations. 472/// 473/// Example matches x in if (x) 474/// bool x; 475/// if (x) {} 476const internal::VariadicDynCastAllOfMatcher< 477 Stmt, 478 DeclRefExpr> declarationReference; 479 480/// \brief Matches if statements. 481/// 482/// Example matches 'if (x) {}' 483/// if (x) {} 484const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt; 485 486/// \brief Matches for statements. 487/// 488/// Example matches 'for (;;) {}' 489/// for (;;) {} 490const internal::VariadicDynCastAllOfMatcher< 491 Stmt, ForStmt> forStmt; 492 493/// \brief Matches the increment statement of a for loop. 494/// 495/// Example: 496/// forStmt(hasIncrement(unaryOperator(hasOperatorName("++")))) 497/// matches '++x' in 498/// for (x; x < N; ++x) { } 499AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>, 500 InnerMatcher) { 501 const Stmt *const Increment = Node.getInc(); 502 return (Increment != NULL && 503 InnerMatcher.matches(*Increment, Finder, Builder)); 504} 505 506/// \brief Matches the initialization statement of a for loop. 507/// 508/// Example: 509/// forStmt(hasLoopInit(declarationStatement())) 510/// matches 'int x = 0' in 511/// for (int x = 0; x < N; ++x) { } 512AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>, 513 InnerMatcher) { 514 const Stmt *const Init = Node.getInit(); 515 return (Init != NULL && InnerMatcher.matches(*Init, Finder, Builder)); 516} 517 518/// \brief Matches while statements. 519/// 520/// Given 521/// while (true) {} 522/// whileStmt() 523/// matches 'while (true) {}'. 524const internal::VariadicDynCastAllOfMatcher< 525 Stmt, 526 WhileStmt> whileStmt; 527 528/// \brief Matches do statements. 529/// 530/// Given 531/// do {} while (true); 532/// doStmt() 533/// matches 'do {} while(true)' 534const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt; 535 536/// \brief Matches case and default statements inside switch statements. 537/// 538/// Given 539/// switch(a) { case 42: break; default: break; } 540/// switchCase() 541/// matches 'case 42: break;' and 'default: break;'. 542const internal::VariadicDynCastAllOfMatcher< 543 Stmt, 544 SwitchCase> switchCase; 545 546/// \brief Matches compound statements. 547/// 548/// Example matches '{}' and '{{}}'in 'for (;;) {{}}' 549/// for (;;) {{}} 550const internal::VariadicDynCastAllOfMatcher< 551 Stmt, 552 CompoundStmt> compoundStatement; 553 554/// \brief Matches bool literals. 555/// 556/// Example matches true 557/// true 558const internal::VariadicDynCastAllOfMatcher< 559 Expr, 560 CXXBoolLiteralExpr> boolLiteral; 561 562/// \brief Matches string literals (also matches wide string literals). 563/// 564/// Example matches "abcd", L"abcd" 565/// char *s = "abcd"; wchar_t *ws = L"abcd" 566const internal::VariadicDynCastAllOfMatcher< 567 Expr, 568 StringLiteral> stringLiteral; 569 570/// \brief Matches character literals (also matches wchar_t). 571/// 572/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral), 573/// though. 574/// 575/// Example matches 'a', L'a' 576/// char ch = 'a'; wchar_t chw = L'a'; 577const internal::VariadicDynCastAllOfMatcher< 578 Expr, 579 CharacterLiteral> characterLiteral; 580 581/// \brief Matches integer literals of all sizes / encodings. 582/// 583/// Not matching character-encoded integers such as L'a'. 584/// 585/// Example matches 1, 1L, 0x1, 1U 586const internal::VariadicDynCastAllOfMatcher< 587 Expr, 588 IntegerLiteral> integerLiteral; 589 590/// \brief Matches binary operator expressions. 591/// 592/// Example matches a || b 593/// !(a || b) 594const internal::VariadicDynCastAllOfMatcher< 595 Stmt, 596 BinaryOperator> binaryOperator; 597 598/// \brief Matches unary operator expressions. 599/// 600/// Example matches !a 601/// !a || b 602const internal::VariadicDynCastAllOfMatcher< 603 Stmt, 604 UnaryOperator> unaryOperator; 605 606/// \brief Matches conditional operator expressions. 607/// 608/// Example matches a ? b : c 609/// (a ? b : c) + 42 610const internal::VariadicDynCastAllOfMatcher< 611 Stmt, 612 ConditionalOperator> conditionalOperator; 613 614/// \brief Matches a reinterpret_cast expression. 615/// 616/// Either the source expression or the destination type can be matched 617/// using has(), but hasDestinationType() is more specific and can be 618/// more readable. 619/// 620/// Example matches reinterpret_cast<char*>(&p) in 621/// void* p = reinterpret_cast<char*>(&p); 622const internal::VariadicDynCastAllOfMatcher< 623 Expr, 624 CXXReinterpretCastExpr> reinterpretCast; 625 626/// \brief Matches a C++ static_cast expression. 627/// 628/// \see hasDestinationType 629/// \see reinterpretCast 630/// 631/// Example: 632/// staticCast() 633/// matches 634/// static_cast<long>(8) 635/// in 636/// long eight(static_cast<long>(8)); 637const internal::VariadicDynCastAllOfMatcher< 638 Expr, 639 CXXStaticCastExpr> staticCast; 640 641/// \brief Matches a dynamic_cast expression. 642/// 643/// Example: 644/// dynamicCast() 645/// matches 646/// dynamic_cast<D*>(&b); 647/// in 648/// struct B { virtual ~B() {} }; struct D : B {}; 649/// B b; 650/// D* p = dynamic_cast<D*>(&b); 651const internal::VariadicDynCastAllOfMatcher< 652 Expr, 653 CXXDynamicCastExpr> dynamicCast; 654 655/// \brief Matches a const_cast expression. 656/// 657/// Example: Matches const_cast<int*>(&r) in 658/// int n = 42; 659/// const int& r(n); 660/// int* p = const_cast<int*>(&r); 661const internal::VariadicDynCastAllOfMatcher< 662 Expr, 663 CXXConstCastExpr> constCast; 664 665/// \brief Matches explicit cast expressions. 666/// 667/// Matches any cast expression written in user code, whether it be a 668/// C-style cast, a functional-style cast, or a keyword cast. 669/// 670/// Does not match implicit conversions. 671/// 672/// Note: the name "explicitCast" is chosen to match Clang's terminology, as 673/// Clang uses the term "cast" to apply to implicit conversions as well as to 674/// actual cast expressions. 675/// 676/// \see hasDestinationType. 677/// 678/// Example: matches all five of the casts in 679/// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42))))) 680/// but does not match the implicit conversion in 681/// long ell = 42; 682const internal::VariadicDynCastAllOfMatcher< 683 Expr, 684 ExplicitCastExpr> explicitCast; 685 686/// \brief Matches the implicit cast nodes of Clang's AST. 687/// 688/// This matches many different places, including function call return value 689/// eliding, as well as any type conversions. 690const internal::VariadicDynCastAllOfMatcher< 691 Expr, 692 ImplicitCastExpr> implicitCast; 693 694/// \brief Matches functional cast expressions 695/// 696/// Example: Matches Foo(bar); 697/// Foo f = bar; 698/// Foo g = (Foo) bar; 699/// Foo h = Foo(bar); 700const internal::VariadicDynCastAllOfMatcher< 701 Expr, 702 CXXFunctionalCastExpr> functionalCast; 703 704/// \brief Various overloads for the anyOf matcher. 705/// @{ 706template<typename C1, typename C2> 707internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1, C2> 708anyOf(const C1 &P1, const C2 &P2) { 709 return internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 710 C1, C2 >(P1, P2); 711} 712template<typename C1, typename C2, typename C3> 713internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1, 714 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2, C3> > 715anyOf(const C1 &P1, const C2 &P2, const C3 &P3) { 716 return anyOf(P1, anyOf(P2, P3)); 717} 718template<typename C1, typename C2, typename C3, typename C4> 719internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1, 720 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2, 721 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 722 C3, C4> > > 723anyOf(const C1 &P1, const C2 &P2, const C3 &P3, const C4 &P4) { 724 return anyOf(P1, anyOf(P2, anyOf(P3, P4))); 725} 726template<typename C1, typename C2, typename C3, typename C4, typename C5> 727internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1, 728 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2, 729 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C3, 730 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 731 C4, C5> > > > 732anyOf(const C1& P1, const C2& P2, const C3& P3, const C4& P4, const C5& P5) { 733 return anyOf(P1, anyOf(P2, anyOf(P3, anyOf(P4, P5)))); 734} 735/// @} 736 737/// \brief Various overloads for the allOf matcher. 738/// @{ 739template<typename C1, typename C2> 740internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C1, C2> 741allOf(const C1 &P1, const C2 &P2) { 742 return internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, 743 C1, C2>(P1, P2); 744} 745template<typename C1, typename C2, typename C3> 746internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C1, 747 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C2, C3> > 748allOf(const C1& P1, const C2& P2, const C3& P3) { 749 return allOf(P1, allOf(P2, P3)); 750} 751/// @} 752 753/// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL) 754/// 755/// Given 756/// Foo x = bar; 757/// int y = sizeof(x) + alignof(x); 758/// unaryExprOrTypeTraitExpr() 759/// matches \c sizeof(x) and \c alignof(x) 760const internal::VariadicDynCastAllOfMatcher< 761 Stmt, 762 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr; 763 764/// \brief Matches unary expressions that have a specific type of argument. 765/// 766/// Given 767/// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c); 768/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int")) 769/// matches \c sizeof(a) and \c alignof(c) 770AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType, 771 internal::Matcher<QualType>, Matcher) { 772 const QualType ArgumentType = Node.getTypeOfArgument(); 773 return Matcher.matches(ArgumentType, Finder, Builder); 774} 775 776/// \brief Matches unary expressions of a certain kind. 777/// 778/// Given 779/// int x; 780/// int s = sizeof(x) + alignof(x) 781/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf)) 782/// matches \c sizeof(x) 783AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) { 784 return Node.getKind() == Kind; 785} 786 787/// \brief Same as unaryExprOrTypeTraitExpr, but only matching 788/// alignof. 789inline internal::Matcher<Stmt> alignOfExpr( 790 const internal::Matcher<UnaryExprOrTypeTraitExpr> &Matcher) { 791 return internal::Matcher<Stmt>(unaryExprOrTypeTraitExpr(allOf( 792 ofKind(UETT_AlignOf), Matcher))); 793} 794 795/// \brief Same as unaryExprOrTypeTraitExpr, but only matching 796/// sizeof. 797inline internal::Matcher<Stmt> sizeOfExpr( 798 const internal::Matcher<UnaryExprOrTypeTraitExpr> &Matcher) { 799 return internal::Matcher<Stmt>(unaryExprOrTypeTraitExpr(allOf( 800 ofKind(UETT_SizeOf), Matcher))); 801} 802 803/// \brief Matches NamedDecl nodes that have the specified name. 804/// 805/// Supports specifying enclosing namespaces or classes by prefixing the name 806/// with '<enclosing>::'. 807/// Does not match typedefs of an underlying type with the given name. 808/// 809/// Example matches X (Name == "X") 810/// class X; 811/// 812/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X") 813/// namespace a { namespace b { class X; } } 814AST_MATCHER_P(NamedDecl, hasName, std::string, Name) { 815 assert(!Name.empty()); 816 const std::string FullNameString = "::" + Node.getQualifiedNameAsString(); 817 const llvm::StringRef FullName = FullNameString; 818 const llvm::StringRef Pattern = Name; 819 if (Pattern.startswith("::")) { 820 return FullName == Pattern; 821 } else { 822 return FullName.endswith(("::" + Pattern).str()); 823 } 824} 825 826/// \brief Matches NamedDecl nodes whose full names partially match the 827/// given RegExp. 828/// 829/// Supports specifying enclosing namespaces or classes by 830/// prefixing the name with '<enclosing>::'. Does not match typedefs 831/// of an underlying type with the given name. 832/// 833/// Example matches X (regexp == "::X") 834/// class X; 835/// 836/// Example matches X (regexp is one of "::X", "^foo::.*X", among others) 837/// namespace foo { namespace bar { class X; } } 838AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) { 839 assert(!RegExp.empty()); 840 std::string FullNameString = "::" + Node.getQualifiedNameAsString(); 841 llvm::Regex RE(RegExp); 842 return RE.match(FullNameString); 843} 844 845/// \brief Matches overloaded operator names. 846/// 847/// Matches overloaded operator names specified in strings without the 848/// "operator" prefix, such as "<<", for OverloadedOperatorCall's. 849/// 850/// Example matches a << b 851/// (matcher == overloadedOperatorCall(hasOverloadedOperatorName("<<"))) 852/// a << b; 853/// c && d; // assuming both operator<< 854/// // and operator&& are overloaded somewhere. 855AST_MATCHER_P(CXXOperatorCallExpr, 856 hasOverloadedOperatorName, std::string, Name) { 857 return getOperatorSpelling(Node.getOperator()) == Name; 858} 859 860/// \brief Matches C++ classes that are directly or indirectly derived from 861/// a class matching \c Base. 862/// 863/// Note that a class is considered to be also derived from itself. 864/// 865/// Example matches X, Y, Z, C (Base == hasName("X")) 866/// class X; // A class is considered to be derived from itself 867/// class Y : public X {}; // directly derived 868/// class Z : public Y {}; // indirectly derived 869/// typedef X A; 870/// typedef A B; 871/// class C : public B {}; // derived from a typedef of X 872/// 873/// In the following example, Bar matches isDerivedFrom(hasName("X")): 874/// class Foo; 875/// typedef Foo X; 876/// class Bar : public Foo {}; // derived from a type that X is a typedef of 877AST_MATCHER_P(CXXRecordDecl, isDerivedFrom, 878 internal::Matcher<NamedDecl>, Base) { 879 return Finder->classIsDerivedFrom(&Node, Base, Builder); 880} 881 882/// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)). 883inline internal::Matcher<CXXRecordDecl> isDerivedFrom(StringRef BaseName) { 884 assert(!BaseName.empty()); 885 return isDerivedFrom(hasName(BaseName)); 886} 887 888/// \brief Matches AST nodes that have child AST nodes that match the 889/// provided matcher. 890/// 891/// Example matches X, Y (matcher = record(has(record(hasName("X"))) 892/// class X {}; // Matches X, because X::X is a class of name X inside X. 893/// class Y { class X {}; }; 894/// class Z { class Y { class X {}; }; }; // Does not match Z. 895/// 896/// ChildT must be an AST base type. 897template <typename ChildT> 898internal::ArgumentAdaptingMatcher<internal::HasMatcher, ChildT> has( 899 const internal::Matcher<ChildT> &ChildMatcher) { 900 return internal::ArgumentAdaptingMatcher<internal::HasMatcher, 901 ChildT>(ChildMatcher); 902} 903 904/// \brief Matches AST nodes that have descendant AST nodes that match the 905/// provided matcher. 906/// 907/// Example matches X, Y, Z 908/// (matcher = record(hasDescendant(record(hasName("X"))))) 909/// class X {}; // Matches X, because X::X is a class of name X inside X. 910/// class Y { class X {}; }; 911/// class Z { class Y { class X {}; }; }; 912/// 913/// DescendantT must be an AST base type. 914template <typename DescendantT> 915internal::ArgumentAdaptingMatcher<internal::HasDescendantMatcher, DescendantT> 916hasDescendant(const internal::Matcher<DescendantT> &DescendantMatcher) { 917 return internal::ArgumentAdaptingMatcher< 918 internal::HasDescendantMatcher, 919 DescendantT>(DescendantMatcher); 920} 921 922 923/// \brief Matches AST nodes that have child AST nodes that match the 924/// provided matcher. 925/// 926/// Example matches X, Y (matcher = record(forEach(record(hasName("X"))) 927/// class X {}; // Matches X, because X::X is a class of name X inside X. 928/// class Y { class X {}; }; 929/// class Z { class Y { class X {}; }; }; // Does not match Z. 930/// 931/// ChildT must be an AST base type. 932/// 933/// As opposed to 'has', 'forEach' will cause a match for each result that 934/// matches instead of only on the first one. 935template <typename ChildT> 936internal::ArgumentAdaptingMatcher<internal::ForEachMatcher, ChildT> forEach( 937 const internal::Matcher<ChildT>& ChildMatcher) { 938 return internal::ArgumentAdaptingMatcher< 939 internal::ForEachMatcher, 940 ChildT>(ChildMatcher); 941} 942 943/// \brief Matches AST nodes that have descendant AST nodes that match the 944/// provided matcher. 945/// 946/// Example matches X, A, B, C 947/// (matcher = record(forEachDescendant(record(hasName("X"))))) 948/// class X {}; // Matches X, because X::X is a class of name X inside X. 949/// class A { class X {}; }; 950/// class B { class C { class X {}; }; }; 951/// 952/// DescendantT must be an AST base type. 953/// 954/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for 955/// each result that matches instead of only on the first one. 956/// 957/// Note: Recursively combined ForEachDescendant can cause many matches: 958/// record(forEachDescendant(record(forEachDescendant(record())))) 959/// will match 10 times (plus injected class name matches) on: 960/// class A { class B { class C { class D { class E {}; }; }; }; }; 961template <typename DescendantT> 962internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, DescendantT> 963forEachDescendant( 964 const internal::Matcher<DescendantT>& DescendantMatcher) { 965 return internal::ArgumentAdaptingMatcher< 966 internal::ForEachDescendantMatcher, 967 DescendantT>(DescendantMatcher); 968} 969 970/// \brief Matches if the provided matcher does not match. 971/// 972/// Example matches Y (matcher = record(unless(hasName("X")))) 973/// class X {}; 974/// class Y {}; 975template <typename M> 976internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M> unless(const M &InnerMatcher) { 977 return internal::PolymorphicMatcherWithParam1< 978 internal::NotMatcher, M>(InnerMatcher); 979} 980 981/// \brief Matches a type if the declaration of the type matches the given 982/// matcher. 983/// 984/// Usable as: Matcher<QualType>, Matcher<CallExpr>, Matcher<CXXConstructExpr> 985inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher, 986 internal::Matcher<Decl> > 987 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) { 988 return internal::PolymorphicMatcherWithParam1< 989 internal::HasDeclarationMatcher, 990 internal::Matcher<Decl> >(InnerMatcher); 991} 992 993/// \brief Matches on the implicit object argument of a member call expression. 994/// 995/// Example matches y.x() (matcher = call(on(hasType(record(hasName("Y")))))) 996/// class Y { public: void x(); }; 997/// void z() { Y y; y.x(); }", 998/// 999/// FIXME: Overload to allow directly matching types? 1000AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>, 1001 InnerMatcher) { 1002 const Expr *ExprNode = const_cast<CXXMemberCallExpr&>(Node) 1003 .getImplicitObjectArgument() 1004 ->IgnoreParenImpCasts(); 1005 return (ExprNode != NULL && 1006 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1007} 1008 1009/// \brief Matches if the call expression's callee expression matches. 1010/// 1011/// Given 1012/// class Y { void x() { this->x(); x(); Y y; y.x(); } }; 1013/// void f() { f(); } 1014/// call(callee(expression())) 1015/// matches this->x(), x(), y.x(), f() 1016/// with callee(...) 1017/// matching this->x, x, y.x, f respectively 1018/// 1019/// Note: Callee cannot take the more general internal::Matcher<Expr> 1020/// because this introduces ambiguous overloads with calls to Callee taking a 1021/// internal::Matcher<Decl>, as the matcher hierarchy is purely 1022/// implemented in terms of implicit casts. 1023AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>, 1024 InnerMatcher) { 1025 const Expr *ExprNode = Node.getCallee(); 1026 return (ExprNode != NULL && 1027 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1028} 1029 1030/// \brief Matches if the call expression's callee's declaration matches the 1031/// given matcher. 1032/// 1033/// Example matches y.x() (matcher = call(callee(method(hasName("x"))))) 1034/// class Y { public: void x(); }; 1035/// void z() { Y y; y.x(); 1036inline internal::Matcher<CallExpr> callee( 1037 const internal::Matcher<Decl> &InnerMatcher) { 1038 return internal::Matcher<CallExpr>(hasDeclaration(InnerMatcher)); 1039} 1040 1041/// \brief Matches if the expression's or declaration's type matches a type 1042/// matcher. 1043/// 1044/// Example matches x (matcher = expression(hasType( 1045/// hasDeclaration(record(hasName("X")))))) 1046/// and z (matcher = variable(hasType( 1047/// hasDeclaration(record(hasName("X")))))) 1048/// class X {}; 1049/// void y(X &x) { x; X z; } 1050AST_POLYMORPHIC_MATCHER_P(hasType, internal::Matcher<QualType>, 1051 InnerMatcher) { 1052 TOOLING_COMPILE_ASSERT((llvm::is_base_of<Expr, NodeType>::value || 1053 llvm::is_base_of<ValueDecl, NodeType>::value), 1054 instantiated_with_wrong_types); 1055 return InnerMatcher.matches(Node.getType(), Finder, Builder); 1056} 1057 1058/// \brief Overloaded to match the declaration of the expression's or value 1059/// declaration's type. 1060/// 1061/// In case of a value declaration (for example a variable declaration), 1062/// this resolves one layer of indirection. For example, in the value 1063/// declaration "X x;", record(hasName("X")) matches the declaration of X, 1064/// while variable(hasType(record(hasName("X")))) matches the declaration 1065/// of x." 1066/// 1067/// Example matches x (matcher = expression(hasType(record(hasName("X"))))) 1068/// and z (matcher = variable(hasType(record(hasName("X"))))) 1069/// class X {}; 1070/// void y(X &x) { x; X z; } 1071/// 1072/// Usable as: Matcher<Expr>, Matcher<ValueDecl> 1073inline internal::PolymorphicMatcherWithParam1< 1074 internal::matcher_hasTypeMatcher, 1075 internal::Matcher<QualType> > 1076hasType(const internal::Matcher<Decl> &InnerMatcher) { 1077 return hasType(internal::Matcher<QualType>( 1078 hasDeclaration(InnerMatcher))); 1079} 1080 1081/// \brief Matches if the matched type is represented by the given string. 1082/// 1083/// Given 1084/// class Y { public: void x(); }; 1085/// void z() { Y* y; y->x(); } 1086/// call(on(hasType(asString("class Y *")))) 1087/// matches y->x() 1088AST_MATCHER_P(QualType, asString, std::string, Name) { 1089 return Name == Node.getAsString(); 1090} 1091 1092/// \brief Matches if the matched type is a pointer type and the pointee type 1093/// matches the specified matcher. 1094/// 1095/// Example matches y->x() 1096/// (matcher = call(on(hasType(pointsTo(record(hasName("Y"))))))) 1097/// class Y { public: void x(); }; 1098/// void z() { Y *y; y->x(); } 1099AST_MATCHER_P( 1100 QualType, pointsTo, internal::Matcher<QualType>, 1101 InnerMatcher) { 1102 return (!Node.isNull() && Node->isPointerType() && 1103 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1104} 1105 1106/// \brief Overloaded to match the pointee type's declaration. 1107inline internal::Matcher<QualType> pointsTo( 1108 const internal::Matcher<Decl> &InnerMatcher) { 1109 return pointsTo(internal::Matcher<QualType>( 1110 hasDeclaration(InnerMatcher))); 1111} 1112 1113/// \brief Matches if the matched type is a reference type and the referenced 1114/// type matches the specified matcher. 1115/// 1116/// Example matches X &x and const X &y 1117/// (matcher = variable(hasType(references(record(hasName("X")))))) 1118/// class X { 1119/// void a(X b) { 1120/// X &x = b; 1121/// const X &y = b; 1122/// }; 1123AST_MATCHER_P(QualType, references, internal::Matcher<QualType>, 1124 InnerMatcher) { 1125 return (!Node.isNull() && Node->isReferenceType() && 1126 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1127} 1128 1129/// \brief Overloaded to match the referenced type's declaration. 1130inline internal::Matcher<QualType> references( 1131 const internal::Matcher<Decl> &InnerMatcher) { 1132 return references(internal::Matcher<QualType>( 1133 hasDeclaration(InnerMatcher))); 1134} 1135 1136AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument, 1137 internal::Matcher<Expr>, InnerMatcher) { 1138 const Expr *ExprNode = 1139 const_cast<CXXMemberCallExpr&>(Node).getImplicitObjectArgument(); 1140 return (ExprNode != NULL && 1141 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1142} 1143 1144/// \brief Matches if the expression's type either matches the specified 1145/// matcher, or is a pointer to a type that matches the InnerMatcher. 1146inline internal::Matcher<CXXMemberCallExpr> thisPointerType( 1147 const internal::Matcher<QualType> &InnerMatcher) { 1148 return onImplicitObjectArgument( 1149 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 1150} 1151 1152/// \brief Overloaded to match the type's declaration. 1153inline internal::Matcher<CXXMemberCallExpr> thisPointerType( 1154 const internal::Matcher<Decl> &InnerMatcher) { 1155 return onImplicitObjectArgument( 1156 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 1157} 1158 1159/// \brief Matches a DeclRefExpr that refers to a declaration that matches the 1160/// specified matcher. 1161/// 1162/// Example matches x in if(x) 1163/// (matcher = declarationReference(to(variable(hasName("x"))))) 1164/// bool x; 1165/// if (x) {} 1166AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>, 1167 InnerMatcher) { 1168 const Decl *DeclNode = Node.getDecl(); 1169 return (DeclNode != NULL && 1170 InnerMatcher.matches(*DeclNode, Finder, Builder)); 1171} 1172 1173/// \brief Matches a \c DeclRefExpr that refers to a declaration through a 1174/// specific using shadow declaration. 1175/// 1176/// FIXME: This currently only works for functions. Fix. 1177/// 1178/// Given 1179/// namespace a { void f() {} } 1180/// using a::f; 1181/// void g() { 1182/// f(); // Matches this .. 1183/// a::f(); // .. but not this. 1184/// } 1185/// declarationReference(throughUsingDeclaration(anything())) 1186/// matches \c f() 1187AST_MATCHER_P(DeclRefExpr, throughUsingDecl, 1188 internal::Matcher<UsingShadowDecl>, Matcher) { 1189 const NamedDecl *FoundDecl = Node.getFoundDecl(); 1190 if (const UsingShadowDecl *UsingDecl = 1191 llvm::dyn_cast<UsingShadowDecl>(FoundDecl)) 1192 return Matcher.matches(*UsingDecl, Finder, Builder); 1193 return false; 1194} 1195 1196/// \brief Matches a variable declaration that has an initializer expression 1197/// that matches the given matcher. 1198/// 1199/// Example matches x (matcher = variable(hasInitializer(call()))) 1200/// bool y() { return true; } 1201/// bool x = y(); 1202AST_MATCHER_P( 1203 VarDecl, hasInitializer, internal::Matcher<Expr>, 1204 InnerMatcher) { 1205 const Expr *Initializer = Node.getAnyInitializer(); 1206 return (Initializer != NULL && 1207 InnerMatcher.matches(*Initializer, Finder, Builder)); 1208} 1209 1210/// \brief Checks that a call expression or a constructor call expression has 1211/// a specific number of arguments (including absent default arguments). 1212/// 1213/// Example matches f(0, 0) (matcher = call(argumentCountIs(2))) 1214/// void f(int x, int y); 1215/// f(0, 0); 1216AST_POLYMORPHIC_MATCHER_P(argumentCountIs, unsigned, N) { 1217 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 1218 llvm::is_base_of<CXXConstructExpr, 1219 NodeType>::value), 1220 instantiated_with_wrong_types); 1221 return Node.getNumArgs() == N; 1222} 1223 1224/// \brief Matches the n'th argument of a call expression or a constructor 1225/// call expression. 1226/// 1227/// Example matches y in x(y) 1228/// (matcher = call(hasArgument(0, declarationReference()))) 1229/// void x(int) { int y; x(y); } 1230AST_POLYMORPHIC_MATCHER_P2( 1231 hasArgument, unsigned, N, internal::Matcher<Expr>, InnerMatcher) { 1232 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 1233 llvm::is_base_of<CXXConstructExpr, 1234 NodeType>::value), 1235 instantiated_with_wrong_types); 1236 return (N < Node.getNumArgs() && 1237 InnerMatcher.matches( 1238 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder)); 1239} 1240 1241/// \brief Matches a constructor initializer. 1242/// 1243/// Given 1244/// struct Foo { 1245/// Foo() : foo_(1) { } 1246/// int foo_; 1247/// }; 1248/// record(has(constructor(hasAnyConstructorInitializer(anything())))) 1249/// record matches Foo, hasAnyConstructorInitializer matches foo_(1) 1250AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer, 1251 internal::Matcher<CXXCtorInitializer>, InnerMatcher) { 1252 for (CXXConstructorDecl::init_const_iterator I = Node.init_begin(); 1253 I != Node.init_end(); ++I) { 1254 if (InnerMatcher.matches(**I, Finder, Builder)) { 1255 return true; 1256 } 1257 } 1258 return false; 1259} 1260 1261/// \brief Matches the field declaration of a constructor initializer. 1262/// 1263/// Given 1264/// struct Foo { 1265/// Foo() : foo_(1) { } 1266/// int foo_; 1267/// }; 1268/// record(has(constructor(hasAnyConstructorInitializer( 1269/// forField(hasName("foo_")))))) 1270/// matches Foo 1271/// with forField matching foo_ 1272AST_MATCHER_P(CXXCtorInitializer, forField, 1273 internal::Matcher<FieldDecl>, InnerMatcher) { 1274 const FieldDecl *NodeAsDecl = Node.getMember(); 1275 return (NodeAsDecl != NULL && 1276 InnerMatcher.matches(*NodeAsDecl, Finder, Builder)); 1277} 1278 1279/// \brief Matches the initializer expression of a constructor initializer. 1280/// 1281/// Given 1282/// struct Foo { 1283/// Foo() : foo_(1) { } 1284/// int foo_; 1285/// }; 1286/// record(has(constructor(hasAnyConstructorInitializer( 1287/// withInitializer(integerLiteral(equals(1))))))) 1288/// matches Foo 1289/// with withInitializer matching (1) 1290AST_MATCHER_P(CXXCtorInitializer, withInitializer, 1291 internal::Matcher<Expr>, InnerMatcher) { 1292 const Expr* NodeAsExpr = Node.getInit(); 1293 return (NodeAsExpr != NULL && 1294 InnerMatcher.matches(*NodeAsExpr, Finder, Builder)); 1295} 1296 1297/// \brief Matches a contructor initializer if it is explicitly written in 1298/// code (as opposed to implicitly added by the compiler). 1299/// 1300/// Given 1301/// struct Foo { 1302/// Foo() { } 1303/// Foo(int) : foo_("A") { } 1304/// string foo_; 1305/// }; 1306/// constructor(hasAnyConstructorInitializer(isWritten())) 1307/// will match Foo(int), but not Foo() 1308AST_MATCHER(CXXCtorInitializer, isWritten) { 1309 return Node.isWritten(); 1310} 1311 1312/// \brief Matches a constructor declaration that has been implicitly added 1313/// by the compiler (eg. implicit default/copy constructors). 1314AST_MATCHER(CXXConstructorDecl, isImplicit) { 1315 return Node.isImplicit(); 1316} 1317 1318/// \brief Matches any argument of a call expression or a constructor call 1319/// expression. 1320/// 1321/// Given 1322/// void x(int, int, int) { int y; x(1, y, 42); } 1323/// call(hasAnyArgument(declarationReference())) 1324/// matches x(1, y, 42) 1325/// with hasAnyArgument(...) 1326/// matching y 1327AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, internal::Matcher<Expr>, 1328 InnerMatcher) { 1329 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 1330 llvm::is_base_of<CXXConstructExpr, 1331 NodeType>::value), 1332 instantiated_with_wrong_types); 1333 for (unsigned I = 0; I < Node.getNumArgs(); ++I) { 1334 if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(), 1335 Finder, Builder)) { 1336 return true; 1337 } 1338 } 1339 return false; 1340} 1341 1342/// \brief Matches the n'th parameter of a function declaration. 1343/// 1344/// Given 1345/// class X { void f(int x) {} }; 1346/// method(hasParameter(0, hasType(variable()))) 1347/// matches f(int x) {} 1348/// with hasParameter(...) 1349/// matching int x 1350AST_MATCHER_P2(FunctionDecl, hasParameter, 1351 unsigned, N, internal::Matcher<ParmVarDecl>, 1352 InnerMatcher) { 1353 return (N < Node.getNumParams() && 1354 InnerMatcher.matches( 1355 *Node.getParamDecl(N), Finder, Builder)); 1356} 1357 1358/// \brief Matches any parameter of a function declaration. 1359/// 1360/// Does not match the 'this' parameter of a method. 1361/// 1362/// Given 1363/// class X { void f(int x, int y, int z) {} }; 1364/// method(hasAnyParameter(hasName("y"))) 1365/// matches f(int x, int y, int z) {} 1366/// with hasAnyParameter(...) 1367/// matching int y 1368AST_MATCHER_P(FunctionDecl, hasAnyParameter, 1369 internal::Matcher<ParmVarDecl>, InnerMatcher) { 1370 for (unsigned I = 0; I < Node.getNumParams(); ++I) { 1371 if (InnerMatcher.matches(*Node.getParamDecl(I), Finder, Builder)) { 1372 return true; 1373 } 1374 } 1375 return false; 1376} 1377 1378/// \brief Matches the return type of a function declaration. 1379/// 1380/// Given: 1381/// class X { int f() { return 1; } }; 1382/// method(returns(asString("int"))) 1383/// matches int f() { return 1; } 1384AST_MATCHER_P(FunctionDecl, returns, internal::Matcher<QualType>, Matcher) { 1385 return Matcher.matches(Node.getResultType(), Finder, Builder); 1386} 1387 1388/// \brief Matches extern "C" function declarations. 1389/// 1390/// Given: 1391/// extern "C" void f() {} 1392/// extern "C" { void g() {} } 1393/// void h() {} 1394/// function(isExternC()) 1395/// matches the declaration of f and g, but not the declaration h 1396AST_MATCHER(FunctionDecl, isExternC) { 1397 return Node.isExternC(); 1398} 1399 1400/// \brief Matches the condition expression of an if statement, for loop, 1401/// or conditional operator. 1402/// 1403/// Example matches true (matcher = hasCondition(boolLiteral(equals(true)))) 1404/// if (true) {} 1405AST_POLYMORPHIC_MATCHER_P(hasCondition, internal::Matcher<Expr>, 1406 InnerMatcher) { 1407 TOOLING_COMPILE_ASSERT( 1408 (llvm::is_base_of<IfStmt, NodeType>::value) || 1409 (llvm::is_base_of<ForStmt, NodeType>::value) || 1410 (llvm::is_base_of<WhileStmt, NodeType>::value) || 1411 (llvm::is_base_of<DoStmt, NodeType>::value) || 1412 (llvm::is_base_of<ConditionalOperator, NodeType>::value), 1413 has_condition_requires_if_statement_conditional_operator_or_loop); 1414 const Expr *const Condition = Node.getCond(); 1415 return (Condition != NULL && 1416 InnerMatcher.matches(*Condition, Finder, Builder)); 1417} 1418 1419/// \brief Matches the condition variable statement in an if statement. 1420/// 1421/// Given 1422/// if (A* a = GetAPointer()) {} 1423/// hasConditionVariableStatment(...) 1424/// matches 'A* a = GetAPointer()'. 1425AST_MATCHER_P(IfStmt, hasConditionVariableStatement, 1426 internal::Matcher<DeclStmt>, InnerMatcher) { 1427 const DeclStmt* const DeclarationStatement = 1428 Node.getConditionVariableDeclStmt(); 1429 return DeclarationStatement != NULL && 1430 InnerMatcher.matches(*DeclarationStatement, Finder, Builder); 1431} 1432 1433/// \brief Matches the index expression of an array subscript expression. 1434/// 1435/// Given 1436/// int i[5]; 1437/// void f() { i[1] = 42; } 1438/// arraySubscriptExpression(hasIndex(integerLiteral())) 1439/// matches \c i[1] with the \c integerLiteral() matching \c 1 1440AST_MATCHER_P(ArraySubscriptExpr, hasIndex, 1441 internal::Matcher<Expr>, matcher) { 1442 if (const Expr* Expression = Node.getIdx()) 1443 return matcher.matches(*Expression, Finder, Builder); 1444 return false; 1445} 1446 1447/// \brief Matches the base expression of an array subscript expression. 1448/// 1449/// Given 1450/// int i[5]; 1451/// void f() { i[1] = 42; } 1452/// arraySubscriptExpression(hasBase(implicitCast( 1453/// hasSourceExpression(declarationReference())))) 1454/// matches \c i[1] with the \c declarationReference() matching \c i 1455AST_MATCHER_P(ArraySubscriptExpr, hasBase, 1456 internal::Matcher<Expr>, matcher) { 1457 if (const Expr* Expression = Node.getBase()) 1458 return matcher.matches(*Expression, Finder, Builder); 1459 return false; 1460} 1461 1462/// \brief Matches a 'for', 'while', or 'do while' statement that has 1463/// a given body. 1464/// 1465/// Given 1466/// for (;;) {} 1467/// hasBody(compoundStatement()) 1468/// matches 'for (;;) {}' 1469/// with compoundStatement() 1470/// matching '{}' 1471AST_POLYMORPHIC_MATCHER_P(hasBody, internal::Matcher<Stmt>, 1472 InnerMatcher) { 1473 TOOLING_COMPILE_ASSERT( 1474 (llvm::is_base_of<DoStmt, NodeType>::value) || 1475 (llvm::is_base_of<ForStmt, NodeType>::value) || 1476 (llvm::is_base_of<WhileStmt, NodeType>::value), 1477 has_body_requires_for_while_or_do_statement); 1478 const Stmt *const Statement = Node.getBody(); 1479 return (Statement != NULL && 1480 InnerMatcher.matches(*Statement, Finder, Builder)); 1481} 1482 1483/// \brief Matches compound statements where at least one substatement matches 1484/// a given matcher. 1485/// 1486/// Given 1487/// { {}; 1+2; } 1488/// hasAnySubstatement(compoundStatement()) 1489/// matches '{ {}; 1+2; }' 1490/// with compoundStatement() 1491/// matching '{}' 1492AST_MATCHER_P(CompoundStmt, hasAnySubstatement, 1493 internal::Matcher<Stmt>, InnerMatcher) { 1494 for (CompoundStmt::const_body_iterator It = Node.body_begin(); 1495 It != Node.body_end(); 1496 ++It) { 1497 if (InnerMatcher.matches(**It, Finder, Builder)) return true; 1498 } 1499 return false; 1500} 1501 1502/// \brief Checks that a compound statement contains a specific number of 1503/// child statements. 1504/// 1505/// Example: Given 1506/// { for (;;) {} } 1507/// compoundStatement(statementCountIs(0))) 1508/// matches '{}' 1509/// but does not match the outer compound statement. 1510AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) { 1511 return Node.size() == N; 1512} 1513 1514/// \brief Matches literals that are equal to the given value. 1515/// 1516/// Example matches true (matcher = boolLiteral(equals(true))) 1517/// true 1518/// 1519/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>, 1520/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral> 1521template <typename ValueT> 1522internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT> 1523equals(const ValueT &Value) { 1524 return internal::PolymorphicMatcherWithParam1< 1525 internal::ValueEqualsMatcher, 1526 ValueT>(Value); 1527} 1528 1529/// \brief Matches the operator Name of operator expressions (binary or 1530/// unary). 1531/// 1532/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||"))) 1533/// !(a || b) 1534AST_POLYMORPHIC_MATCHER_P(hasOperatorName, std::string, Name) { 1535 TOOLING_COMPILE_ASSERT( 1536 (llvm::is_base_of<BinaryOperator, NodeType>::value) || 1537 (llvm::is_base_of<UnaryOperator, NodeType>::value), 1538 has_condition_requires_if_statement_or_conditional_operator); 1539 return Name == Node.getOpcodeStr(Node.getOpcode()); 1540} 1541 1542/// \brief Matches the left hand side of binary operator expressions. 1543/// 1544/// Example matches a (matcher = binaryOperator(hasLHS())) 1545/// a || b 1546AST_MATCHER_P(BinaryOperator, hasLHS, 1547 internal::Matcher<Expr>, InnerMatcher) { 1548 Expr *LeftHandSide = Node.getLHS(); 1549 return (LeftHandSide != NULL && 1550 InnerMatcher.matches(*LeftHandSide, Finder, Builder)); 1551} 1552 1553/// \brief Matches the right hand side of binary operator expressions. 1554/// 1555/// Example matches b (matcher = binaryOperator(hasRHS())) 1556/// a || b 1557AST_MATCHER_P(BinaryOperator, hasRHS, 1558 internal::Matcher<Expr>, InnerMatcher) { 1559 Expr *RightHandSide = Node.getRHS(); 1560 return (RightHandSide != NULL && 1561 InnerMatcher.matches(*RightHandSide, Finder, Builder)); 1562} 1563 1564/// \brief Matches if either the left hand side or the right hand side of a 1565/// binary operator matches. 1566inline internal::Matcher<BinaryOperator> hasEitherOperand( 1567 const internal::Matcher<Expr> &InnerMatcher) { 1568 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)); 1569} 1570 1571/// \brief Matches if the operand of a unary operator matches. 1572/// 1573/// Example matches true (matcher = hasOperand(boolLiteral(equals(true)))) 1574/// !true 1575AST_MATCHER_P(UnaryOperator, hasUnaryOperand, 1576 internal::Matcher<Expr>, InnerMatcher) { 1577 const Expr * const Operand = Node.getSubExpr(); 1578 return (Operand != NULL && 1579 InnerMatcher.matches(*Operand, Finder, Builder)); 1580} 1581 1582/// \brief Matches if the cast's source expression matches the given matcher. 1583/// 1584/// Example: matches "a string" (matcher = 1585/// hasSourceExpression(constructorCall())) 1586/// 1587/// class URL { URL(string); }; 1588/// URL url = "a string"; 1589AST_MATCHER_P(CastExpr, hasSourceExpression, 1590 internal::Matcher<Expr>, InnerMatcher) { 1591 const Expr* const SubExpression = Node.getSubExpr(); 1592 return (SubExpression != NULL && 1593 InnerMatcher.matches(*SubExpression, Finder, Builder)); 1594} 1595 1596/// \brief Matches casts whose destination type matches a given matcher. 1597/// 1598/// (Note: Clang's AST refers to other conversions as "casts" too, and calls 1599/// actual casts "explicit" casts.) 1600AST_MATCHER_P(ExplicitCastExpr, hasDestinationType, 1601 internal::Matcher<QualType>, InnerMatcher) { 1602 const QualType NodeType = Node.getTypeAsWritten(); 1603 return InnerMatcher.matches(NodeType, Finder, Builder); 1604} 1605 1606/// \brief Matches implicit casts whose destination type matches a given 1607/// matcher. 1608/// 1609/// FIXME: Unit test this matcher 1610AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType, 1611 internal::Matcher<QualType>, InnerMatcher) { 1612 return InnerMatcher.matches(Node.getType(), Finder, Builder); 1613} 1614 1615/// \brief Matches the true branch expression of a conditional operator. 1616/// 1617/// Example matches a 1618/// condition ? a : b 1619AST_MATCHER_P(ConditionalOperator, hasTrueExpression, 1620 internal::Matcher<Expr>, InnerMatcher) { 1621 Expr *Expression = Node.getTrueExpr(); 1622 return (Expression != NULL && 1623 InnerMatcher.matches(*Expression, Finder, Builder)); 1624} 1625 1626/// \brief Matches the false branch expression of a conditional operator. 1627/// 1628/// Example matches b 1629/// condition ? a : b 1630AST_MATCHER_P(ConditionalOperator, hasFalseExpression, 1631 internal::Matcher<Expr>, InnerMatcher) { 1632 Expr *Expression = Node.getFalseExpr(); 1633 return (Expression != NULL && 1634 InnerMatcher.matches(*Expression, Finder, Builder)); 1635} 1636 1637/// \brief Matches if a declaration has a body attached. 1638/// 1639/// Example matches A, va, fa 1640/// class A {}; 1641/// class B; // Doesn't match, as it has no body. 1642/// int va; 1643/// extern int vb; // Doesn't match, as it doesn't define the variable. 1644/// void fa() {} 1645/// void fb(); // Doesn't match, as it has no body. 1646/// 1647/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl> 1648inline internal::PolymorphicMatcherWithParam0<internal::IsDefinitionMatcher> 1649isDefinition() { 1650 return internal::PolymorphicMatcherWithParam0< 1651 internal::IsDefinitionMatcher>(); 1652} 1653 1654/// \brief Matches the class declaration that the given method declaration 1655/// belongs to. 1656/// 1657/// FIXME: Generalize this for other kinds of declarations. 1658/// FIXME: What other kind of declarations would we need to generalize 1659/// this to? 1660/// 1661/// Example matches A() in the last line 1662/// (matcher = constructorCall(hasDeclaration(method( 1663/// ofClass(hasName("A")))))) 1664/// class A { 1665/// public: 1666/// A(); 1667/// }; 1668/// A a = A(); 1669AST_MATCHER_P(CXXMethodDecl, ofClass, 1670 internal::Matcher<CXXRecordDecl>, InnerMatcher) { 1671 const CXXRecordDecl *Parent = Node.getParent(); 1672 return (Parent != NULL && 1673 InnerMatcher.matches(*Parent, Finder, Builder)); 1674} 1675 1676/// \brief Matches member expressions that are called with '->' as opposed 1677/// to '.'. 1678/// 1679/// Member calls on the implicit this pointer match as called with '->'. 1680/// 1681/// Given 1682/// class Y { 1683/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 1684/// int a; 1685/// static int b; 1686/// }; 1687/// memberExpression(isArrow()) 1688/// matches this->x, x, y.x, a, this->b 1689inline internal::Matcher<MemberExpr> isArrow() { 1690 return makeMatcher(new internal::IsArrowMatcher()); 1691} 1692 1693/// \brief Matches QualType nodes that are of integer type. 1694/// 1695/// Given 1696/// void a(int); 1697/// void b(long); 1698/// void c(double); 1699/// function(hasAnyParameter(hasType(isInteger()))) 1700/// matches "a(int)", "b(long)", but not "c(double)". 1701AST_MATCHER(QualType, isInteger) { 1702 return Node->isIntegerType(); 1703} 1704 1705/// \brief Matches QualType nodes that are const-qualified, i.e., that 1706/// include "top-level" const. 1707/// 1708/// Given 1709/// void a(int); 1710/// void b(int const); 1711/// void c(const int); 1712/// void d(const int*); 1713/// void e(int const) {}; 1714/// function(hasAnyParameter(hasType(isConstQualified()))) 1715/// matches "void b(int const)", "void c(const int)" and 1716/// "void e(int const) {}". It does not match d as there 1717/// is no top-level const on the parameter type "const int *". 1718inline internal::Matcher<QualType> isConstQualified() { 1719 return makeMatcher(new internal::IsConstQualifiedMatcher()); 1720} 1721 1722/// \brief Matches a member expression where the member is matched by a 1723/// given matcher. 1724/// 1725/// Given 1726/// struct { int first, second; } first, second; 1727/// int i(second.first); 1728/// int j(first.second); 1729/// memberExpression(member(hasName("first"))) 1730/// matches second.first 1731/// but not first.second (because the member name there is "second"). 1732AST_MATCHER_P(MemberExpr, member, 1733 internal::Matcher<ValueDecl>, InnerMatcher) { 1734 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder); 1735} 1736 1737/// \brief Matches a member expression where the object expression is 1738/// matched by a given matcher. 1739/// 1740/// Given 1741/// struct X { int m; }; 1742/// void f(X x) { x.m; m; } 1743/// memberExpression(hasObjectExpression(hasType(record(hasName("X"))))))) 1744/// matches "x.m" and "m" 1745/// with hasObjectExpression(...) 1746/// matching "x" and the implicit object expression of "m" which has type X*. 1747AST_MATCHER_P(MemberExpr, hasObjectExpression, 1748 internal::Matcher<Expr>, InnerMatcher) { 1749 return InnerMatcher.matches(*Node.getBase(), Finder, Builder); 1750} 1751 1752/// \brief Matches any using shadow declaration. 1753/// 1754/// Given 1755/// namespace X { void b(); } 1756/// using X::b; 1757/// usingDecl(hasAnyUsingShadowDecl(hasName("b")))) 1758/// matches \code using X::b \endcode 1759AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl, 1760 internal::Matcher<UsingShadowDecl>, Matcher) { 1761 for (UsingDecl::shadow_iterator II = Node.shadow_begin(); 1762 II != Node.shadow_end(); ++II) { 1763 if (Matcher.matches(**II, Finder, Builder)) 1764 return true; 1765 } 1766 return false; 1767} 1768 1769/// \brief Matches a using shadow declaration where the target declaration is 1770/// matched by the given matcher. 1771/// 1772/// Given 1773/// namespace X { int a; void b(); } 1774/// using X::a; 1775/// using X::b; 1776/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(function()))) 1777/// matches \code using X::b \endcode 1778/// but not \code using X::a \endcode 1779AST_MATCHER_P(UsingShadowDecl, hasTargetDecl, 1780 internal::Matcher<NamedDecl>, Matcher) { 1781 return Matcher.matches(*Node.getTargetDecl(), Finder, Builder); 1782} 1783 1784/// \brief Matches template instantiations of function, class, or static 1785/// member variable template instantiations. 1786/// 1787/// Given 1788/// template <typename T> class X {}; class A {}; X<A> x; 1789/// or 1790/// template <typename T> class X {}; class A {}; template class X<A>; 1791/// record(hasName("::X"), isTemplateInstantiation()) 1792/// matches the template instantiation of X<A>. 1793/// 1794/// But given 1795/// template <typename T> class X {}; class A {}; 1796/// template <> class X<A> {}; X<A> x; 1797/// record(hasName("::X"), isTemplateInstantiation()) 1798/// does not match, as X<A> is an explicit template specialization. 1799/// 1800/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> 1801inline internal::PolymorphicMatcherWithParam0< 1802 internal::IsTemplateInstantiationMatcher> 1803isTemplateInstantiation() { 1804 return internal::PolymorphicMatcherWithParam0< 1805 internal::IsTemplateInstantiationMatcher>(); 1806} 1807 1808} // end namespace ast_matchers 1809} // end namespace clang 1810 1811#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H 1812