ASTMatchers.h revision 715c9568ee5d75f25dab98229c87bcec880daf5d
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. 983inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher, 984 internal::Matcher<Decl> > 985 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) { 986 return internal::PolymorphicMatcherWithParam1< 987 internal::HasDeclarationMatcher, 988 internal::Matcher<Decl> >(InnerMatcher); 989} 990 991/// \brief Matches on the implicit object argument of a member call expression. 992/// 993/// Example matches y.x() (matcher = call(on(hasType(record(hasName("Y")))))) 994/// class Y { public: void x(); }; 995/// void z() { Y y; y.x(); }", 996/// 997/// FIXME: Overload to allow directly matching types? 998AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>, 999 InnerMatcher) { 1000 const Expr *ExprNode = const_cast<CXXMemberCallExpr&>(Node) 1001 .getImplicitObjectArgument() 1002 ->IgnoreParenImpCasts(); 1003 return (ExprNode != NULL && 1004 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1005} 1006 1007/// \brief Matches if the call expression's callee expression matches. 1008/// 1009/// Given 1010/// class Y { void x() { this->x(); x(); Y y; y.x(); } }; 1011/// void f() { f(); } 1012/// call(callee(expression())) 1013/// matches this->x(), x(), y.x(), f() 1014/// with callee(...) 1015/// matching this->x, x, y.x, f respectively 1016/// 1017/// Note: Callee cannot take the more general internal::Matcher<Expr> 1018/// because this introduces ambiguous overloads with calls to Callee taking a 1019/// internal::Matcher<Decl>, as the matcher hierarchy is purely 1020/// implemented in terms of implicit casts. 1021AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>, 1022 InnerMatcher) { 1023 const Expr *ExprNode = Node.getCallee(); 1024 return (ExprNode != NULL && 1025 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1026} 1027 1028/// \brief Matches if the call expression's callee's declaration matches the 1029/// given matcher. 1030/// 1031/// Example matches y.x() (matcher = call(callee(method(hasName("x"))))) 1032/// class Y { public: void x(); }; 1033/// void z() { Y y; y.x(); 1034inline internal::Matcher<CallExpr> callee( 1035 const internal::Matcher<Decl> &InnerMatcher) { 1036 return internal::Matcher<CallExpr>(hasDeclaration(InnerMatcher)); 1037} 1038 1039/// \brief Matches if the expression's or declaration's type matches a type 1040/// matcher. 1041/// 1042/// Example matches x (matcher = expression(hasType( 1043/// hasDeclaration(record(hasName("X")))))) 1044/// and z (matcher = variable(hasType( 1045/// hasDeclaration(record(hasName("X")))))) 1046/// class X {}; 1047/// void y(X &x) { x; X z; } 1048AST_POLYMORPHIC_MATCHER_P(hasType, internal::Matcher<QualType>, 1049 InnerMatcher) { 1050 TOOLING_COMPILE_ASSERT((llvm::is_base_of<Expr, NodeType>::value || 1051 llvm::is_base_of<ValueDecl, NodeType>::value), 1052 instantiated_with_wrong_types); 1053 return InnerMatcher.matches(Node.getType(), Finder, Builder); 1054} 1055 1056/// \brief Overloaded to match the declaration of the expression's or value 1057/// declaration's type. 1058/// 1059/// In case of a value declaration (for example a variable declaration), 1060/// this resolves one layer of indirection. For example, in the value 1061/// declaration "X x;", record(hasName("X")) matches the declaration of X, 1062/// while variable(hasType(record(hasName("X")))) matches the declaration 1063/// of x." 1064/// 1065/// Example matches x (matcher = expression(hasType(record(hasName("X"))))) 1066/// and z (matcher = variable(hasType(record(hasName("X"))))) 1067/// class X {}; 1068/// void y(X &x) { x; X z; } 1069inline internal::PolymorphicMatcherWithParam1< 1070 internal::matcher_hasTypeMatcher, 1071 internal::Matcher<QualType> > 1072hasType(const internal::Matcher<Decl> &InnerMatcher) { 1073 return hasType(internal::Matcher<QualType>( 1074 hasDeclaration(InnerMatcher))); 1075} 1076 1077/// \brief Matches if the matched type is represented by the given string. 1078/// 1079/// Given 1080/// class Y { public: void x(); }; 1081/// void z() { Y* y; y->x(); } 1082/// call(on(hasType(asString("class Y *")))) 1083/// matches y->x() 1084AST_MATCHER_P(QualType, asString, std::string, Name) { 1085 return Name == Node.getAsString(); 1086} 1087 1088/// \brief Matches if the matched type is a pointer type and the pointee type 1089/// matches the specified matcher. 1090/// 1091/// Example matches y->x() 1092/// (matcher = call(on(hasType(pointsTo(record(hasName("Y"))))))) 1093/// class Y { public: void x(); }; 1094/// void z() { Y *y; y->x(); } 1095AST_MATCHER_P( 1096 QualType, pointsTo, internal::Matcher<QualType>, 1097 InnerMatcher) { 1098 return (!Node.isNull() && Node->isPointerType() && 1099 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1100} 1101 1102/// \brief Overloaded to match the pointee type's declaration. 1103inline internal::Matcher<QualType> pointsTo( 1104 const internal::Matcher<Decl> &InnerMatcher) { 1105 return pointsTo(internal::Matcher<QualType>( 1106 hasDeclaration(InnerMatcher))); 1107} 1108 1109/// \brief Matches if the matched type is a reference type and the referenced 1110/// type matches the specified matcher. 1111/// 1112/// Example matches X &x and const X &y 1113/// (matcher = variable(hasType(references(record(hasName("X")))))) 1114/// class X { 1115/// void a(X b) { 1116/// X &x = b; 1117/// const X &y = b; 1118/// }; 1119AST_MATCHER_P(QualType, references, internal::Matcher<QualType>, 1120 InnerMatcher) { 1121 return (!Node.isNull() && Node->isReferenceType() && 1122 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1123} 1124 1125/// \brief Overloaded to match the referenced type's declaration. 1126inline internal::Matcher<QualType> references( 1127 const internal::Matcher<Decl> &InnerMatcher) { 1128 return references(internal::Matcher<QualType>( 1129 hasDeclaration(InnerMatcher))); 1130} 1131 1132AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument, 1133 internal::Matcher<Expr>, InnerMatcher) { 1134 const Expr *ExprNode = 1135 const_cast<CXXMemberCallExpr&>(Node).getImplicitObjectArgument(); 1136 return (ExprNode != NULL && 1137 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1138} 1139 1140/// \brief Matches if the expression's type either matches the specified 1141/// matcher, or is a pointer to a type that matches the InnerMatcher. 1142inline internal::Matcher<CXXMemberCallExpr> thisPointerType( 1143 const internal::Matcher<QualType> &InnerMatcher) { 1144 return onImplicitObjectArgument( 1145 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 1146} 1147 1148/// \brief Overloaded to match the type's declaration. 1149inline internal::Matcher<CXXMemberCallExpr> thisPointerType( 1150 const internal::Matcher<Decl> &InnerMatcher) { 1151 return onImplicitObjectArgument( 1152 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 1153} 1154 1155/// \brief Matches a DeclRefExpr that refers to a declaration that matches the 1156/// specified matcher. 1157/// 1158/// Example matches x in if(x) 1159/// (matcher = declarationReference(to(variable(hasName("x"))))) 1160/// bool x; 1161/// if (x) {} 1162AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>, 1163 InnerMatcher) { 1164 const Decl *DeclNode = Node.getDecl(); 1165 return (DeclNode != NULL && 1166 InnerMatcher.matches(*DeclNode, Finder, Builder)); 1167} 1168 1169/// \brief Matches a \c DeclRefExpr that refers to a declaration through a 1170/// specific using shadow declaration. 1171/// 1172/// FIXME: This currently only works for functions. Fix. 1173/// 1174/// Given 1175/// namespace a { void f() {} } 1176/// using a::f; 1177/// void g() { 1178/// f(); // Matches this .. 1179/// a::f(); // .. but not this. 1180/// } 1181/// declarationReference(throughUsingDeclaration(anything())) 1182/// matches \c f() 1183AST_MATCHER_P(DeclRefExpr, throughUsingDecl, 1184 internal::Matcher<UsingShadowDecl>, Matcher) { 1185 const NamedDecl *FoundDecl = Node.getFoundDecl(); 1186 if (const UsingShadowDecl *UsingDecl = 1187 llvm::dyn_cast<UsingShadowDecl>(FoundDecl)) 1188 return Matcher.matches(*UsingDecl, Finder, Builder); 1189 return false; 1190} 1191 1192/// \brief Matches a variable declaration that has an initializer expression 1193/// that matches the given matcher. 1194/// 1195/// Example matches x (matcher = variable(hasInitializer(call()))) 1196/// bool y() { return true; } 1197/// bool x = y(); 1198AST_MATCHER_P( 1199 VarDecl, hasInitializer, internal::Matcher<Expr>, 1200 InnerMatcher) { 1201 const Expr *Initializer = Node.getAnyInitializer(); 1202 return (Initializer != NULL && 1203 InnerMatcher.matches(*Initializer, Finder, Builder)); 1204} 1205 1206/// \brief Checks that a call expression or a constructor call expression has 1207/// a specific number of arguments (including absent default arguments). 1208/// 1209/// Example matches f(0, 0) (matcher = call(argumentCountIs(2))) 1210/// void f(int x, int y); 1211/// f(0, 0); 1212AST_POLYMORPHIC_MATCHER_P(argumentCountIs, unsigned, N) { 1213 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 1214 llvm::is_base_of<CXXConstructExpr, 1215 NodeType>::value), 1216 instantiated_with_wrong_types); 1217 return Node.getNumArgs() == N; 1218} 1219 1220/// \brief Matches the n'th argument of a call expression or a constructor 1221/// call expression. 1222/// 1223/// Example matches y in x(y) 1224/// (matcher = call(hasArgument(0, declarationReference()))) 1225/// void x(int) { int y; x(y); } 1226AST_POLYMORPHIC_MATCHER_P2( 1227 hasArgument, unsigned, N, internal::Matcher<Expr>, InnerMatcher) { 1228 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 1229 llvm::is_base_of<CXXConstructExpr, 1230 NodeType>::value), 1231 instantiated_with_wrong_types); 1232 return (N < Node.getNumArgs() && 1233 InnerMatcher.matches( 1234 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder)); 1235} 1236 1237/// \brief Matches a constructor initializer. 1238/// 1239/// Given 1240/// struct Foo { 1241/// Foo() : foo_(1) { } 1242/// int foo_; 1243/// }; 1244/// record(has(constructor(hasAnyConstructorInitializer(anything())))) 1245/// record matches Foo, hasAnyConstructorInitializer matches foo_(1) 1246AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer, 1247 internal::Matcher<CXXCtorInitializer>, InnerMatcher) { 1248 for (CXXConstructorDecl::init_const_iterator I = Node.init_begin(); 1249 I != Node.init_end(); ++I) { 1250 if (InnerMatcher.matches(**I, Finder, Builder)) { 1251 return true; 1252 } 1253 } 1254 return false; 1255} 1256 1257/// \brief Matches the field declaration of a constructor initializer. 1258/// 1259/// Given 1260/// struct Foo { 1261/// Foo() : foo_(1) { } 1262/// int foo_; 1263/// }; 1264/// record(has(constructor(hasAnyConstructorInitializer( 1265/// forField(hasName("foo_")))))) 1266/// matches Foo 1267/// with forField matching foo_ 1268AST_MATCHER_P(CXXCtorInitializer, forField, 1269 internal::Matcher<FieldDecl>, InnerMatcher) { 1270 const FieldDecl *NodeAsDecl = Node.getMember(); 1271 return (NodeAsDecl != NULL && 1272 InnerMatcher.matches(*NodeAsDecl, Finder, Builder)); 1273} 1274 1275/// \brief Matches the initializer expression of a constructor initializer. 1276/// 1277/// Given 1278/// struct Foo { 1279/// Foo() : foo_(1) { } 1280/// int foo_; 1281/// }; 1282/// record(has(constructor(hasAnyConstructorInitializer( 1283/// withInitializer(integerLiteral(equals(1))))))) 1284/// matches Foo 1285/// with withInitializer matching (1) 1286AST_MATCHER_P(CXXCtorInitializer, withInitializer, 1287 internal::Matcher<Expr>, InnerMatcher) { 1288 const Expr* NodeAsExpr = Node.getInit(); 1289 return (NodeAsExpr != NULL && 1290 InnerMatcher.matches(*NodeAsExpr, Finder, Builder)); 1291} 1292 1293/// \brief Matches a contructor initializer if it is explicitly written in 1294/// code (as opposed to implicitly added by the compiler). 1295/// 1296/// Given 1297/// struct Foo { 1298/// Foo() { } 1299/// Foo(int) : foo_("A") { } 1300/// string foo_; 1301/// }; 1302/// constructor(hasAnyConstructorInitializer(isWritten())) 1303/// will match Foo(int), but not Foo() 1304AST_MATCHER(CXXCtorInitializer, isWritten) { 1305 return Node.isWritten(); 1306} 1307 1308/// \brief Matches a constructor declaration that has been implicitly added 1309/// by the compiler (eg. implicit default/copy constructors). 1310AST_MATCHER(CXXConstructorDecl, isImplicit) { 1311 return Node.isImplicit(); 1312} 1313 1314/// \brief Matches any argument of a call expression or a constructor call 1315/// expression. 1316/// 1317/// Given 1318/// void x(int, int, int) { int y; x(1, y, 42); } 1319/// call(hasAnyArgument(declarationReference())) 1320/// matches x(1, y, 42) 1321/// with hasAnyArgument(...) 1322/// matching y 1323AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, internal::Matcher<Expr>, 1324 InnerMatcher) { 1325 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 1326 llvm::is_base_of<CXXConstructExpr, 1327 NodeType>::value), 1328 instantiated_with_wrong_types); 1329 for (unsigned I = 0; I < Node.getNumArgs(); ++I) { 1330 if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(), 1331 Finder, Builder)) { 1332 return true; 1333 } 1334 } 1335 return false; 1336} 1337 1338/// \brief Matches the n'th parameter of a function declaration. 1339/// 1340/// Given 1341/// class X { void f(int x) {} }; 1342/// method(hasParameter(0, hasType(variable()))) 1343/// matches f(int x) {} 1344/// with hasParameter(...) 1345/// matching int x 1346AST_MATCHER_P2(FunctionDecl, hasParameter, 1347 unsigned, N, internal::Matcher<ParmVarDecl>, 1348 InnerMatcher) { 1349 return (N < Node.getNumParams() && 1350 InnerMatcher.matches( 1351 *Node.getParamDecl(N), Finder, Builder)); 1352} 1353 1354/// \brief Matches any parameter of a function declaration. 1355/// 1356/// Does not match the 'this' parameter of a method. 1357/// 1358/// Given 1359/// class X { void f(int x, int y, int z) {} }; 1360/// method(hasAnyParameter(hasName("y"))) 1361/// matches f(int x, int y, int z) {} 1362/// with hasAnyParameter(...) 1363/// matching int y 1364AST_MATCHER_P(FunctionDecl, hasAnyParameter, 1365 internal::Matcher<ParmVarDecl>, InnerMatcher) { 1366 for (unsigned I = 0; I < Node.getNumParams(); ++I) { 1367 if (InnerMatcher.matches(*Node.getParamDecl(I), Finder, Builder)) { 1368 return true; 1369 } 1370 } 1371 return false; 1372} 1373 1374/// \brief Matches the return type of a function declaration. 1375/// 1376/// Given: 1377/// class X { int f() { return 1; } }; 1378/// method(returns(asString("int"))) 1379/// matches int f() { return 1; } 1380AST_MATCHER_P(FunctionDecl, returns, internal::Matcher<QualType>, Matcher) { 1381 return Matcher.matches(Node.getResultType(), Finder, Builder); 1382} 1383 1384/// \brief Matches the condition expression of an if statement, for loop, 1385/// or conditional operator. 1386/// 1387/// Example matches true (matcher = hasCondition(boolLiteral(equals(true)))) 1388/// if (true) {} 1389AST_POLYMORPHIC_MATCHER_P(hasCondition, internal::Matcher<Expr>, 1390 InnerMatcher) { 1391 TOOLING_COMPILE_ASSERT( 1392 (llvm::is_base_of<IfStmt, NodeType>::value) || 1393 (llvm::is_base_of<ForStmt, NodeType>::value) || 1394 (llvm::is_base_of<WhileStmt, NodeType>::value) || 1395 (llvm::is_base_of<DoStmt, NodeType>::value) || 1396 (llvm::is_base_of<ConditionalOperator, NodeType>::value), 1397 has_condition_requires_if_statement_conditional_operator_or_loop); 1398 const Expr *const Condition = Node.getCond(); 1399 return (Condition != NULL && 1400 InnerMatcher.matches(*Condition, Finder, Builder)); 1401} 1402 1403/// \brief Matches the condition variable statement in an if statement. 1404/// 1405/// Given 1406/// if (A* a = GetAPointer()) {} 1407/// hasConditionVariableStatment(...) 1408/// matches 'A* a = GetAPointer()'. 1409AST_MATCHER_P(IfStmt, hasConditionVariableStatement, 1410 internal::Matcher<DeclStmt>, InnerMatcher) { 1411 const DeclStmt* const DeclarationStatement = 1412 Node.getConditionVariableDeclStmt(); 1413 return DeclarationStatement != NULL && 1414 InnerMatcher.matches(*DeclarationStatement, Finder, Builder); 1415} 1416 1417/// \brief Matches the index expression of an array subscript expression. 1418/// 1419/// Given 1420/// int i[5]; 1421/// void f() { i[1] = 42; } 1422/// arraySubscriptExpression(hasIndex(integerLiteral())) 1423/// matches \c i[1] with the \c integerLiteral() matching \c 1 1424AST_MATCHER_P(ArraySubscriptExpr, hasIndex, 1425 internal::Matcher<Expr>, matcher) { 1426 if (const Expr* Expression = Node.getIdx()) 1427 return matcher.matches(*Expression, Finder, Builder); 1428 return false; 1429} 1430 1431/// \brief Matches the base expression of an array subscript expression. 1432/// 1433/// Given 1434/// int i[5]; 1435/// void f() { i[1] = 42; } 1436/// arraySubscriptExpression(hasBase(implicitCast( 1437/// hasSourceExpression(declarationReference())))) 1438/// matches \c i[1] with the \c declarationReference() matching \c i 1439AST_MATCHER_P(ArraySubscriptExpr, hasBase, 1440 internal::Matcher<Expr>, matcher) { 1441 if (const Expr* Expression = Node.getBase()) 1442 return matcher.matches(*Expression, Finder, Builder); 1443 return false; 1444} 1445 1446/// \brief Matches a 'for', 'while', or 'do while' statement that has 1447/// a given body. 1448/// 1449/// Given 1450/// for (;;) {} 1451/// hasBody(compoundStatement()) 1452/// matches 'for (;;) {}' 1453/// with compoundStatement() 1454/// matching '{}' 1455AST_POLYMORPHIC_MATCHER_P(hasBody, internal::Matcher<Stmt>, 1456 InnerMatcher) { 1457 TOOLING_COMPILE_ASSERT( 1458 (llvm::is_base_of<DoStmt, NodeType>::value) || 1459 (llvm::is_base_of<ForStmt, NodeType>::value) || 1460 (llvm::is_base_of<WhileStmt, NodeType>::value), 1461 has_body_requires_for_while_or_do_statement); 1462 const Stmt *const Statement = Node.getBody(); 1463 return (Statement != NULL && 1464 InnerMatcher.matches(*Statement, Finder, Builder)); 1465} 1466 1467/// \brief Matches compound statements where at least one substatement matches 1468/// a given matcher. 1469/// 1470/// Given 1471/// { {}; 1+2; } 1472/// hasAnySubstatement(compoundStatement()) 1473/// matches '{ {}; 1+2; }' 1474/// with compoundStatement() 1475/// matching '{}' 1476AST_MATCHER_P(CompoundStmt, hasAnySubstatement, 1477 internal::Matcher<Stmt>, InnerMatcher) { 1478 for (CompoundStmt::const_body_iterator It = Node.body_begin(); 1479 It != Node.body_end(); 1480 ++It) { 1481 if (InnerMatcher.matches(**It, Finder, Builder)) return true; 1482 } 1483 return false; 1484} 1485 1486/// \brief Checks that a compound statement contains a specific number of 1487/// child statements. 1488/// 1489/// Example: Given 1490/// { for (;;) {} } 1491/// compoundStatement(statementCountIs(0))) 1492/// matches '{}' 1493/// but does not match the outer compound statement. 1494AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) { 1495 return Node.size() == N; 1496} 1497 1498/// \brief Matches literals that are equal to the given value. 1499/// 1500/// Example matches true (matcher = boolLiteral(equals(true))) 1501/// true 1502template <typename ValueT> 1503internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT> 1504equals(const ValueT &Value) { 1505 return internal::PolymorphicMatcherWithParam1< 1506 internal::ValueEqualsMatcher, 1507 ValueT>(Value); 1508} 1509 1510/// \brief Matches the operator Name of operator expressions (binary or 1511/// unary). 1512/// 1513/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||"))) 1514/// !(a || b) 1515AST_POLYMORPHIC_MATCHER_P(hasOperatorName, std::string, Name) { 1516 TOOLING_COMPILE_ASSERT( 1517 (llvm::is_base_of<BinaryOperator, NodeType>::value) || 1518 (llvm::is_base_of<UnaryOperator, NodeType>::value), 1519 has_condition_requires_if_statement_or_conditional_operator); 1520 return Name == Node.getOpcodeStr(Node.getOpcode()); 1521} 1522 1523/// \brief Matches the left hand side of binary operator expressions. 1524/// 1525/// Example matches a (matcher = binaryOperator(hasLHS())) 1526/// a || b 1527AST_MATCHER_P(BinaryOperator, hasLHS, 1528 internal::Matcher<Expr>, InnerMatcher) { 1529 Expr *LeftHandSide = Node.getLHS(); 1530 return (LeftHandSide != NULL && 1531 InnerMatcher.matches(*LeftHandSide, Finder, Builder)); 1532} 1533 1534/// \brief Matches the right hand side of binary operator expressions. 1535/// 1536/// Example matches b (matcher = binaryOperator(hasRHS())) 1537/// a || b 1538AST_MATCHER_P(BinaryOperator, hasRHS, 1539 internal::Matcher<Expr>, InnerMatcher) { 1540 Expr *RightHandSide = Node.getRHS(); 1541 return (RightHandSide != NULL && 1542 InnerMatcher.matches(*RightHandSide, Finder, Builder)); 1543} 1544 1545/// \brief Matches if either the left hand side or the right hand side of a 1546/// binary operator matches. 1547inline internal::Matcher<BinaryOperator> hasEitherOperand( 1548 const internal::Matcher<Expr> &InnerMatcher) { 1549 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)); 1550} 1551 1552/// \brief Matches if the operand of a unary operator matches. 1553/// 1554/// Example matches true (matcher = hasOperand(boolLiteral(equals(true)))) 1555/// !true 1556AST_MATCHER_P(UnaryOperator, hasUnaryOperand, 1557 internal::Matcher<Expr>, InnerMatcher) { 1558 const Expr * const Operand = Node.getSubExpr(); 1559 return (Operand != NULL && 1560 InnerMatcher.matches(*Operand, Finder, Builder)); 1561} 1562 1563/// \brief Matches if the cast's source expression matches the given matcher. 1564/// 1565/// Example: matches "a string" (matcher = 1566/// hasSourceExpression(constructorCall())) 1567/// 1568/// class URL { URL(string); }; 1569/// URL url = "a string"; 1570AST_MATCHER_P(CastExpr, hasSourceExpression, 1571 internal::Matcher<Expr>, InnerMatcher) { 1572 const Expr* const SubExpression = Node.getSubExpr(); 1573 return (SubExpression != NULL && 1574 InnerMatcher.matches(*SubExpression, Finder, Builder)); 1575} 1576 1577/// \brief Matches casts whose destination type matches a given matcher. 1578/// 1579/// (Note: Clang's AST refers to other conversions as "casts" too, and calls 1580/// actual casts "explicit" casts.) 1581AST_MATCHER_P(ExplicitCastExpr, hasDestinationType, 1582 internal::Matcher<QualType>, InnerMatcher) { 1583 const QualType NodeType = Node.getTypeAsWritten(); 1584 return InnerMatcher.matches(NodeType, Finder, Builder); 1585} 1586 1587/// \brief Matches implicit casts whose destination type matches a given 1588/// matcher. 1589/// 1590/// FIXME: Unit test this matcher 1591AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType, 1592 internal::Matcher<QualType>, InnerMatcher) { 1593 return InnerMatcher.matches(Node.getType(), Finder, Builder); 1594} 1595 1596/// \brief Matches the true branch expression of a conditional operator. 1597/// 1598/// Example matches a 1599/// condition ? a : b 1600AST_MATCHER_P(ConditionalOperator, hasTrueExpression, 1601 internal::Matcher<Expr>, InnerMatcher) { 1602 Expr *Expression = Node.getTrueExpr(); 1603 return (Expression != NULL && 1604 InnerMatcher.matches(*Expression, Finder, Builder)); 1605} 1606 1607/// \brief Matches the false branch expression of a conditional operator. 1608/// 1609/// Example matches b 1610/// condition ? a : b 1611AST_MATCHER_P(ConditionalOperator, hasFalseExpression, 1612 internal::Matcher<Expr>, InnerMatcher) { 1613 Expr *Expression = Node.getFalseExpr(); 1614 return (Expression != NULL && 1615 InnerMatcher.matches(*Expression, Finder, Builder)); 1616} 1617 1618/// \brief Matches if a declaration has a body attached. 1619/// 1620/// Example matches A, va, fa 1621/// class A {}; 1622/// class B; // Doesn't match, as it has no body. 1623/// int va; 1624/// extern int vb; // Doesn't match, as it doesn't define the variable. 1625/// void fa() {} 1626/// void fb(); // Doesn't match, as it has no body. 1627inline internal::PolymorphicMatcherWithParam0<internal::IsDefinitionMatcher> 1628isDefinition() { 1629 return internal::PolymorphicMatcherWithParam0< 1630 internal::IsDefinitionMatcher>(); 1631} 1632 1633/// \brief Matches the class declaration that the given method declaration 1634/// belongs to. 1635/// 1636/// FIXME: Generalize this for other kinds of declarations. 1637/// FIXME: What other kind of declarations would we need to generalize 1638/// this to? 1639/// 1640/// Example matches A() in the last line 1641/// (matcher = constructorCall(hasDeclaration(method( 1642/// ofClass(hasName("A")))))) 1643/// class A { 1644/// public: 1645/// A(); 1646/// }; 1647/// A a = A(); 1648AST_MATCHER_P(CXXMethodDecl, ofClass, 1649 internal::Matcher<CXXRecordDecl>, InnerMatcher) { 1650 const CXXRecordDecl *Parent = Node.getParent(); 1651 return (Parent != NULL && 1652 InnerMatcher.matches(*Parent, Finder, Builder)); 1653} 1654 1655/// \brief Matches member expressions that are called with '->' as opposed 1656/// to '.'. 1657/// 1658/// Member calls on the implicit this pointer match as called with '->'. 1659/// 1660/// Given 1661/// class Y { 1662/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 1663/// int a; 1664/// static int b; 1665/// }; 1666/// memberExpression(isArrow()) 1667/// matches this->x, x, y.x, a, this->b 1668inline internal::Matcher<MemberExpr> isArrow() { 1669 return makeMatcher(new internal::IsArrowMatcher()); 1670} 1671 1672/// \brief Matches QualType nodes that are of integer type. 1673/// 1674/// Given 1675/// void a(int); 1676/// void b(long); 1677/// void c(double); 1678/// function(hasAnyParameter(hasType(isInteger()))) 1679/// matches "a(int)", "b(long)", but not "c(double)". 1680AST_MATCHER(QualType, isInteger) { 1681 return Node->isIntegerType(); 1682} 1683 1684/// \brief Matches QualType nodes that are const-qualified, i.e., that 1685/// include "top-level" const. 1686/// 1687/// Given 1688/// void a(int); 1689/// void b(int const); 1690/// void c(const int); 1691/// void d(const int*); 1692/// void e(int const) {}; 1693/// function(hasAnyParameter(hasType(isConstQualified()))) 1694/// matches "void b(int const)", "void c(const int)" and 1695/// "void e(int const) {}". It does not match d as there 1696/// is no top-level const on the parameter type "const int *". 1697inline internal::Matcher<QualType> isConstQualified() { 1698 return makeMatcher(new internal::IsConstQualifiedMatcher()); 1699} 1700 1701/// \brief Matches a member expression where the member is matched by a 1702/// given matcher. 1703/// 1704/// Given 1705/// struct { int first, second; } first, second; 1706/// int i(second.first); 1707/// int j(first.second); 1708/// memberExpression(member(hasName("first"))) 1709/// matches second.first 1710/// but not first.second (because the member name there is "second"). 1711AST_MATCHER_P(MemberExpr, member, 1712 internal::Matcher<ValueDecl>, InnerMatcher) { 1713 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder); 1714} 1715 1716/// \brief Matches a member expression where the object expression is 1717/// matched by a given matcher. 1718/// 1719/// Given 1720/// struct X { int m; }; 1721/// void f(X x) { x.m; m; } 1722/// memberExpression(hasObjectExpression(hasType(record(hasName("X"))))))) 1723/// matches "x.m" and "m" 1724/// with hasObjectExpression(...) 1725/// matching "x" and the implicit object expression of "m" which has type X*. 1726AST_MATCHER_P(MemberExpr, hasObjectExpression, 1727 internal::Matcher<Expr>, InnerMatcher) { 1728 return InnerMatcher.matches(*Node.getBase(), Finder, Builder); 1729} 1730 1731/// \brief Matches any using shadow declaration. 1732/// 1733/// Given 1734/// namespace X { void b(); } 1735/// using X::b; 1736/// usingDecl(hasAnyUsingShadowDecl(hasName("b")))) 1737/// matches \code using X::b \endcode 1738AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl, 1739 internal::Matcher<UsingShadowDecl>, Matcher) { 1740 for (UsingDecl::shadow_iterator II = Node.shadow_begin(); 1741 II != Node.shadow_end(); ++II) { 1742 if (Matcher.matches(**II, Finder, Builder)) 1743 return true; 1744 } 1745 return false; 1746} 1747 1748/// \brief Matches a using shadow declaration where the target declaration is 1749/// matched by the given matcher. 1750/// 1751/// Given 1752/// namespace X { int a; void b(); } 1753/// using X::a; 1754/// using X::b; 1755/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(function()))) 1756/// matches \code using X::b \endcode 1757/// but not \code using X::a \endcode 1758AST_MATCHER_P(UsingShadowDecl, hasTargetDecl, 1759 internal::Matcher<NamedDecl>, Matcher) { 1760 return Matcher.matches(*Node.getTargetDecl(), Finder, Builder); 1761} 1762 1763/// \brief Matches template instantiations of function, class, or static 1764/// member variable template instantiations. 1765/// 1766/// Given 1767/// template <typename T> class X {}; class A {}; X<A> x; 1768/// or 1769/// template <typename T> class X {}; class A {}; template class X<A>; 1770/// record(hasName("::X"), isTemplateInstantiation()) 1771/// matches the template instantiation of X<A>. 1772/// 1773/// But given 1774/// template <typename T> class X {}; class A {}; 1775/// template <> class X<A> {}; X<A> x; 1776/// record(hasName("::X"), isTemplateInstantiation()) 1777/// does not match, as X<A> is an explicit template specialization. 1778inline internal::PolymorphicMatcherWithParam0< 1779 internal::IsTemplateInstantiationMatcher> 1780isTemplateInstantiation() { 1781 return internal::PolymorphicMatcherWithParam0< 1782 internal::IsTemplateInstantiationMatcher>(); 1783} 1784 1785} // end namespace ast_matchers 1786} // end namespace clang 1787 1788#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H 1789