ASTMatchers.h revision 76dafa7e6487c0b51fadebd16bdefe0e0e23d595
1//===--- ASTMatchers.h - Structural query framework -------------*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements matchers to be used together with the MatchFinder to 11// match AST nodes. 12// 13// Matchers are created by generator functions, which can be combined in 14// a functional in-language DSL to express queries over the C++ AST. 15// 16// For example, to match a class with a certain name, one would call: 17// recordDecl(hasName("MyClass")) 18// which returns a matcher that can be used to find all AST nodes that declare 19// a class named 'MyClass'. 20// 21// For more complicated match expressions we're often interested in accessing 22// multiple parts of the matched AST nodes once a match is found. In that case, 23// use the id(...) matcher around the match expressions that match the nodes 24// you want to access. 25// 26// For example, when we're interested in child classes of a certain class, we 27// would write: 28// recordDecl(hasName("MyClass"), hasChild(id("child", recordDecl()))) 29// When the match is found via the MatchFinder, a user provided callback will 30// be called with a BoundNodes instance that contains a mapping from the 31// strings that we provided for the id(...) calls to the nodes that were 32// matched. 33// In the given example, each time our matcher finds a match we get a callback 34// where "child" is bound to the CXXRecordDecl node of the matching child 35// class declaration. 36// 37// See ASTMatchersInternal.h for a more in-depth explanation of the 38// implementation details of the matcher framework. 39// 40// See ASTMatchFinder.h for how to use the generated matchers to run over 41// an AST. 42// 43//===----------------------------------------------------------------------===// 44 45#ifndef LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H 46#define LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H 47 48#include "clang/AST/DeclTemplate.h" 49#include "clang/ASTMatchers/ASTMatchersInternal.h" 50#include "clang/ASTMatchers/ASTMatchersMacros.h" 51#include "llvm/ADT/Twine.h" 52#include "llvm/Support/Regex.h" 53#include <iterator> 54 55namespace clang { 56namespace ast_matchers { 57 58/// \brief Maps string IDs to AST nodes matched by parts of a matcher. 59/// 60/// The bound nodes are generated by calling \c bind("id") on the node matchers 61/// of the nodes we want to access later. 62/// 63/// The instances of BoundNodes are created by \c MatchFinder when the user's 64/// callbacks are executed every time a match is found. 65class BoundNodes { 66public: 67 /// \brief Returns the AST node bound to \c ID. 68 /// 69 /// Returns NULL if there was no node bound to \c ID or if there is a node but 70 /// it cannot be converted to the specified type. 71 template <typename T> 72 const T *getNodeAs(StringRef ID) const { 73 return MyBoundNodes.getNodeAs<T>(ID); 74 } 75 76 /// \brief Deprecated. Please use \c getNodeAs instead. 77 /// @{ 78 template <typename T> 79 const T *getDeclAs(StringRef ID) const { 80 return getNodeAs<T>(ID); 81 } 82 template <typename T> 83 const T *getStmtAs(StringRef ID) const { 84 return getNodeAs<T>(ID); 85 } 86 /// @} 87 88private: 89 /// \brief Create BoundNodes from a pre-filled map of bindings. 90 BoundNodes(internal::BoundNodesMap &MyBoundNodes) 91 : MyBoundNodes(MyBoundNodes) {} 92 93 internal::BoundNodesMap MyBoundNodes; 94 95 friend class internal::BoundNodesTree; 96}; 97 98/// \brief If the provided matcher matches a node, binds the node to \c ID. 99/// 100/// FIXME: Do we want to support this now that we have bind()? 101template <typename T> 102internal::Matcher<T> id(const std::string &ID, 103 const internal::BindableMatcher<T> &InnerMatcher) { 104 return InnerMatcher.bind(ID); 105} 106 107/// \brief Types of matchers for the top-level classes in the AST class 108/// hierarchy. 109/// @{ 110typedef internal::Matcher<Decl> DeclarationMatcher; 111typedef internal::Matcher<QualType> TypeMatcher; 112typedef internal::Matcher<Stmt> StatementMatcher; 113/// @} 114 115/// \brief Matches any node. 116/// 117/// Useful when another matcher requires a child matcher, but there's no 118/// additional constraint. This will often be used with an explicit conversion 119/// to an \c internal::Matcher<> type such as \c TypeMatcher. 120/// 121/// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g., 122/// \code 123/// "int* p" and "void f()" in 124/// int* p; 125/// void f(); 126/// \endcode 127/// 128/// Usable as: Any Matcher 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 \c X, \c S, the anonymous union type, \c i, and \c U; 147/// \code 148/// typedef int X; 149/// struct S { 150/// union { 151/// int i; 152/// } U; 153/// }; 154/// \endcode 155const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl; 156 157/// \brief Matches C++ class declarations. 158/// 159/// Example matches \c X, \c Z 160/// \code 161/// class X; 162/// template<class T> class Z {}; 163/// \endcode 164const internal::VariadicDynCastAllOfMatcher< 165 Decl, 166 CXXRecordDecl> recordDecl; 167 168/// \brief Matches C++ class template declarations. 169/// 170/// Example matches \c Z 171/// \code 172/// template<class T> class Z {}; 173/// \endcode 174const internal::VariadicDynCastAllOfMatcher< 175 Decl, 176 ClassTemplateDecl> classTemplateDecl; 177 178/// \brief Matches C++ class template specializations. 179/// 180/// Given 181/// \code 182/// template<typename T> class A {}; 183/// template<> class A<double> {}; 184/// A<int> a; 185/// \endcode 186/// classTemplateSpecializationDecl() 187/// matches the specializations \c A<int> and \c A<double> 188const internal::VariadicDynCastAllOfMatcher< 189 Decl, 190 ClassTemplateSpecializationDecl> classTemplateSpecializationDecl; 191 192/// \brief Matches classTemplateSpecializations that have at least one 193/// TemplateArgument matching the given InnerMatcher. 194/// 195/// Given 196/// \code 197/// template<typename T> class A {}; 198/// template<> class A<double> {}; 199/// A<int> a; 200/// \endcode 201/// classTemplateSpecializationDecl(hasAnyTemplateArgument( 202/// refersToType(asString("int")))) 203/// matches the specialization \c A<int> 204AST_MATCHER_P(ClassTemplateSpecializationDecl, hasAnyTemplateArgument, 205 internal::Matcher<TemplateArgument>, InnerMatcher) { 206 const TemplateArgumentList &List = Node.getTemplateArgs(); 207 for (unsigned i = 0; i < List.size(); ++i) { 208 if (InnerMatcher.matches(List.get(i), Finder, Builder)) 209 return true; 210 } 211 return false; 212} 213 214/// \brief Matches expressions that match InnerMatcher after any implicit casts 215/// are stripped off. 216/// 217/// Parentheses and explicit casts are not discarded. 218/// Given 219/// \code 220/// int arr[5]; 221/// int a = 0; 222/// char b = 0; 223/// const int c = a; 224/// int *d = arr; 225/// long e = (long) 0l; 226/// \endcode 227/// The matchers 228/// \code 229/// varDecl(hasInitializer(ignoringImpCasts(integerLiteral()))) 230/// varDecl(hasInitializer(ignoringImpCasts(declRefExpr()))) 231/// \endcode 232/// would match the declarations for a, b, c, and d, but not e. 233/// While 234/// \code 235/// varDecl(hasInitializer(integerLiteral())) 236/// varDecl(hasInitializer(declRefExpr())) 237/// \endcode 238/// only match the declarations for b, c, and d. 239AST_MATCHER_P(Expr, ignoringImpCasts, 240 internal::Matcher<Expr>, InnerMatcher) { 241 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder); 242} 243 244/// \brief Matches expressions that match InnerMatcher after parentheses and 245/// casts are stripped off. 246/// 247/// Implicit and non-C Style casts are also discarded. 248/// Given 249/// \code 250/// int a = 0; 251/// char b = (0); 252/// void* c = reinterpret_cast<char*>(0); 253/// char d = char(0); 254/// \endcode 255/// The matcher 256/// varDecl(hasInitializer(ignoringParenCasts(integerLiteral()))) 257/// would match the declarations for a, b, c, and d. 258/// while 259/// varDecl(hasInitializer(integerLiteral())) 260/// only match the declaration for a. 261AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) { 262 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder); 263} 264 265/// \brief Matches expressions that match InnerMatcher after implicit casts and 266/// parentheses are stripped off. 267/// 268/// Explicit casts are not discarded. 269/// Given 270/// \code 271/// int arr[5]; 272/// int a = 0; 273/// char b = (0); 274/// const int c = a; 275/// int *d = (arr); 276/// long e = ((long) 0l); 277/// \endcode 278/// The matchers 279/// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral()))) 280/// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr()))) 281/// would match the declarations for a, b, c, and d, but not e. 282/// while 283/// varDecl(hasInitializer(integerLiteral())) 284/// varDecl(hasInitializer(declRefExpr())) 285/// would only match the declaration for a. 286AST_MATCHER_P(Expr, ignoringParenImpCasts, 287 internal::Matcher<Expr>, InnerMatcher) { 288 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder); 289} 290 291/// \brief Matches classTemplateSpecializations where the n'th TemplateArgument 292/// matches the given InnerMatcher. 293/// 294/// Given 295/// \code 296/// template<typename T, typename U> class A {}; 297/// A<bool, int> b; 298/// A<int, bool> c; 299/// \endcode 300/// classTemplateSpecializationDecl(hasTemplateArgument( 301/// 1, refersToType(asString("int")))) 302/// matches the specialization \c A<bool, int> 303AST_MATCHER_P2(ClassTemplateSpecializationDecl, hasTemplateArgument, 304 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) { 305 const TemplateArgumentList &List = Node.getTemplateArgs(); 306 if (List.size() <= N) 307 return false; 308 return InnerMatcher.matches(List.get(N), Finder, Builder); 309} 310 311/// \brief Matches a TemplateArgument that refers to a certain type. 312/// 313/// Given 314/// \code 315/// struct X {}; 316/// template<typename T> struct A {}; 317/// A<X> a; 318/// \endcode 319/// classTemplateSpecializationDecl(hasAnyTemplateArgument( 320/// refersToType(class(hasName("X"))))) 321/// matches the specialization \c A<X> 322AST_MATCHER_P(TemplateArgument, refersToType, 323 internal::Matcher<QualType>, InnerMatcher) { 324 if (Node.getKind() != TemplateArgument::Type) 325 return false; 326 return InnerMatcher.matches(Node.getAsType(), Finder, Builder); 327} 328 329/// \brief Matches a TemplateArgument that refers to a certain declaration. 330/// 331/// Given 332/// \code 333/// template<typename T> struct A {}; 334/// struct B { B* next; }; 335/// A<&B::next> a; 336/// \endcode 337/// classTemplateSpecializationDecl(hasAnyTemplateArgument( 338/// refersToDeclaration(fieldDecl(hasName("next")))) 339/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching 340/// \c B::next 341AST_MATCHER_P(TemplateArgument, refersToDeclaration, 342 internal::Matcher<Decl>, InnerMatcher) { 343 if (const Decl *Declaration = Node.getAsDecl()) 344 return InnerMatcher.matches(*Declaration, Finder, Builder); 345 return false; 346} 347 348/// \brief Matches C++ constructor declarations. 349/// 350/// Example matches Foo::Foo() and Foo::Foo(int) 351/// \code 352/// class Foo { 353/// public: 354/// Foo(); 355/// Foo(int); 356/// int DoSomething(); 357/// }; 358/// \endcode 359const internal::VariadicDynCastAllOfMatcher< 360 Decl, 361 CXXConstructorDecl> constructorDecl; 362 363/// \brief Matches explicit C++ destructor declarations. 364/// 365/// Example matches Foo::~Foo() 366/// \code 367/// class Foo { 368/// public: 369/// virtual ~Foo(); 370/// }; 371/// \endcode 372const internal::VariadicDynCastAllOfMatcher< 373 Decl, 374 CXXDestructorDecl> destructorDecl; 375 376/// \brief Matches enum declarations. 377/// 378/// Example matches X 379/// \code 380/// enum X { 381/// A, B, C 382/// }; 383/// \endcode 384const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl; 385 386/// \brief Matches enum constants. 387/// 388/// Example matches A, B, C 389/// \code 390/// enum X { 391/// A, B, C 392/// }; 393/// \endcode 394const internal::VariadicDynCastAllOfMatcher< 395 Decl, 396 EnumConstantDecl> enumConstantDecl; 397 398/// \brief Matches method declarations. 399/// 400/// Example matches y 401/// \code 402/// class X { void y() }; 403/// \endcode 404const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> methodDecl; 405 406/// \brief Matches variable declarations. 407/// 408/// Note: this does not match declarations of member variables, which are 409/// "field" declarations in Clang parlance. 410/// 411/// Example matches a 412/// \code 413/// int a; 414/// \endcode 415const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl; 416 417/// \brief Matches field declarations. 418/// 419/// Given 420/// \code 421/// class X { int m; }; 422/// \endcode 423/// fieldDecl() 424/// matches 'm'. 425const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl; 426 427/// \brief Matches function declarations. 428/// 429/// Example matches f 430/// \code 431/// void f(); 432/// \endcode 433const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl; 434 435/// \brief Matches C++ function template declarations. 436/// 437/// Example matches f 438/// \code 439/// template<class T> void f(T t) {} 440/// \endcode 441const internal::VariadicDynCastAllOfMatcher< 442 Decl, 443 FunctionTemplateDecl> functionTemplateDecl; 444 445/// \brief Matches statements. 446/// 447/// Given 448/// \code 449/// { ++a; } 450/// \endcode 451/// stmt() 452/// matches both the compound statement '{ ++a; }' and '++a'. 453const internal::VariadicDynCastAllOfMatcher<Stmt, Stmt> stmt; 454 455/// \brief Matches declaration statements. 456/// 457/// Given 458/// \code 459/// int a; 460/// \endcode 461/// declStmt() 462/// matches 'int a'. 463const internal::VariadicDynCastAllOfMatcher< 464 Stmt, 465 DeclStmt> declStmt; 466 467/// \brief Matches member expressions. 468/// 469/// Given 470/// \code 471/// class Y { 472/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 473/// int a; static int b; 474/// }; 475/// \endcode 476/// memberExpr() 477/// matches this->x, x, y.x, a, this->b 478const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr; 479 480/// \brief Matches call expressions. 481/// 482/// Example matches x.y() and y() 483/// \code 484/// X x; 485/// x.y(); 486/// y(); 487/// \endcode 488const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr; 489 490/// \brief Matches member call expressions. 491/// 492/// Example matches x.y() 493/// \code 494/// X x; 495/// x.y(); 496/// \endcode 497const internal::VariadicDynCastAllOfMatcher< 498 Stmt, 499 CXXMemberCallExpr> memberCallExpr; 500 501/// \brief Matches init list expressions. 502/// 503/// Given 504/// \code 505/// int a[] = { 1, 2 }; 506/// struct B { int x, y; }; 507/// B b = { 5, 6 }; 508/// \endcode 509/// initList() 510/// matches "{ 1, 2 }" and "{ 5, 6 }" 511const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr; 512 513/// \brief Matches using declarations. 514/// 515/// Given 516/// \code 517/// namespace X { int x; } 518/// using X::x; 519/// \endcode 520/// usingDecl() 521/// matches \code using X::x \endcode 522const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl; 523 524/// \brief Matches constructor call expressions (including implicit ones). 525/// 526/// Example matches string(ptr, n) and ptr within arguments of f 527/// (matcher = constructExpr()) 528/// \code 529/// void f(const string &a, const string &b); 530/// char *ptr; 531/// int n; 532/// f(string(ptr, n), ptr); 533/// \endcode 534const internal::VariadicDynCastAllOfMatcher< 535 Stmt, 536 CXXConstructExpr> constructExpr; 537 538/// \brief Matches nodes where temporaries are created. 539/// 540/// Example matches FunctionTakesString(GetStringByValue()) 541/// (matcher = bindTemporaryExpr()) 542/// \code 543/// FunctionTakesString(GetStringByValue()); 544/// FunctionTakesStringByPointer(GetStringPointer()); 545/// \endcode 546const internal::VariadicDynCastAllOfMatcher< 547 Stmt, 548 CXXBindTemporaryExpr> bindTemporaryExpr; 549 550/// \brief Matches nodes where temporaries are materialized. 551/// 552/// Example: Given 553/// \code 554/// struct T {void func()}; 555/// T f(); 556/// void g(T); 557/// \endcode 558/// materializeTemporaryExpr() matches 'f()' in these statements 559/// \code 560/// T u(f()); 561/// g(f()); 562/// \endcode 563/// but does not match 564/// \code 565/// f(); 566/// f().func(); 567/// \endcode 568const internal::VariadicDynCastAllOfMatcher< 569 Stmt, 570 MaterializeTemporaryExpr> materializeTemporaryExpr; 571 572/// \brief Matches new expressions. 573/// 574/// Given 575/// \code 576/// new X; 577/// \endcode 578/// newExpr() 579/// matches 'new X'. 580const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> newExpr; 581 582/// \brief Matches delete expressions. 583/// 584/// Given 585/// \code 586/// delete X; 587/// \endcode 588/// deleteExpr() 589/// matches 'delete X'. 590const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> deleteExpr; 591 592/// \brief Matches array subscript expressions. 593/// 594/// Given 595/// \code 596/// int i = a[1]; 597/// \endcode 598/// arraySubscriptExpr() 599/// matches "a[1]" 600const internal::VariadicDynCastAllOfMatcher< 601 Stmt, 602 ArraySubscriptExpr> arraySubscriptExpr; 603 604/// \brief Matches the value of a default argument at the call site. 605/// 606/// Example matches the CXXDefaultArgExpr placeholder inserted for the 607/// default value of the second parameter in the call expression f(42) 608/// (matcher = defaultArgExpr()) 609/// \code 610/// void f(int x, int y = 0); 611/// f(42); 612/// \endcode 613const internal::VariadicDynCastAllOfMatcher< 614 Stmt, 615 CXXDefaultArgExpr> defaultArgExpr; 616 617/// \brief Matches overloaded operator calls. 618/// 619/// Note that if an operator isn't overloaded, it won't match. Instead, use 620/// binaryOperator matcher. 621/// Currently it does not match operators such as new delete. 622/// FIXME: figure out why these do not match? 623/// 624/// Example matches both operator<<((o << b), c) and operator<<(o, b) 625/// (matcher = operatorCallExpr()) 626/// \code 627/// ostream &operator<< (ostream &out, int i) { }; 628/// ostream &o; int b = 1, c = 1; 629/// o << b << c; 630/// \endcode 631const internal::VariadicDynCastAllOfMatcher< 632 Stmt, 633 CXXOperatorCallExpr> operatorCallExpr; 634 635/// \brief Matches expressions. 636/// 637/// Example matches x() 638/// \code 639/// void f() { x(); } 640/// \endcode 641const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr; 642 643/// \brief Matches expressions that refer to declarations. 644/// 645/// Example matches x in if (x) 646/// \code 647/// bool x; 648/// if (x) {} 649/// \endcode 650const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr; 651 652/// \brief Matches if statements. 653/// 654/// Example matches 'if (x) {}' 655/// \code 656/// if (x) {} 657/// \endcode 658const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt; 659 660/// \brief Matches for statements. 661/// 662/// Example matches 'for (;;) {}' 663/// \code 664/// for (;;) {} 665/// \endcode 666const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt; 667 668/// \brief Matches the increment statement of a for loop. 669/// 670/// Example: 671/// forStmt(hasIncrement(unaryOperator(hasOperatorName("++")))) 672/// matches '++x' in 673/// \code 674/// for (x; x < N; ++x) { } 675/// \endcode 676AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>, 677 InnerMatcher) { 678 const Stmt *const Increment = Node.getInc(); 679 return (Increment != NULL && 680 InnerMatcher.matches(*Increment, Finder, Builder)); 681} 682 683/// \brief Matches the initialization statement of a for loop. 684/// 685/// Example: 686/// forStmt(hasLoopInit(declStmt())) 687/// matches 'int x = 0' in 688/// \code 689/// for (int x = 0; x < N; ++x) { } 690/// \endcode 691AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>, 692 InnerMatcher) { 693 const Stmt *const Init = Node.getInit(); 694 return (Init != NULL && InnerMatcher.matches(*Init, Finder, Builder)); 695} 696 697/// \brief Matches while statements. 698/// 699/// Given 700/// \code 701/// while (true) {} 702/// \endcode 703/// whileStmt() 704/// matches 'while (true) {}'. 705const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt; 706 707/// \brief Matches do statements. 708/// 709/// Given 710/// \code 711/// do {} while (true); 712/// \endcode 713/// doStmt() 714/// matches 'do {} while(true)' 715const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt; 716 717/// \brief Matches case and default statements inside switch statements. 718/// 719/// Given 720/// \code 721/// switch(a) { case 42: break; default: break; } 722/// \endcode 723/// switchCase() 724/// matches 'case 42: break;' and 'default: break;'. 725const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase; 726 727/// \brief Matches compound statements. 728/// 729/// Example matches '{}' and '{{}}'in 'for (;;) {{}}' 730/// \code 731/// for (;;) {{}} 732/// \endcode 733const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt; 734 735/// \brief Matches bool literals. 736/// 737/// Example matches true 738/// \code 739/// true 740/// \endcode 741const internal::VariadicDynCastAllOfMatcher< 742 Expr, 743 CXXBoolLiteralExpr> boolLiteral; 744 745/// \brief Matches string literals (also matches wide string literals). 746/// 747/// Example matches "abcd", L"abcd" 748/// \code 749/// char *s = "abcd"; wchar_t *ws = L"abcd" 750/// \endcode 751const internal::VariadicDynCastAllOfMatcher< 752 Expr, 753 StringLiteral> stringLiteral; 754 755/// \brief Matches character literals (also matches wchar_t). 756/// 757/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral), 758/// though. 759/// 760/// Example matches 'a', L'a' 761/// \code 762/// char ch = 'a'; wchar_t chw = L'a'; 763/// \endcode 764const internal::VariadicDynCastAllOfMatcher< 765 Expr, 766 CharacterLiteral> characterLiteral; 767 768/// \brief Matches integer literals of all sizes / encodings. 769/// 770/// Not matching character-encoded integers such as L'a'. 771/// 772/// Example matches 1, 1L, 0x1, 1U 773const internal::VariadicDynCastAllOfMatcher< 774 Expr, 775 IntegerLiteral> integerLiteral; 776 777/// \brief Matches binary operator expressions. 778/// 779/// Example matches a || b 780/// \code 781/// !(a || b) 782/// \endcode 783const internal::VariadicDynCastAllOfMatcher< 784 Stmt, 785 BinaryOperator> binaryOperator; 786 787/// \brief Matches unary operator expressions. 788/// 789/// Example matches !a 790/// \code 791/// !a || b 792/// \endcode 793const internal::VariadicDynCastAllOfMatcher< 794 Stmt, 795 UnaryOperator> unaryOperator; 796 797/// \brief Matches conditional operator expressions. 798/// 799/// Example matches a ? b : c 800/// \code 801/// (a ? b : c) + 42 802/// \endcode 803const internal::VariadicDynCastAllOfMatcher< 804 Stmt, 805 ConditionalOperator> conditionalOperator; 806 807/// \brief Matches a reinterpret_cast expression. 808/// 809/// Either the source expression or the destination type can be matched 810/// using has(), but hasDestinationType() is more specific and can be 811/// more readable. 812/// 813/// Example matches reinterpret_cast<char*>(&p) in 814/// \code 815/// void* p = reinterpret_cast<char*>(&p); 816/// \endcode 817const internal::VariadicDynCastAllOfMatcher< 818 Expr, 819 CXXReinterpretCastExpr> reinterpretCastExpr; 820 821/// \brief Matches a C++ static_cast expression. 822/// 823/// \see hasDestinationType 824/// \see reinterpretCast 825/// 826/// Example: 827/// staticCastExpr() 828/// matches 829/// static_cast<long>(8) 830/// in 831/// \code 832/// long eight(static_cast<long>(8)); 833/// \endcode 834const internal::VariadicDynCastAllOfMatcher< 835 Expr, 836 CXXStaticCastExpr> staticCastExpr; 837 838/// \brief Matches a dynamic_cast expression. 839/// 840/// Example: 841/// dynamicCastExpr() 842/// matches 843/// dynamic_cast<D*>(&b); 844/// in 845/// \code 846/// struct B { virtual ~B() {} }; struct D : B {}; 847/// B b; 848/// D* p = dynamic_cast<D*>(&b); 849/// \endcode 850const internal::VariadicDynCastAllOfMatcher< 851 Expr, 852 CXXDynamicCastExpr> dynamicCastExpr; 853 854/// \brief Matches a const_cast expression. 855/// 856/// Example: Matches const_cast<int*>(&r) in 857/// \code 858/// int n = 42; 859/// const int &r(n); 860/// int* p = const_cast<int*>(&r); 861/// \endcode 862const internal::VariadicDynCastAllOfMatcher< 863 Expr, 864 CXXConstCastExpr> constCastExpr; 865 866/// \brief Matches explicit cast expressions. 867/// 868/// Matches any cast expression written in user code, whether it be a 869/// C-style cast, a functional-style cast, or a keyword cast. 870/// 871/// Does not match implicit conversions. 872/// 873/// Note: the name "explicitCast" is chosen to match Clang's terminology, as 874/// Clang uses the term "cast" to apply to implicit conversions as well as to 875/// actual cast expressions. 876/// 877/// \see hasDestinationType. 878/// 879/// Example: matches all five of the casts in 880/// \code 881/// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42))))) 882/// \endcode 883/// but does not match the implicit conversion in 884/// \code 885/// long ell = 42; 886/// \endcode 887const internal::VariadicDynCastAllOfMatcher< 888 Expr, 889 ExplicitCastExpr> explicitCastExpr; 890 891/// \brief Matches the implicit cast nodes of Clang's AST. 892/// 893/// This matches many different places, including function call return value 894/// eliding, as well as any type conversions. 895const internal::VariadicDynCastAllOfMatcher< 896 Expr, 897 ImplicitCastExpr> implicitCastExpr; 898 899/// \brief Matches any cast nodes of Clang's AST. 900/// 901/// Example: castExpr() matches each of the following: 902/// \code 903/// (int) 3; 904/// const_cast<Expr *>(SubExpr); 905/// char c = 0; 906/// \endcode 907/// but does not match 908/// \code 909/// int i = (0); 910/// int k = 0; 911/// \endcode 912const internal::VariadicDynCastAllOfMatcher<Expr, CastExpr> castExpr; 913 914/// \brief Matches functional cast expressions 915/// 916/// Example: Matches Foo(bar); 917/// \code 918/// Foo f = bar; 919/// Foo g = (Foo) bar; 920/// Foo h = Foo(bar); 921/// \endcode 922const internal::VariadicDynCastAllOfMatcher< 923 Expr, 924 CXXFunctionalCastExpr> functionalCastExpr; 925 926/// \brief Various overloads for the anyOf matcher. 927/// @{ 928 929/// \brief Matches if any of the given matchers matches. 930/// 931/// Usable as: Any Matcher 932template<typename M1, typename M2> 933internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1, M2> 934anyOf(const M1 &P1, const M2 &P2) { 935 return internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 936 M1, M2 >(P1, P2); 937} 938template<typename M1, typename M2, typename M3> 939internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1, 940 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2, M3> > 941anyOf(const M1 &P1, const M2 &P2, const M3 &P3) { 942 return anyOf(P1, anyOf(P2, P3)); 943} 944template<typename M1, typename M2, typename M3, typename M4> 945internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1, 946 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2, 947 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 948 M3, M4> > > 949anyOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4) { 950 return anyOf(P1, anyOf(P2, anyOf(P3, P4))); 951} 952template<typename M1, typename M2, typename M3, typename M4, typename M5> 953internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1, 954 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2, 955 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M3, 956 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 957 M4, M5> > > > 958anyOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4, const M5 &P5) { 959 return anyOf(P1, anyOf(P2, anyOf(P3, anyOf(P4, P5)))); 960} 961 962/// @} 963 964/// \brief Various overloads for the allOf matcher. 965/// @{ 966 967/// \brief Matches if all given matchers match. 968/// 969/// Usable as: Any Matcher 970template<typename M1, typename M2> 971internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M1, M2> 972allOf(const M1 &P1, const M2 &P2) { 973 return internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, 974 M1, M2>(P1, P2); 975} 976template<typename M1, typename M2, typename M3> 977internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M1, 978 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M2, M3> > 979allOf(const M1 &P1, const M2 &P2, const M3 &P3) { 980 return allOf(P1, allOf(P2, P3)); 981} 982 983/// @} 984 985/// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL) 986/// 987/// Given 988/// \code 989/// Foo x = bar; 990/// int y = sizeof(x) + alignof(x); 991/// \endcode 992/// unaryExprOrTypeTraitExpr() 993/// matches \c sizeof(x) and \c alignof(x) 994const internal::VariadicDynCastAllOfMatcher< 995 Stmt, 996 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr; 997 998/// \brief Matches unary expressions that have a specific type of argument. 999/// 1000/// Given 1001/// \code 1002/// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c); 1003/// \endcode 1004/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int")) 1005/// matches \c sizeof(a) and \c alignof(c) 1006AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType, 1007 internal::Matcher<QualType>, InnerMatcher) { 1008 const QualType ArgumentType = Node.getTypeOfArgument(); 1009 return InnerMatcher.matches(ArgumentType, Finder, Builder); 1010} 1011 1012/// \brief Matches unary expressions of a certain kind. 1013/// 1014/// Given 1015/// \code 1016/// int x; 1017/// int s = sizeof(x) + alignof(x) 1018/// \endcode 1019/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf)) 1020/// matches \c sizeof(x) 1021AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) { 1022 return Node.getKind() == Kind; 1023} 1024 1025/// \brief Same as unaryExprOrTypeTraitExpr, but only matching 1026/// alignof. 1027inline internal::Matcher<Stmt> alignOfExpr( 1028 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) { 1029 return internal::Matcher<Stmt>(unaryExprOrTypeTraitExpr(allOf( 1030 ofKind(UETT_AlignOf), InnerMatcher))); 1031} 1032 1033/// \brief Same as unaryExprOrTypeTraitExpr, but only matching 1034/// sizeof. 1035inline internal::Matcher<Stmt> sizeOfExpr( 1036 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) { 1037 return internal::Matcher<Stmt>(unaryExprOrTypeTraitExpr(allOf( 1038 ofKind(UETT_SizeOf), InnerMatcher))); 1039} 1040 1041/// \brief Matches NamedDecl nodes that have the specified name. 1042/// 1043/// Supports specifying enclosing namespaces or classes by prefixing the name 1044/// with '<enclosing>::'. 1045/// Does not match typedefs of an underlying type with the given name. 1046/// 1047/// Example matches X (Name == "X") 1048/// \code 1049/// class X; 1050/// \endcode 1051/// 1052/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X") 1053/// \code 1054/// namespace a { namespace b { class X; } } 1055/// \endcode 1056AST_MATCHER_P(NamedDecl, hasName, std::string, Name) { 1057 assert(!Name.empty()); 1058 const std::string FullNameString = "::" + Node.getQualifiedNameAsString(); 1059 const llvm::StringRef FullName = FullNameString; 1060 const llvm::StringRef Pattern = Name; 1061 if (Pattern.startswith("::")) { 1062 return FullName == Pattern; 1063 } else { 1064 return FullName.endswith(("::" + Pattern).str()); 1065 } 1066} 1067 1068/// \brief Matches NamedDecl nodes whose full names partially match the 1069/// given RegExp. 1070/// 1071/// Supports specifying enclosing namespaces or classes by 1072/// prefixing the name with '<enclosing>::'. Does not match typedefs 1073/// of an underlying type with the given name. 1074/// 1075/// Example matches X (regexp == "::X") 1076/// \code 1077/// class X; 1078/// \endcode 1079/// 1080/// Example matches X (regexp is one of "::X", "^foo::.*X", among others) 1081/// \code 1082/// namespace foo { namespace bar { class X; } } 1083/// \endcode 1084AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) { 1085 assert(!RegExp.empty()); 1086 std::string FullNameString = "::" + Node.getQualifiedNameAsString(); 1087 llvm::Regex RE(RegExp); 1088 return RE.match(FullNameString); 1089} 1090 1091/// \brief Matches overloaded operator names. 1092/// 1093/// Matches overloaded operator names specified in strings without the 1094/// "operator" prefix, such as "<<", for OverloadedOperatorCall's. 1095/// 1096/// Example matches a << b 1097/// (matcher == operatorCallExpr(hasOverloadedOperatorName("<<"))) 1098/// \code 1099/// a << b; 1100/// c && d; // assuming both operator<< 1101/// // and operator&& are overloaded somewhere. 1102/// \endcode 1103AST_MATCHER_P(CXXOperatorCallExpr, 1104 hasOverloadedOperatorName, std::string, Name) { 1105 return getOperatorSpelling(Node.getOperator()) == Name; 1106} 1107 1108/// \brief Matches C++ classes that are directly or indirectly derived from 1109/// a class matching \c Base. 1110/// 1111/// Note that a class is not considered to be derived from itself. 1112/// 1113/// Example matches Y, Z, C (Base == hasName("X")) 1114/// \code 1115/// class X; 1116/// class Y : public X {}; // directly derived 1117/// class Z : public Y {}; // indirectly derived 1118/// typedef X A; 1119/// typedef A B; 1120/// class C : public B {}; // derived from a typedef of X 1121/// \endcode 1122/// 1123/// In the following example, Bar matches isDerivedFrom(hasName("X")): 1124/// \code 1125/// class Foo; 1126/// typedef Foo X; 1127/// class Bar : public Foo {}; // derived from a type that X is a typedef of 1128/// \endcode 1129AST_MATCHER_P(CXXRecordDecl, isDerivedFrom, 1130 internal::Matcher<NamedDecl>, Base) { 1131 return Finder->classIsDerivedFrom(&Node, Base, Builder); 1132} 1133 1134/// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)). 1135inline internal::Matcher<CXXRecordDecl> isDerivedFrom(StringRef BaseName) { 1136 assert(!BaseName.empty()); 1137 return isDerivedFrom(hasName(BaseName)); 1138} 1139 1140/// \brief Similar to \c isDerivedFrom(), but also matches classes that directly 1141/// match \c Base. 1142inline internal::Matcher<CXXRecordDecl> isA(internal::Matcher<NamedDecl> Base) { 1143 return anyOf(Base, isDerivedFrom(Base)); 1144} 1145 1146/// \brief Overloaded method as shortcut for \c isA(hasName(...)). 1147inline internal::Matcher<CXXRecordDecl> isA(StringRef BaseName) { 1148 assert(!BaseName.empty()); 1149 return isA(hasName(BaseName)); 1150} 1151 1152/// \brief Matches AST nodes that have child AST nodes that match the 1153/// provided matcher. 1154/// 1155/// Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X"))) 1156/// \code 1157/// class X {}; // Matches X, because X::X is a class of name X inside X. 1158/// class Y { class X {}; }; 1159/// class Z { class Y { class X {}; }; }; // Does not match Z. 1160/// \endcode 1161/// 1162/// ChildT must be an AST base type. 1163/// 1164/// Usable as: Any Matcher 1165template <typename ChildT> 1166internal::ArgumentAdaptingMatcher<internal::HasMatcher, ChildT> has( 1167 const internal::Matcher<ChildT> &ChildMatcher) { 1168 return internal::ArgumentAdaptingMatcher<internal::HasMatcher, 1169 ChildT>(ChildMatcher); 1170} 1171 1172/// \brief Matches AST nodes that have descendant AST nodes that match the 1173/// provided matcher. 1174/// 1175/// Example matches X, Y, Z 1176/// (matcher = recordDecl(hasDescendant(recordDecl(hasName("X"))))) 1177/// \code 1178/// class X {}; // Matches X, because X::X is a class of name X inside X. 1179/// class Y { class X {}; }; 1180/// class Z { class Y { class X {}; }; }; 1181/// \endcode 1182/// 1183/// DescendantT must be an AST base type. 1184/// 1185/// Usable as: Any Matcher 1186template <typename DescendantT> 1187internal::ArgumentAdaptingMatcher<internal::HasDescendantMatcher, DescendantT> 1188hasDescendant(const internal::Matcher<DescendantT> &DescendantMatcher) { 1189 return internal::ArgumentAdaptingMatcher< 1190 internal::HasDescendantMatcher, 1191 DescendantT>(DescendantMatcher); 1192} 1193 1194/// \brief Matches AST nodes that have child AST nodes that match the 1195/// provided matcher. 1196/// 1197/// Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X"))) 1198/// \code 1199/// class X {}; // Matches X, because X::X is a class of name X inside X. 1200/// class Y { class X {}; }; 1201/// class Z { class Y { class X {}; }; }; // Does not match Z. 1202/// \endcode 1203/// 1204/// ChildT must be an AST base type. 1205/// 1206/// As opposed to 'has', 'forEach' will cause a match for each result that 1207/// matches instead of only on the first one. 1208/// 1209/// Usable as: Any Matcher 1210template <typename ChildT> 1211internal::ArgumentAdaptingMatcher<internal::ForEachMatcher, ChildT> forEach( 1212 const internal::Matcher<ChildT> &ChildMatcher) { 1213 return internal::ArgumentAdaptingMatcher< 1214 internal::ForEachMatcher, 1215 ChildT>(ChildMatcher); 1216} 1217 1218/// \brief Matches AST nodes that have descendant AST nodes that match the 1219/// provided matcher. 1220/// 1221/// Example matches X, A, B, C 1222/// (matcher = recordDecl(forEachDescendant(recordDecl(hasName("X"))))) 1223/// \code 1224/// class X {}; // Matches X, because X::X is a class of name X inside X. 1225/// class A { class X {}; }; 1226/// class B { class C { class X {}; }; }; 1227/// \endcode 1228/// 1229/// DescendantT must be an AST base type. 1230/// 1231/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for 1232/// each result that matches instead of only on the first one. 1233/// 1234/// Note: Recursively combined ForEachDescendant can cause many matches: 1235/// recordDecl(forEachDescendant(recordDecl(forEachDescendant(recordDecl())))) 1236/// will match 10 times (plus injected class name matches) on: 1237/// \code 1238/// class A { class B { class C { class D { class E {}; }; }; }; }; 1239/// \endcode 1240/// 1241/// Usable as: Any Matcher 1242template <typename DescendantT> 1243internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, DescendantT> 1244forEachDescendant( 1245 const internal::Matcher<DescendantT> &DescendantMatcher) { 1246 return internal::ArgumentAdaptingMatcher< 1247 internal::ForEachDescendantMatcher, 1248 DescendantT>(DescendantMatcher); 1249} 1250 1251/// \brief Matches AST nodes that have an ancestor that matches the provided 1252/// matcher. 1253/// 1254/// Given 1255/// \code 1256/// void f() { if (true) { int x = 42; } } 1257/// void g() { for (;;) { int x = 43; } } 1258/// \endcode 1259/// \c expr(integerLiteral(hasAncsestor(ifStmt()))) matches \c 42, but not 43. 1260/// 1261/// Usable as: Any Matcher 1262template <typename AncestorT> 1263internal::ArgumentAdaptingMatcher<internal::HasAncestorMatcher, AncestorT> 1264hasAncestor(const internal::Matcher<AncestorT> &AncestorMatcher) { 1265 return internal::ArgumentAdaptingMatcher< 1266 internal::HasAncestorMatcher, 1267 AncestorT>(AncestorMatcher); 1268} 1269 1270/// \brief Matches if the provided matcher does not match. 1271/// 1272/// Example matches Y (matcher = recordDecl(unless(hasName("X")))) 1273/// \code 1274/// class X {}; 1275/// class Y {}; 1276/// \endcode 1277/// 1278/// Usable as: Any Matcher 1279template <typename M> 1280internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M> 1281unless(const M &InnerMatcher) { 1282 return internal::PolymorphicMatcherWithParam1< 1283 internal::NotMatcher, M>(InnerMatcher); 1284} 1285 1286/// \brief Matches a type if the declaration of the type matches the given 1287/// matcher. 1288/// 1289/// Usable as: Matcher<QualType>, Matcher<CallExpr>, Matcher<CXXConstructExpr> 1290inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher, 1291 internal::Matcher<Decl> > 1292 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) { 1293 return internal::PolymorphicMatcherWithParam1< 1294 internal::HasDeclarationMatcher, 1295 internal::Matcher<Decl> >(InnerMatcher); 1296} 1297 1298/// \brief Matches on the implicit object argument of a member call expression. 1299/// 1300/// Example matches y.x() (matcher = callExpr(on(hasType(recordDecl(hasName("Y")))))) 1301/// \code 1302/// class Y { public: void x(); }; 1303/// void z() { Y y; y.x(); }", 1304/// \endcode 1305/// 1306/// FIXME: Overload to allow directly matching types? 1307AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>, 1308 InnerMatcher) { 1309 const Expr *ExprNode = const_cast<CXXMemberCallExpr&>(Node) 1310 .getImplicitObjectArgument() 1311 ->IgnoreParenImpCasts(); 1312 return (ExprNode != NULL && 1313 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1314} 1315 1316/// \brief Matches if the call expression's callee expression matches. 1317/// 1318/// Given 1319/// \code 1320/// class Y { void x() { this->x(); x(); Y y; y.x(); } }; 1321/// void f() { f(); } 1322/// \endcode 1323/// callExpr(callee(expr())) 1324/// matches this->x(), x(), y.x(), f() 1325/// with callee(...) 1326/// matching this->x, x, y.x, f respectively 1327/// 1328/// Note: Callee cannot take the more general internal::Matcher<Expr> 1329/// because this introduces ambiguous overloads with calls to Callee taking a 1330/// internal::Matcher<Decl>, as the matcher hierarchy is purely 1331/// implemented in terms of implicit casts. 1332AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>, 1333 InnerMatcher) { 1334 const Expr *ExprNode = Node.getCallee(); 1335 return (ExprNode != NULL && 1336 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1337} 1338 1339/// \brief Matches if the call expression's callee's declaration matches the 1340/// given matcher. 1341/// 1342/// Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x"))))) 1343/// \code 1344/// class Y { public: void x(); }; 1345/// void z() { Y y; y.x(); 1346/// \endcode 1347inline internal::Matcher<CallExpr> callee( 1348 const internal::Matcher<Decl> &InnerMatcher) { 1349 return internal::Matcher<CallExpr>(hasDeclaration(InnerMatcher)); 1350} 1351 1352/// \brief Matches if the expression's or declaration's type matches a type 1353/// matcher. 1354/// 1355/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) 1356/// and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) 1357/// \code 1358/// class X {}; 1359/// void y(X &x) { x; X z; } 1360/// \endcode 1361AST_POLYMORPHIC_MATCHER_P(hasType, internal::Matcher<QualType>, 1362 InnerMatcher) { 1363 TOOLING_COMPILE_ASSERT((llvm::is_base_of<Expr, NodeType>::value || 1364 llvm::is_base_of<ValueDecl, NodeType>::value), 1365 instantiated_with_wrong_types); 1366 return InnerMatcher.matches(Node.getType(), Finder, Builder); 1367} 1368 1369/// \brief Overloaded to match the declaration of the expression's or value 1370/// declaration's type. 1371/// 1372/// In case of a value declaration (for example a variable declaration), 1373/// this resolves one layer of indirection. For example, in the value 1374/// declaration "X x;", recordDecl(hasName("X")) matches the declaration of X, 1375/// while varDecl(hasType(recordDecl(hasName("X")))) matches the declaration 1376/// of x." 1377/// 1378/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) 1379/// and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) 1380/// \code 1381/// class X {}; 1382/// void y(X &x) { x; X z; } 1383/// \endcode 1384/// 1385/// Usable as: Matcher<Expr>, Matcher<ValueDecl> 1386inline internal::PolymorphicMatcherWithParam1< 1387 internal::matcher_hasTypeMatcher, 1388 internal::Matcher<QualType> > 1389hasType(const internal::Matcher<Decl> &InnerMatcher) { 1390 return hasType(internal::Matcher<QualType>( 1391 hasDeclaration(InnerMatcher))); 1392} 1393 1394/// \brief Matches if the matched type is represented by the given string. 1395/// 1396/// Given 1397/// \code 1398/// class Y { public: void x(); }; 1399/// void z() { Y* y; y->x(); } 1400/// \endcode 1401/// callExpr(on(hasType(asString("class Y *")))) 1402/// matches y->x() 1403AST_MATCHER_P(QualType, asString, std::string, Name) { 1404 return Name == Node.getAsString(); 1405} 1406 1407/// \brief Matches if the matched type is a pointer type and the pointee type 1408/// matches the specified matcher. 1409/// 1410/// Example matches y->x() 1411/// (matcher = callExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))))) 1412/// \code 1413/// class Y { public: void x(); }; 1414/// void z() { Y *y; y->x(); } 1415/// \endcode 1416AST_MATCHER_P( 1417 QualType, pointsTo, internal::Matcher<QualType>, 1418 InnerMatcher) { 1419 return (!Node.isNull() && Node->isPointerType() && 1420 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1421} 1422 1423/// \brief Overloaded to match the pointee type's declaration. 1424inline internal::Matcher<QualType> pointsTo( 1425 const internal::Matcher<Decl> &InnerMatcher) { 1426 return pointsTo(internal::Matcher<QualType>( 1427 hasDeclaration(InnerMatcher))); 1428} 1429 1430/// \brief Matches if the matched type is a reference type and the referenced 1431/// type matches the specified matcher. 1432/// 1433/// Example matches X &x and const X &y 1434/// (matcher = varDecl(hasType(references(recordDecl(hasName("X")))))) 1435/// \code 1436/// class X { 1437/// void a(X b) { 1438/// X &x = b; 1439/// const X &y = b; 1440/// }; 1441/// \endcode 1442AST_MATCHER_P(QualType, references, internal::Matcher<QualType>, 1443 InnerMatcher) { 1444 return (!Node.isNull() && Node->isReferenceType() && 1445 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1446} 1447 1448/// \brief Overloaded to match the referenced type's declaration. 1449inline internal::Matcher<QualType> references( 1450 const internal::Matcher<Decl> &InnerMatcher) { 1451 return references(internal::Matcher<QualType>( 1452 hasDeclaration(InnerMatcher))); 1453} 1454 1455AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument, 1456 internal::Matcher<Expr>, InnerMatcher) { 1457 const Expr *ExprNode = 1458 const_cast<CXXMemberCallExpr&>(Node).getImplicitObjectArgument(); 1459 return (ExprNode != NULL && 1460 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1461} 1462 1463/// \brief Matches if the expression's type either matches the specified 1464/// matcher, or is a pointer to a type that matches the InnerMatcher. 1465inline internal::Matcher<CXXMemberCallExpr> thisPointerType( 1466 const internal::Matcher<QualType> &InnerMatcher) { 1467 return onImplicitObjectArgument( 1468 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 1469} 1470 1471/// \brief Overloaded to match the type's declaration. 1472inline internal::Matcher<CXXMemberCallExpr> thisPointerType( 1473 const internal::Matcher<Decl> &InnerMatcher) { 1474 return onImplicitObjectArgument( 1475 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 1476} 1477 1478/// \brief Matches a DeclRefExpr that refers to a declaration that matches the 1479/// specified matcher. 1480/// 1481/// Example matches x in if(x) 1482/// (matcher = declRefExpr(to(varDecl(hasName("x"))))) 1483/// \code 1484/// bool x; 1485/// if (x) {} 1486/// \endcode 1487AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>, 1488 InnerMatcher) { 1489 const Decl *DeclNode = Node.getDecl(); 1490 return (DeclNode != NULL && 1491 InnerMatcher.matches(*DeclNode, Finder, Builder)); 1492} 1493 1494/// \brief Matches a \c DeclRefExpr that refers to a declaration through a 1495/// specific using shadow declaration. 1496/// 1497/// FIXME: This currently only works for functions. Fix. 1498/// 1499/// Given 1500/// \code 1501/// namespace a { void f() {} } 1502/// using a::f; 1503/// void g() { 1504/// f(); // Matches this .. 1505/// a::f(); // .. but not this. 1506/// } 1507/// \endcode 1508/// declRefExpr(throughUsingDeclaration(anything())) 1509/// matches \c f() 1510AST_MATCHER_P(DeclRefExpr, throughUsingDecl, 1511 internal::Matcher<UsingShadowDecl>, InnerMatcher) { 1512 const NamedDecl *FoundDecl = Node.getFoundDecl(); 1513 if (const UsingShadowDecl *UsingDecl = 1514 llvm::dyn_cast<UsingShadowDecl>(FoundDecl)) 1515 return InnerMatcher.matches(*UsingDecl, Finder, Builder); 1516 return false; 1517} 1518 1519/// \brief Matches the Decl of a DeclStmt which has a single declaration. 1520/// 1521/// Given 1522/// \code 1523/// int a, b; 1524/// int c; 1525/// \endcode 1526/// declStmt(hasSingleDecl(anything())) 1527/// matches 'int c;' but not 'int a, b;'. 1528AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) { 1529 if (Node.isSingleDecl()) { 1530 const Decl *FoundDecl = Node.getSingleDecl(); 1531 return InnerMatcher.matches(*FoundDecl, Finder, Builder); 1532 } 1533 return false; 1534} 1535 1536/// \brief Matches a variable declaration that has an initializer expression 1537/// that matches the given matcher. 1538/// 1539/// Example matches x (matcher = varDecl(hasInitializer(callExpr()))) 1540/// \code 1541/// bool y() { return true; } 1542/// bool x = y(); 1543/// \endcode 1544AST_MATCHER_P( 1545 VarDecl, hasInitializer, internal::Matcher<Expr>, 1546 InnerMatcher) { 1547 const Expr *Initializer = Node.getAnyInitializer(); 1548 return (Initializer != NULL && 1549 InnerMatcher.matches(*Initializer, Finder, Builder)); 1550} 1551 1552/// \brief Checks that a call expression or a constructor call expression has 1553/// a specific number of arguments (including absent default arguments). 1554/// 1555/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2))) 1556/// \code 1557/// void f(int x, int y); 1558/// f(0, 0); 1559/// \endcode 1560AST_POLYMORPHIC_MATCHER_P(argumentCountIs, unsigned, N) { 1561 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 1562 llvm::is_base_of<CXXConstructExpr, 1563 NodeType>::value), 1564 instantiated_with_wrong_types); 1565 return Node.getNumArgs() == N; 1566} 1567 1568/// \brief Matches the n'th argument of a call expression or a constructor 1569/// call expression. 1570/// 1571/// Example matches y in x(y) 1572/// (matcher = callExpr(hasArgument(0, declRefExpr()))) 1573/// \code 1574/// void x(int) { int y; x(y); } 1575/// \endcode 1576AST_POLYMORPHIC_MATCHER_P2( 1577 hasArgument, unsigned, N, internal::Matcher<Expr>, InnerMatcher) { 1578 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 1579 llvm::is_base_of<CXXConstructExpr, 1580 NodeType>::value), 1581 instantiated_with_wrong_types); 1582 return (N < Node.getNumArgs() && 1583 InnerMatcher.matches( 1584 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder)); 1585} 1586 1587/// \brief Matches declaration statements that contain a specific number of 1588/// declarations. 1589/// 1590/// Example: Given 1591/// \code 1592/// int a, b; 1593/// int c; 1594/// int d = 2, e; 1595/// \endcode 1596/// declCountIs(2) 1597/// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'. 1598AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) { 1599 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N; 1600} 1601 1602/// \brief Matches the n'th declaration of a declaration statement. 1603/// 1604/// Note that this does not work for global declarations because the AST 1605/// breaks up multiple-declaration DeclStmt's into multiple single-declaration 1606/// DeclStmt's. 1607/// Example: Given non-global declarations 1608/// \code 1609/// int a, b = 0; 1610/// int c; 1611/// int d = 2, e; 1612/// \endcode 1613/// declStmt(containsDeclaration( 1614/// 0, varDecl(hasInitializer(anything())))) 1615/// matches only 'int d = 2, e;', and 1616/// declStmt(containsDeclaration(1, varDecl())) 1617/// \code 1618/// matches 'int a, b = 0' as well as 'int d = 2, e;' 1619/// but 'int c;' is not matched. 1620/// \endcode 1621AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N, 1622 internal::Matcher<Decl>, InnerMatcher) { 1623 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end()); 1624 if (N >= NumDecls) 1625 return false; 1626 DeclStmt::const_decl_iterator Iterator = Node.decl_begin(); 1627 std::advance(Iterator, N); 1628 return InnerMatcher.matches(**Iterator, Finder, Builder); 1629} 1630 1631/// \brief Matches a constructor initializer. 1632/// 1633/// Given 1634/// \code 1635/// struct Foo { 1636/// Foo() : foo_(1) { } 1637/// int foo_; 1638/// }; 1639/// \endcode 1640/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything())))) 1641/// record matches Foo, hasAnyConstructorInitializer matches foo_(1) 1642AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer, 1643 internal::Matcher<CXXCtorInitializer>, InnerMatcher) { 1644 for (CXXConstructorDecl::init_const_iterator I = Node.init_begin(); 1645 I != Node.init_end(); ++I) { 1646 if (InnerMatcher.matches(**I, Finder, Builder)) { 1647 return true; 1648 } 1649 } 1650 return false; 1651} 1652 1653/// \brief Matches the field declaration of a constructor initializer. 1654/// 1655/// Given 1656/// \code 1657/// struct Foo { 1658/// Foo() : foo_(1) { } 1659/// int foo_; 1660/// }; 1661/// \endcode 1662/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer( 1663/// forField(hasName("foo_")))))) 1664/// matches Foo 1665/// with forField matching foo_ 1666AST_MATCHER_P(CXXCtorInitializer, forField, 1667 internal::Matcher<FieldDecl>, InnerMatcher) { 1668 const FieldDecl *NodeAsDecl = Node.getMember(); 1669 return (NodeAsDecl != NULL && 1670 InnerMatcher.matches(*NodeAsDecl, Finder, Builder)); 1671} 1672 1673/// \brief Matches the initializer expression of a constructor initializer. 1674/// 1675/// Given 1676/// \code 1677/// struct Foo { 1678/// Foo() : foo_(1) { } 1679/// int foo_; 1680/// }; 1681/// \endcode 1682/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer( 1683/// withInitializer(integerLiteral(equals(1))))))) 1684/// matches Foo 1685/// with withInitializer matching (1) 1686AST_MATCHER_P(CXXCtorInitializer, withInitializer, 1687 internal::Matcher<Expr>, InnerMatcher) { 1688 const Expr* NodeAsExpr = Node.getInit(); 1689 return (NodeAsExpr != NULL && 1690 InnerMatcher.matches(*NodeAsExpr, Finder, Builder)); 1691} 1692 1693/// \brief Matches a contructor initializer if it is explicitly written in 1694/// code (as opposed to implicitly added by the compiler). 1695/// 1696/// Given 1697/// \code 1698/// struct Foo { 1699/// Foo() { } 1700/// Foo(int) : foo_("A") { } 1701/// string foo_; 1702/// }; 1703/// \endcode 1704/// constructorDecl(hasAnyConstructorInitializer(isWritten())) 1705/// will match Foo(int), but not Foo() 1706AST_MATCHER(CXXCtorInitializer, isWritten) { 1707 return Node.isWritten(); 1708} 1709 1710/// \brief Matches a constructor declaration that has been implicitly added 1711/// by the compiler (eg. implicit default/copy constructors). 1712AST_MATCHER(CXXConstructorDecl, isImplicit) { 1713 return Node.isImplicit(); 1714} 1715 1716/// \brief Matches any argument of a call expression or a constructor call 1717/// expression. 1718/// 1719/// Given 1720/// \code 1721/// void x(int, int, int) { int y; x(1, y, 42); } 1722/// \endcode 1723/// callExpr(hasAnyArgument(declRefExpr())) 1724/// matches x(1, y, 42) 1725/// with hasAnyArgument(...) 1726/// matching y 1727AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, internal::Matcher<Expr>, 1728 InnerMatcher) { 1729 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 1730 llvm::is_base_of<CXXConstructExpr, 1731 NodeType>::value), 1732 instantiated_with_wrong_types); 1733 for (unsigned I = 0; I < Node.getNumArgs(); ++I) { 1734 if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(), 1735 Finder, Builder)) { 1736 return true; 1737 } 1738 } 1739 return false; 1740} 1741 1742/// \brief Matches the n'th parameter of a function declaration. 1743/// 1744/// Given 1745/// \code 1746/// class X { void f(int x) {} }; 1747/// \endcode 1748/// methodDecl(hasParameter(0, hasType(varDecl()))) 1749/// matches f(int x) {} 1750/// with hasParameter(...) 1751/// matching int x 1752AST_MATCHER_P2(FunctionDecl, hasParameter, 1753 unsigned, N, internal::Matcher<ParmVarDecl>, 1754 InnerMatcher) { 1755 return (N < Node.getNumParams() && 1756 InnerMatcher.matches( 1757 *Node.getParamDecl(N), Finder, Builder)); 1758} 1759 1760/// \brief Matches any parameter of a function declaration. 1761/// 1762/// Does not match the 'this' parameter of a method. 1763/// 1764/// Given 1765/// \code 1766/// class X { void f(int x, int y, int z) {} }; 1767/// \endcode 1768/// methodDecl(hasAnyParameter(hasName("y"))) 1769/// matches f(int x, int y, int z) {} 1770/// with hasAnyParameter(...) 1771/// matching int y 1772AST_MATCHER_P(FunctionDecl, hasAnyParameter, 1773 internal::Matcher<ParmVarDecl>, InnerMatcher) { 1774 for (unsigned I = 0; I < Node.getNumParams(); ++I) { 1775 if (InnerMatcher.matches(*Node.getParamDecl(I), Finder, Builder)) { 1776 return true; 1777 } 1778 } 1779 return false; 1780} 1781 1782/// \brief Matches the return type of a function declaration. 1783/// 1784/// Given: 1785/// \code 1786/// class X { int f() { return 1; } }; 1787/// \endcode 1788/// methodDecl(returns(asString("int"))) 1789/// matches int f() { return 1; } 1790AST_MATCHER_P(FunctionDecl, returns, 1791 internal::Matcher<QualType>, InnerMatcher) { 1792 return InnerMatcher.matches(Node.getResultType(), Finder, Builder); 1793} 1794 1795/// \brief Matches extern "C" function declarations. 1796/// 1797/// Given: 1798/// \code 1799/// extern "C" void f() {} 1800/// extern "C" { void g() {} } 1801/// void h() {} 1802/// \endcode 1803/// functionDecl(isExternC()) 1804/// matches the declaration of f and g, but not the declaration h 1805AST_MATCHER(FunctionDecl, isExternC) { 1806 return Node.isExternC(); 1807} 1808 1809/// \brief Matches the condition expression of an if statement, for loop, 1810/// or conditional operator. 1811/// 1812/// Example matches true (matcher = hasCondition(boolLiteral(equals(true)))) 1813/// \code 1814/// if (true) {} 1815/// \endcode 1816AST_POLYMORPHIC_MATCHER_P(hasCondition, internal::Matcher<Expr>, 1817 InnerMatcher) { 1818 TOOLING_COMPILE_ASSERT( 1819 (llvm::is_base_of<IfStmt, NodeType>::value) || 1820 (llvm::is_base_of<ForStmt, NodeType>::value) || 1821 (llvm::is_base_of<WhileStmt, NodeType>::value) || 1822 (llvm::is_base_of<DoStmt, NodeType>::value) || 1823 (llvm::is_base_of<ConditionalOperator, NodeType>::value), 1824 has_condition_requires_if_statement_conditional_operator_or_loop); 1825 const Expr *const Condition = Node.getCond(); 1826 return (Condition != NULL && 1827 InnerMatcher.matches(*Condition, Finder, Builder)); 1828} 1829 1830/// \brief Matches the condition variable statement in an if statement. 1831/// 1832/// Given 1833/// \code 1834/// if (A* a = GetAPointer()) {} 1835/// \endcode 1836/// hasConditionVariableStatment(...) 1837/// matches 'A* a = GetAPointer()'. 1838AST_MATCHER_P(IfStmt, hasConditionVariableStatement, 1839 internal::Matcher<DeclStmt>, InnerMatcher) { 1840 const DeclStmt* const DeclarationStatement = 1841 Node.getConditionVariableDeclStmt(); 1842 return DeclarationStatement != NULL && 1843 InnerMatcher.matches(*DeclarationStatement, Finder, Builder); 1844} 1845 1846/// \brief Matches the index expression of an array subscript expression. 1847/// 1848/// Given 1849/// \code 1850/// int i[5]; 1851/// void f() { i[1] = 42; } 1852/// \endcode 1853/// arraySubscriptExpression(hasIndex(integerLiteral())) 1854/// matches \c i[1] with the \c integerLiteral() matching \c 1 1855AST_MATCHER_P(ArraySubscriptExpr, hasIndex, 1856 internal::Matcher<Expr>, InnerMatcher) { 1857 if (const Expr* Expression = Node.getIdx()) 1858 return InnerMatcher.matches(*Expression, Finder, Builder); 1859 return false; 1860} 1861 1862/// \brief Matches the base expression of an array subscript expression. 1863/// 1864/// Given 1865/// \code 1866/// int i[5]; 1867/// void f() { i[1] = 42; } 1868/// \endcode 1869/// arraySubscriptExpression(hasBase(implicitCastExpr( 1870/// hasSourceExpression(declRefExpr())))) 1871/// matches \c i[1] with the \c declRefExpr() matching \c i 1872AST_MATCHER_P(ArraySubscriptExpr, hasBase, 1873 internal::Matcher<Expr>, InnerMatcher) { 1874 if (const Expr* Expression = Node.getBase()) 1875 return InnerMatcher.matches(*Expression, Finder, Builder); 1876 return false; 1877} 1878 1879/// \brief Matches a 'for', 'while', or 'do while' statement that has 1880/// a given body. 1881/// 1882/// Given 1883/// \code 1884/// for (;;) {} 1885/// \endcode 1886/// hasBody(compoundStmt()) 1887/// matches 'for (;;) {}' 1888/// with compoundStmt() 1889/// matching '{}' 1890AST_POLYMORPHIC_MATCHER_P(hasBody, internal::Matcher<Stmt>, 1891 InnerMatcher) { 1892 TOOLING_COMPILE_ASSERT( 1893 (llvm::is_base_of<DoStmt, NodeType>::value) || 1894 (llvm::is_base_of<ForStmt, NodeType>::value) || 1895 (llvm::is_base_of<WhileStmt, NodeType>::value), 1896 has_body_requires_for_while_or_do_statement); 1897 const Stmt *const Statement = Node.getBody(); 1898 return (Statement != NULL && 1899 InnerMatcher.matches(*Statement, Finder, Builder)); 1900} 1901 1902/// \brief Matches compound statements where at least one substatement matches 1903/// a given matcher. 1904/// 1905/// Given 1906/// \code 1907/// { {}; 1+2; } 1908/// \endcode 1909/// hasAnySubstatement(compoundStmt()) 1910/// matches '{ {}; 1+2; }' 1911/// with compoundStmt() 1912/// matching '{}' 1913AST_MATCHER_P(CompoundStmt, hasAnySubstatement, 1914 internal::Matcher<Stmt>, InnerMatcher) { 1915 for (CompoundStmt::const_body_iterator It = Node.body_begin(); 1916 It != Node.body_end(); 1917 ++It) { 1918 if (InnerMatcher.matches(**It, Finder, Builder)) return true; 1919 } 1920 return false; 1921} 1922 1923/// \brief Checks that a compound statement contains a specific number of 1924/// child statements. 1925/// 1926/// Example: Given 1927/// \code 1928/// { for (;;) {} } 1929/// \endcode 1930/// compoundStmt(statementCountIs(0))) 1931/// matches '{}' 1932/// but does not match the outer compound statement. 1933AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) { 1934 return Node.size() == N; 1935} 1936 1937/// \brief Matches literals that are equal to the given value. 1938/// 1939/// Example matches true (matcher = boolLiteral(equals(true))) 1940/// \code 1941/// true 1942/// \endcode 1943/// 1944/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>, 1945/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral> 1946template <typename ValueT> 1947internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT> 1948equals(const ValueT &Value) { 1949 return internal::PolymorphicMatcherWithParam1< 1950 internal::ValueEqualsMatcher, 1951 ValueT>(Value); 1952} 1953 1954/// \brief Matches the operator Name of operator expressions (binary or 1955/// unary). 1956/// 1957/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||"))) 1958/// \code 1959/// !(a || b) 1960/// \endcode 1961AST_POLYMORPHIC_MATCHER_P(hasOperatorName, std::string, Name) { 1962 TOOLING_COMPILE_ASSERT( 1963 (llvm::is_base_of<BinaryOperator, NodeType>::value) || 1964 (llvm::is_base_of<UnaryOperator, NodeType>::value), 1965 has_condition_requires_if_statement_or_conditional_operator); 1966 return Name == Node.getOpcodeStr(Node.getOpcode()); 1967} 1968 1969/// \brief Matches the left hand side of binary operator expressions. 1970/// 1971/// Example matches a (matcher = binaryOperator(hasLHS())) 1972/// \code 1973/// a || b 1974/// \endcode 1975AST_MATCHER_P(BinaryOperator, hasLHS, 1976 internal::Matcher<Expr>, InnerMatcher) { 1977 Expr *LeftHandSide = Node.getLHS(); 1978 return (LeftHandSide != NULL && 1979 InnerMatcher.matches(*LeftHandSide, Finder, Builder)); 1980} 1981 1982/// \brief Matches the right hand side of binary operator expressions. 1983/// 1984/// Example matches b (matcher = binaryOperator(hasRHS())) 1985/// \code 1986/// a || b 1987/// \endcode 1988AST_MATCHER_P(BinaryOperator, hasRHS, 1989 internal::Matcher<Expr>, InnerMatcher) { 1990 Expr *RightHandSide = Node.getRHS(); 1991 return (RightHandSide != NULL && 1992 InnerMatcher.matches(*RightHandSide, Finder, Builder)); 1993} 1994 1995/// \brief Matches if either the left hand side or the right hand side of a 1996/// binary operator matches. 1997inline internal::Matcher<BinaryOperator> hasEitherOperand( 1998 const internal::Matcher<Expr> &InnerMatcher) { 1999 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)); 2000} 2001 2002/// \brief Matches if the operand of a unary operator matches. 2003/// 2004/// Example matches true (matcher = hasOperand(boolLiteral(equals(true)))) 2005/// \code 2006/// !true 2007/// \endcode 2008AST_MATCHER_P(UnaryOperator, hasUnaryOperand, 2009 internal::Matcher<Expr>, InnerMatcher) { 2010 const Expr * const Operand = Node.getSubExpr(); 2011 return (Operand != NULL && 2012 InnerMatcher.matches(*Operand, Finder, Builder)); 2013} 2014 2015/// \brief Matches if the cast's source expression matches the given matcher. 2016/// 2017/// Example: matches "a string" (matcher = 2018/// hasSourceExpression(constructExpr())) 2019/// \code 2020/// class URL { URL(string); }; 2021/// URL url = "a string"; 2022AST_MATCHER_P(CastExpr, hasSourceExpression, 2023 internal::Matcher<Expr>, InnerMatcher) { 2024 const Expr* const SubExpression = Node.getSubExpr(); 2025 return (SubExpression != NULL && 2026 InnerMatcher.matches(*SubExpression, Finder, Builder)); 2027} 2028 2029/// \brief Matches casts whose destination type matches a given matcher. 2030/// 2031/// (Note: Clang's AST refers to other conversions as "casts" too, and calls 2032/// actual casts "explicit" casts.) 2033AST_MATCHER_P(ExplicitCastExpr, hasDestinationType, 2034 internal::Matcher<QualType>, InnerMatcher) { 2035 const QualType NodeType = Node.getTypeAsWritten(); 2036 return InnerMatcher.matches(NodeType, Finder, Builder); 2037} 2038 2039/// \brief Matches implicit casts whose destination type matches a given 2040/// matcher. 2041/// 2042/// FIXME: Unit test this matcher 2043AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType, 2044 internal::Matcher<QualType>, InnerMatcher) { 2045 return InnerMatcher.matches(Node.getType(), Finder, Builder); 2046} 2047 2048/// \brief Matches the true branch expression of a conditional operator. 2049/// 2050/// Example matches a 2051/// \code 2052/// condition ? a : b 2053/// \endcode 2054AST_MATCHER_P(ConditionalOperator, hasTrueExpression, 2055 internal::Matcher<Expr>, InnerMatcher) { 2056 Expr *Expression = Node.getTrueExpr(); 2057 return (Expression != NULL && 2058 InnerMatcher.matches(*Expression, Finder, Builder)); 2059} 2060 2061/// \brief Matches the false branch expression of a conditional operator. 2062/// 2063/// Example matches b 2064/// \code 2065/// condition ? a : b 2066/// \endcode 2067AST_MATCHER_P(ConditionalOperator, hasFalseExpression, 2068 internal::Matcher<Expr>, InnerMatcher) { 2069 Expr *Expression = Node.getFalseExpr(); 2070 return (Expression != NULL && 2071 InnerMatcher.matches(*Expression, Finder, Builder)); 2072} 2073 2074/// \brief Matches if a declaration has a body attached. 2075/// 2076/// Example matches A, va, fa 2077/// \code 2078/// class A {}; 2079/// class B; // Doesn't match, as it has no body. 2080/// int va; 2081/// extern int vb; // Doesn't match, as it doesn't define the variable. 2082/// void fa() {} 2083/// void fb(); // Doesn't match, as it has no body. 2084/// \endcode 2085/// 2086/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl> 2087inline internal::PolymorphicMatcherWithParam0<internal::IsDefinitionMatcher> 2088isDefinition() { 2089 return internal::PolymorphicMatcherWithParam0< 2090 internal::IsDefinitionMatcher>(); 2091} 2092 2093/// \brief Matches the class declaration that the given method declaration 2094/// belongs to. 2095/// 2096/// FIXME: Generalize this for other kinds of declarations. 2097/// FIXME: What other kind of declarations would we need to generalize 2098/// this to? 2099/// 2100/// Example matches A() in the last line 2101/// (matcher = constructExpr(hasDeclaration(methodDecl( 2102/// ofClass(hasName("A")))))) 2103/// \code 2104/// class A { 2105/// public: 2106/// A(); 2107/// }; 2108/// A a = A(); 2109/// \endcode 2110AST_MATCHER_P(CXXMethodDecl, ofClass, 2111 internal::Matcher<CXXRecordDecl>, InnerMatcher) { 2112 const CXXRecordDecl *Parent = Node.getParent(); 2113 return (Parent != NULL && 2114 InnerMatcher.matches(*Parent, Finder, Builder)); 2115} 2116 2117/// \brief Matches member expressions that are called with '->' as opposed 2118/// to '.'. 2119/// 2120/// Member calls on the implicit this pointer match as called with '->'. 2121/// 2122/// Given 2123/// \code 2124/// class Y { 2125/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 2126/// int a; 2127/// static int b; 2128/// }; 2129/// \endcode 2130/// memberExpr(isArrow()) 2131/// matches this->x, x, y.x, a, this->b 2132inline internal::Matcher<MemberExpr> isArrow() { 2133 return makeMatcher(new internal::IsArrowMatcher()); 2134} 2135 2136/// \brief Matches QualType nodes that are of integer type. 2137/// 2138/// Given 2139/// \code 2140/// void a(int); 2141/// void b(long); 2142/// void c(double); 2143/// \endcode 2144/// functionDecl(hasAnyParameter(hasType(isInteger()))) 2145/// matches "a(int)", "b(long)", but not "c(double)". 2146AST_MATCHER(QualType, isInteger) { 2147 return Node->isIntegerType(); 2148} 2149 2150/// \brief Matches QualType nodes that are const-qualified, i.e., that 2151/// include "top-level" const. 2152/// 2153/// Given 2154/// \code 2155/// void a(int); 2156/// void b(int const); 2157/// void c(const int); 2158/// void d(const int*); 2159/// void e(int const) {}; 2160/// \endcode 2161/// functionDecl(hasAnyParameter(hasType(isConstQualified()))) 2162/// matches "void b(int const)", "void c(const int)" and 2163/// "void e(int const) {}". It does not match d as there 2164/// is no top-level const on the parameter type "const int *". 2165inline internal::Matcher<QualType> isConstQualified() { 2166 return makeMatcher(new internal::IsConstQualifiedMatcher()); 2167} 2168 2169/// \brief Matches a member expression where the member is matched by a 2170/// given matcher. 2171/// 2172/// Given 2173/// \code 2174/// struct { int first, second; } first, second; 2175/// int i(second.first); 2176/// int j(first.second); 2177/// \endcode 2178/// memberExpr(member(hasName("first"))) 2179/// matches second.first 2180/// but not first.second (because the member name there is "second"). 2181AST_MATCHER_P(MemberExpr, member, 2182 internal::Matcher<ValueDecl>, InnerMatcher) { 2183 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder); 2184} 2185 2186/// \brief Matches a member expression where the object expression is 2187/// matched by a given matcher. 2188/// 2189/// Given 2190/// \code 2191/// struct X { int m; }; 2192/// void f(X x) { x.m; m; } 2193/// \endcode 2194/// memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X"))))))) 2195/// matches "x.m" and "m" 2196/// with hasObjectExpression(...) 2197/// matching "x" and the implicit object expression of "m" which has type X*. 2198AST_MATCHER_P(MemberExpr, hasObjectExpression, 2199 internal::Matcher<Expr>, InnerMatcher) { 2200 return InnerMatcher.matches(*Node.getBase(), Finder, Builder); 2201} 2202 2203/// \brief Matches any using shadow declaration. 2204/// 2205/// Given 2206/// \code 2207/// namespace X { void b(); } 2208/// using X::b; 2209/// \endcode 2210/// usingDecl(hasAnyUsingShadowDecl(hasName("b")))) 2211/// matches \code using X::b \endcode 2212AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl, 2213 internal::Matcher<UsingShadowDecl>, InnerMatcher) { 2214 for (UsingDecl::shadow_iterator II = Node.shadow_begin(); 2215 II != Node.shadow_end(); ++II) { 2216 if (InnerMatcher.matches(**II, Finder, Builder)) 2217 return true; 2218 } 2219 return false; 2220} 2221 2222/// \brief Matches a using shadow declaration where the target declaration is 2223/// matched by the given matcher. 2224/// 2225/// Given 2226/// \code 2227/// namespace X { int a; void b(); } 2228/// using X::a; 2229/// using X::b; 2230/// \endcode 2231/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl()))) 2232/// matches \code using X::b \endcode 2233/// but not \code using X::a \endcode 2234AST_MATCHER_P(UsingShadowDecl, hasTargetDecl, 2235 internal::Matcher<NamedDecl>, InnerMatcher) { 2236 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder); 2237} 2238 2239/// \brief Matches template instantiations of function, class, or static 2240/// member variable template instantiations. 2241/// 2242/// Given 2243/// \code 2244/// template <typename T> class X {}; class A {}; X<A> x; 2245/// \endcode 2246/// or 2247/// \code 2248/// template <typename T> class X {}; class A {}; template class X<A>; 2249/// \endcode 2250/// recordDecl(hasName("::X"), isTemplateInstantiation()) 2251/// matches the template instantiation of X<A>. 2252/// 2253/// But given 2254/// \code 2255/// template <typename T> class X {}; class A {}; 2256/// template <> class X<A> {}; X<A> x; 2257/// \endcode 2258/// recordDecl(hasName("::X"), isTemplateInstantiation()) 2259/// does not match, as X<A> is an explicit template specialization. 2260/// 2261/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> 2262inline internal::PolymorphicMatcherWithParam0< 2263 internal::IsTemplateInstantiationMatcher> 2264isTemplateInstantiation() { 2265 return internal::PolymorphicMatcherWithParam0< 2266 internal::IsTemplateInstantiationMatcher>(); 2267} 2268 2269/// \brief Matches explicit template specializations of function, class, or 2270/// static member variable template instantiations. 2271/// 2272/// Given 2273/// \code 2274/// template<typename T> void A(T t) { } 2275/// template<> void A(int N) { } 2276/// \endcode 2277/// functionDecl(isExplicitTemplateSpecialization()) 2278/// matches the specialization A<int>(). 2279/// 2280/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> 2281inline internal::PolymorphicMatcherWithParam0< 2282 internal::IsExplicitTemplateSpecializationMatcher> 2283isExplicitTemplateSpecialization() { 2284 return internal::PolymorphicMatcherWithParam0< 2285 internal::IsExplicitTemplateSpecializationMatcher>(); 2286} 2287 2288} // end namespace ast_matchers 2289} // end namespace clang 2290 2291#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H 2292