ASTMatchers.h revision 579b120038ca817e0ce423303ebc1b4e0c6cbbe1
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 considered to be also derived from itself. 1112/// 1113/// Example matches X, Y, Z, C (Base == hasName("X")) 1114/// \code 1115/// class X; // A class is considered to be derived from itself 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 Matches AST nodes that have child AST nodes that match the 1141/// provided matcher. 1142/// 1143/// Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X"))) 1144/// \code 1145/// class X {}; // Matches X, because X::X is a class of name X inside X. 1146/// class Y { class X {}; }; 1147/// class Z { class Y { class X {}; }; }; // Does not match Z. 1148/// \endcode 1149/// 1150/// ChildT must be an AST base type. 1151/// 1152/// Usable as: Any Matcher 1153template <typename ChildT> 1154internal::ArgumentAdaptingMatcher<internal::HasMatcher, ChildT> has( 1155 const internal::Matcher<ChildT> &ChildMatcher) { 1156 return internal::ArgumentAdaptingMatcher<internal::HasMatcher, 1157 ChildT>(ChildMatcher); 1158} 1159 1160/// \brief Matches AST nodes that have descendant AST nodes that match the 1161/// provided matcher. 1162/// 1163/// Example matches X, Y, Z 1164/// (matcher = recordDecl(hasDescendant(recordDecl(hasName("X"))))) 1165/// \code 1166/// class X {}; // Matches X, because X::X is a class of name X inside X. 1167/// class Y { class X {}; }; 1168/// class Z { class Y { class X {}; }; }; 1169/// \endcode 1170/// 1171/// DescendantT must be an AST base type. 1172/// 1173/// Usable as: Any Matcher 1174template <typename DescendantT> 1175internal::ArgumentAdaptingMatcher<internal::HasDescendantMatcher, DescendantT> 1176hasDescendant(const internal::Matcher<DescendantT> &DescendantMatcher) { 1177 return internal::ArgumentAdaptingMatcher< 1178 internal::HasDescendantMatcher, 1179 DescendantT>(DescendantMatcher); 1180} 1181 1182/// \brief Matches AST nodes that have child AST nodes that match the 1183/// provided matcher. 1184/// 1185/// Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X"))) 1186/// \code 1187/// class X {}; // Matches X, because X::X is a class of name X inside X. 1188/// class Y { class X {}; }; 1189/// class Z { class Y { class X {}; }; }; // Does not match Z. 1190/// \endcode 1191/// 1192/// ChildT must be an AST base type. 1193/// 1194/// As opposed to 'has', 'forEach' will cause a match for each result that 1195/// matches instead of only on the first one. 1196/// 1197/// Usable as: Any Matcher 1198template <typename ChildT> 1199internal::ArgumentAdaptingMatcher<internal::ForEachMatcher, ChildT> forEach( 1200 const internal::Matcher<ChildT> &ChildMatcher) { 1201 return internal::ArgumentAdaptingMatcher< 1202 internal::ForEachMatcher, 1203 ChildT>(ChildMatcher); 1204} 1205 1206/// \brief Matches AST nodes that have descendant AST nodes that match the 1207/// provided matcher. 1208/// 1209/// Example matches X, A, B, C 1210/// (matcher = recordDecl(forEachDescendant(recordDecl(hasName("X"))))) 1211/// \code 1212/// class X {}; // Matches X, because X::X is a class of name X inside X. 1213/// class A { class X {}; }; 1214/// class B { class C { class X {}; }; }; 1215/// \endcode 1216/// 1217/// DescendantT must be an AST base type. 1218/// 1219/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for 1220/// each result that matches instead of only on the first one. 1221/// 1222/// Note: Recursively combined ForEachDescendant can cause many matches: 1223/// recordDecl(forEachDescendant(recordDecl(forEachDescendant(recordDecl())))) 1224/// will match 10 times (plus injected class name matches) on: 1225/// \code 1226/// class A { class B { class C { class D { class E {}; }; }; }; }; 1227/// \endcode 1228/// 1229/// Usable as: Any Matcher 1230template <typename DescendantT> 1231internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, DescendantT> 1232forEachDescendant( 1233 const internal::Matcher<DescendantT> &DescendantMatcher) { 1234 return internal::ArgumentAdaptingMatcher< 1235 internal::ForEachDescendantMatcher, 1236 DescendantT>(DescendantMatcher); 1237} 1238 1239/// \brief Matches AST nodes that have an ancestor that matches the provided 1240/// matcher. 1241/// 1242/// Given 1243/// \code 1244/// void f() { if (true) { int x = 42; } } 1245/// void g() { for (;;) { int x = 43; } } 1246/// \endcode 1247/// \c expr(integerLiteral(hasAncsestor(ifStmt()))) matches \c 42, but not 43. 1248/// 1249/// Usable as: Any Matcher 1250template <typename AncestorT> 1251internal::ArgumentAdaptingMatcher<internal::HasAncestorMatcher, AncestorT> 1252hasAncestor(const internal::Matcher<AncestorT> &AncestorMatcher) { 1253 return internal::ArgumentAdaptingMatcher< 1254 internal::HasAncestorMatcher, 1255 AncestorT>(AncestorMatcher); 1256} 1257 1258/// \brief Matches if the provided matcher does not match. 1259/// 1260/// Example matches Y (matcher = recordDecl(unless(hasName("X")))) 1261/// \code 1262/// class X {}; 1263/// class Y {}; 1264/// \endcode 1265/// 1266/// Usable as: Any Matcher 1267template <typename M> 1268internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M> 1269unless(const M &InnerMatcher) { 1270 return internal::PolymorphicMatcherWithParam1< 1271 internal::NotMatcher, M>(InnerMatcher); 1272} 1273 1274/// \brief Matches a type if the declaration of the type matches the given 1275/// matcher. 1276/// 1277/// Usable as: Matcher<QualType>, Matcher<CallExpr>, Matcher<CXXConstructExpr> 1278inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher, 1279 internal::Matcher<Decl> > 1280 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) { 1281 return internal::PolymorphicMatcherWithParam1< 1282 internal::HasDeclarationMatcher, 1283 internal::Matcher<Decl> >(InnerMatcher); 1284} 1285 1286/// \brief Matches on the implicit object argument of a member call expression. 1287/// 1288/// Example matches y.x() (matcher = callExpr(on(hasType(recordDecl(hasName("Y")))))) 1289/// \code 1290/// class Y { public: void x(); }; 1291/// void z() { Y y; y.x(); }", 1292/// \endcode 1293/// 1294/// FIXME: Overload to allow directly matching types? 1295AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>, 1296 InnerMatcher) { 1297 const Expr *ExprNode = const_cast<CXXMemberCallExpr&>(Node) 1298 .getImplicitObjectArgument() 1299 ->IgnoreParenImpCasts(); 1300 return (ExprNode != NULL && 1301 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1302} 1303 1304/// \brief Matches if the call expression's callee expression matches. 1305/// 1306/// Given 1307/// \code 1308/// class Y { void x() { this->x(); x(); Y y; y.x(); } }; 1309/// void f() { f(); } 1310/// \endcode 1311/// callExpr(callee(expr())) 1312/// matches this->x(), x(), y.x(), f() 1313/// with callee(...) 1314/// matching this->x, x, y.x, f respectively 1315/// 1316/// Note: Callee cannot take the more general internal::Matcher<Expr> 1317/// because this introduces ambiguous overloads with calls to Callee taking a 1318/// internal::Matcher<Decl>, as the matcher hierarchy is purely 1319/// implemented in terms of implicit casts. 1320AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>, 1321 InnerMatcher) { 1322 const Expr *ExprNode = Node.getCallee(); 1323 return (ExprNode != NULL && 1324 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1325} 1326 1327/// \brief Matches if the call expression's callee's declaration matches the 1328/// given matcher. 1329/// 1330/// Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x"))))) 1331/// \code 1332/// class Y { public: void x(); }; 1333/// void z() { Y y; y.x(); 1334/// \endcode 1335inline internal::Matcher<CallExpr> callee( 1336 const internal::Matcher<Decl> &InnerMatcher) { 1337 return internal::Matcher<CallExpr>(hasDeclaration(InnerMatcher)); 1338} 1339 1340/// \brief Matches if the expression's or declaration's type matches a type 1341/// matcher. 1342/// 1343/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) 1344/// and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) 1345/// \code 1346/// class X {}; 1347/// void y(X &x) { x; X z; } 1348/// \endcode 1349AST_POLYMORPHIC_MATCHER_P(hasType, internal::Matcher<QualType>, 1350 InnerMatcher) { 1351 TOOLING_COMPILE_ASSERT((llvm::is_base_of<Expr, NodeType>::value || 1352 llvm::is_base_of<ValueDecl, NodeType>::value), 1353 instantiated_with_wrong_types); 1354 return InnerMatcher.matches(Node.getType(), Finder, Builder); 1355} 1356 1357/// \brief Overloaded to match the declaration of the expression's or value 1358/// declaration's type. 1359/// 1360/// In case of a value declaration (for example a variable declaration), 1361/// this resolves one layer of indirection. For example, in the value 1362/// declaration "X x;", recordDecl(hasName("X")) matches the declaration of X, 1363/// while varDecl(hasType(recordDecl(hasName("X")))) matches the declaration 1364/// of x." 1365/// 1366/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) 1367/// and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) 1368/// \code 1369/// class X {}; 1370/// void y(X &x) { x; X z; } 1371/// \endcode 1372/// 1373/// Usable as: Matcher<Expr>, Matcher<ValueDecl> 1374inline internal::PolymorphicMatcherWithParam1< 1375 internal::matcher_hasTypeMatcher, 1376 internal::Matcher<QualType> > 1377hasType(const internal::Matcher<Decl> &InnerMatcher) { 1378 return hasType(internal::Matcher<QualType>( 1379 hasDeclaration(InnerMatcher))); 1380} 1381 1382/// \brief Matches if the matched type is represented by the given string. 1383/// 1384/// Given 1385/// \code 1386/// class Y { public: void x(); }; 1387/// void z() { Y* y; y->x(); } 1388/// \endcode 1389/// callExpr(on(hasType(asString("class Y *")))) 1390/// matches y->x() 1391AST_MATCHER_P(QualType, asString, std::string, Name) { 1392 return Name == Node.getAsString(); 1393} 1394 1395/// \brief Matches if the matched type is a pointer type and the pointee type 1396/// matches the specified matcher. 1397/// 1398/// Example matches y->x() 1399/// (matcher = callExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))))) 1400/// \code 1401/// class Y { public: void x(); }; 1402/// void z() { Y *y; y->x(); } 1403/// \endcode 1404AST_MATCHER_P( 1405 QualType, pointsTo, internal::Matcher<QualType>, 1406 InnerMatcher) { 1407 return (!Node.isNull() && Node->isPointerType() && 1408 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1409} 1410 1411/// \brief Overloaded to match the pointee type's declaration. 1412inline internal::Matcher<QualType> pointsTo( 1413 const internal::Matcher<Decl> &InnerMatcher) { 1414 return pointsTo(internal::Matcher<QualType>( 1415 hasDeclaration(InnerMatcher))); 1416} 1417 1418/// \brief Matches if the matched type is a reference type and the referenced 1419/// type matches the specified matcher. 1420/// 1421/// Example matches X &x and const X &y 1422/// (matcher = varDecl(hasType(references(recordDecl(hasName("X")))))) 1423/// \code 1424/// class X { 1425/// void a(X b) { 1426/// X &x = b; 1427/// const X &y = b; 1428/// }; 1429/// \endcode 1430AST_MATCHER_P(QualType, references, internal::Matcher<QualType>, 1431 InnerMatcher) { 1432 return (!Node.isNull() && Node->isReferenceType() && 1433 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1434} 1435 1436/// \brief Overloaded to match the referenced type's declaration. 1437inline internal::Matcher<QualType> references( 1438 const internal::Matcher<Decl> &InnerMatcher) { 1439 return references(internal::Matcher<QualType>( 1440 hasDeclaration(InnerMatcher))); 1441} 1442 1443AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument, 1444 internal::Matcher<Expr>, InnerMatcher) { 1445 const Expr *ExprNode = 1446 const_cast<CXXMemberCallExpr&>(Node).getImplicitObjectArgument(); 1447 return (ExprNode != NULL && 1448 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1449} 1450 1451/// \brief Matches if the expression's type either matches the specified 1452/// matcher, or is a pointer to a type that matches the InnerMatcher. 1453inline internal::Matcher<CXXMemberCallExpr> thisPointerType( 1454 const internal::Matcher<QualType> &InnerMatcher) { 1455 return onImplicitObjectArgument( 1456 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 1457} 1458 1459/// \brief Overloaded to match the type's declaration. 1460inline internal::Matcher<CXXMemberCallExpr> thisPointerType( 1461 const internal::Matcher<Decl> &InnerMatcher) { 1462 return onImplicitObjectArgument( 1463 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 1464} 1465 1466/// \brief Matches a DeclRefExpr that refers to a declaration that matches the 1467/// specified matcher. 1468/// 1469/// Example matches x in if(x) 1470/// (matcher = declRefExpr(to(varDecl(hasName("x"))))) 1471/// \code 1472/// bool x; 1473/// if (x) {} 1474/// \endcode 1475AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>, 1476 InnerMatcher) { 1477 const Decl *DeclNode = Node.getDecl(); 1478 return (DeclNode != NULL && 1479 InnerMatcher.matches(*DeclNode, Finder, Builder)); 1480} 1481 1482/// \brief Matches a \c DeclRefExpr that refers to a declaration through a 1483/// specific using shadow declaration. 1484/// 1485/// FIXME: This currently only works for functions. Fix. 1486/// 1487/// Given 1488/// \code 1489/// namespace a { void f() {} } 1490/// using a::f; 1491/// void g() { 1492/// f(); // Matches this .. 1493/// a::f(); // .. but not this. 1494/// } 1495/// \endcode 1496/// declRefExpr(throughUsingDeclaration(anything())) 1497/// matches \c f() 1498AST_MATCHER_P(DeclRefExpr, throughUsingDecl, 1499 internal::Matcher<UsingShadowDecl>, InnerMatcher) { 1500 const NamedDecl *FoundDecl = Node.getFoundDecl(); 1501 if (const UsingShadowDecl *UsingDecl = 1502 llvm::dyn_cast<UsingShadowDecl>(FoundDecl)) 1503 return InnerMatcher.matches(*UsingDecl, Finder, Builder); 1504 return false; 1505} 1506 1507/// \brief Matches the Decl of a DeclStmt which has a single declaration. 1508/// 1509/// Given 1510/// \code 1511/// int a, b; 1512/// int c; 1513/// \endcode 1514/// declStmt(hasSingleDecl(anything())) 1515/// matches 'int c;' but not 'int a, b;'. 1516AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) { 1517 if (Node.isSingleDecl()) { 1518 const Decl *FoundDecl = Node.getSingleDecl(); 1519 return InnerMatcher.matches(*FoundDecl, Finder, Builder); 1520 } 1521 return false; 1522} 1523 1524/// \brief Matches a variable declaration that has an initializer expression 1525/// that matches the given matcher. 1526/// 1527/// Example matches x (matcher = varDecl(hasInitializer(callExpr()))) 1528/// \code 1529/// bool y() { return true; } 1530/// bool x = y(); 1531/// \endcode 1532AST_MATCHER_P( 1533 VarDecl, hasInitializer, internal::Matcher<Expr>, 1534 InnerMatcher) { 1535 const Expr *Initializer = Node.getAnyInitializer(); 1536 return (Initializer != NULL && 1537 InnerMatcher.matches(*Initializer, Finder, Builder)); 1538} 1539 1540/// \brief Checks that a call expression or a constructor call expression has 1541/// a specific number of arguments (including absent default arguments). 1542/// 1543/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2))) 1544/// \code 1545/// void f(int x, int y); 1546/// f(0, 0); 1547/// \endcode 1548AST_POLYMORPHIC_MATCHER_P(argumentCountIs, unsigned, N) { 1549 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 1550 llvm::is_base_of<CXXConstructExpr, 1551 NodeType>::value), 1552 instantiated_with_wrong_types); 1553 return Node.getNumArgs() == N; 1554} 1555 1556/// \brief Matches the n'th argument of a call expression or a constructor 1557/// call expression. 1558/// 1559/// Example matches y in x(y) 1560/// (matcher = callExpr(hasArgument(0, declRefExpr()))) 1561/// \code 1562/// void x(int) { int y; x(y); } 1563/// \endcode 1564AST_POLYMORPHIC_MATCHER_P2( 1565 hasArgument, unsigned, N, internal::Matcher<Expr>, InnerMatcher) { 1566 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 1567 llvm::is_base_of<CXXConstructExpr, 1568 NodeType>::value), 1569 instantiated_with_wrong_types); 1570 return (N < Node.getNumArgs() && 1571 InnerMatcher.matches( 1572 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder)); 1573} 1574 1575/// \brief Matches declaration statements that contain a specific number of 1576/// declarations. 1577/// 1578/// Example: Given 1579/// \code 1580/// int a, b; 1581/// int c; 1582/// int d = 2, e; 1583/// \endcode 1584/// declCountIs(2) 1585/// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'. 1586AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) { 1587 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N; 1588} 1589 1590/// \brief Matches the n'th declaration of a declaration statement. 1591/// 1592/// Note that this does not work for global declarations because the AST 1593/// breaks up multiple-declaration DeclStmt's into multiple single-declaration 1594/// DeclStmt's. 1595/// Example: Given non-global declarations 1596/// \code 1597/// int a, b = 0; 1598/// int c; 1599/// int d = 2, e; 1600/// \endcode 1601/// declStmt(containsDeclaration( 1602/// 0, varDecl(hasInitializer(anything())))) 1603/// matches only 'int d = 2, e;', and 1604/// declStmt(containsDeclaration(1, varDecl())) 1605/// \code 1606/// matches 'int a, b = 0' as well as 'int d = 2, e;' 1607/// but 'int c;' is not matched. 1608/// \endcode 1609AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N, 1610 internal::Matcher<Decl>, InnerMatcher) { 1611 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end()); 1612 if (N >= NumDecls) 1613 return false; 1614 DeclStmt::const_decl_iterator Iterator = Node.decl_begin(); 1615 std::advance(Iterator, N); 1616 return InnerMatcher.matches(**Iterator, Finder, Builder); 1617} 1618 1619/// \brief Matches a constructor initializer. 1620/// 1621/// Given 1622/// \code 1623/// struct Foo { 1624/// Foo() : foo_(1) { } 1625/// int foo_; 1626/// }; 1627/// \endcode 1628/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything())))) 1629/// record matches Foo, hasAnyConstructorInitializer matches foo_(1) 1630AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer, 1631 internal::Matcher<CXXCtorInitializer>, InnerMatcher) { 1632 for (CXXConstructorDecl::init_const_iterator I = Node.init_begin(); 1633 I != Node.init_end(); ++I) { 1634 if (InnerMatcher.matches(**I, Finder, Builder)) { 1635 return true; 1636 } 1637 } 1638 return false; 1639} 1640 1641/// \brief Matches the field declaration of a constructor initializer. 1642/// 1643/// Given 1644/// \code 1645/// struct Foo { 1646/// Foo() : foo_(1) { } 1647/// int foo_; 1648/// }; 1649/// \endcode 1650/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer( 1651/// forField(hasName("foo_")))))) 1652/// matches Foo 1653/// with forField matching foo_ 1654AST_MATCHER_P(CXXCtorInitializer, forField, 1655 internal::Matcher<FieldDecl>, InnerMatcher) { 1656 const FieldDecl *NodeAsDecl = Node.getMember(); 1657 return (NodeAsDecl != NULL && 1658 InnerMatcher.matches(*NodeAsDecl, Finder, Builder)); 1659} 1660 1661/// \brief Matches the initializer expression of a constructor initializer. 1662/// 1663/// Given 1664/// \code 1665/// struct Foo { 1666/// Foo() : foo_(1) { } 1667/// int foo_; 1668/// }; 1669/// \endcode 1670/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer( 1671/// withInitializer(integerLiteral(equals(1))))))) 1672/// matches Foo 1673/// with withInitializer matching (1) 1674AST_MATCHER_P(CXXCtorInitializer, withInitializer, 1675 internal::Matcher<Expr>, InnerMatcher) { 1676 const Expr* NodeAsExpr = Node.getInit(); 1677 return (NodeAsExpr != NULL && 1678 InnerMatcher.matches(*NodeAsExpr, Finder, Builder)); 1679} 1680 1681/// \brief Matches a contructor initializer if it is explicitly written in 1682/// code (as opposed to implicitly added by the compiler). 1683/// 1684/// Given 1685/// \code 1686/// struct Foo { 1687/// Foo() { } 1688/// Foo(int) : foo_("A") { } 1689/// string foo_; 1690/// }; 1691/// \endcode 1692/// constructorDecl(hasAnyConstructorInitializer(isWritten())) 1693/// will match Foo(int), but not Foo() 1694AST_MATCHER(CXXCtorInitializer, isWritten) { 1695 return Node.isWritten(); 1696} 1697 1698/// \brief Matches a constructor declaration that has been implicitly added 1699/// by the compiler (eg. implicit default/copy constructors). 1700AST_MATCHER(CXXConstructorDecl, isImplicit) { 1701 return Node.isImplicit(); 1702} 1703 1704/// \brief Matches any argument of a call expression or a constructor call 1705/// expression. 1706/// 1707/// Given 1708/// \code 1709/// void x(int, int, int) { int y; x(1, y, 42); } 1710/// \endcode 1711/// callExpr(hasAnyArgument(declRefExpr())) 1712/// matches x(1, y, 42) 1713/// with hasAnyArgument(...) 1714/// matching y 1715AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, internal::Matcher<Expr>, 1716 InnerMatcher) { 1717 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 1718 llvm::is_base_of<CXXConstructExpr, 1719 NodeType>::value), 1720 instantiated_with_wrong_types); 1721 for (unsigned I = 0; I < Node.getNumArgs(); ++I) { 1722 if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(), 1723 Finder, Builder)) { 1724 return true; 1725 } 1726 } 1727 return false; 1728} 1729 1730/// \brief Matches the n'th parameter of a function declaration. 1731/// 1732/// Given 1733/// \code 1734/// class X { void f(int x) {} }; 1735/// \endcode 1736/// methodDecl(hasParameter(0, hasType(varDecl()))) 1737/// matches f(int x) {} 1738/// with hasParameter(...) 1739/// matching int x 1740AST_MATCHER_P2(FunctionDecl, hasParameter, 1741 unsigned, N, internal::Matcher<ParmVarDecl>, 1742 InnerMatcher) { 1743 return (N < Node.getNumParams() && 1744 InnerMatcher.matches( 1745 *Node.getParamDecl(N), Finder, Builder)); 1746} 1747 1748/// \brief Matches any parameter of a function declaration. 1749/// 1750/// Does not match the 'this' parameter of a method. 1751/// 1752/// Given 1753/// \code 1754/// class X { void f(int x, int y, int z) {} }; 1755/// \endcode 1756/// methodDecl(hasAnyParameter(hasName("y"))) 1757/// matches f(int x, int y, int z) {} 1758/// with hasAnyParameter(...) 1759/// matching int y 1760AST_MATCHER_P(FunctionDecl, hasAnyParameter, 1761 internal::Matcher<ParmVarDecl>, InnerMatcher) { 1762 for (unsigned I = 0; I < Node.getNumParams(); ++I) { 1763 if (InnerMatcher.matches(*Node.getParamDecl(I), Finder, Builder)) { 1764 return true; 1765 } 1766 } 1767 return false; 1768} 1769 1770/// \brief Matches the return type of a function declaration. 1771/// 1772/// Given: 1773/// \code 1774/// class X { int f() { return 1; } }; 1775/// \endcode 1776/// methodDecl(returns(asString("int"))) 1777/// matches int f() { return 1; } 1778AST_MATCHER_P(FunctionDecl, returns, 1779 internal::Matcher<QualType>, InnerMatcher) { 1780 return InnerMatcher.matches(Node.getResultType(), Finder, Builder); 1781} 1782 1783/// \brief Matches extern "C" function declarations. 1784/// 1785/// Given: 1786/// \code 1787/// extern "C" void f() {} 1788/// extern "C" { void g() {} } 1789/// void h() {} 1790/// \endcode 1791/// functionDecl(isExternC()) 1792/// matches the declaration of f and g, but not the declaration h 1793AST_MATCHER(FunctionDecl, isExternC) { 1794 return Node.isExternC(); 1795} 1796 1797/// \brief Matches the condition expression of an if statement, for loop, 1798/// or conditional operator. 1799/// 1800/// Example matches true (matcher = hasCondition(boolLiteral(equals(true)))) 1801/// \code 1802/// if (true) {} 1803/// \endcode 1804AST_POLYMORPHIC_MATCHER_P(hasCondition, internal::Matcher<Expr>, 1805 InnerMatcher) { 1806 TOOLING_COMPILE_ASSERT( 1807 (llvm::is_base_of<IfStmt, NodeType>::value) || 1808 (llvm::is_base_of<ForStmt, NodeType>::value) || 1809 (llvm::is_base_of<WhileStmt, NodeType>::value) || 1810 (llvm::is_base_of<DoStmt, NodeType>::value) || 1811 (llvm::is_base_of<ConditionalOperator, NodeType>::value), 1812 has_condition_requires_if_statement_conditional_operator_or_loop); 1813 const Expr *const Condition = Node.getCond(); 1814 return (Condition != NULL && 1815 InnerMatcher.matches(*Condition, Finder, Builder)); 1816} 1817 1818/// \brief Matches the condition variable statement in an if statement. 1819/// 1820/// Given 1821/// \code 1822/// if (A* a = GetAPointer()) {} 1823/// \endcode 1824/// hasConditionVariableStatment(...) 1825/// matches 'A* a = GetAPointer()'. 1826AST_MATCHER_P(IfStmt, hasConditionVariableStatement, 1827 internal::Matcher<DeclStmt>, InnerMatcher) { 1828 const DeclStmt* const DeclarationStatement = 1829 Node.getConditionVariableDeclStmt(); 1830 return DeclarationStatement != NULL && 1831 InnerMatcher.matches(*DeclarationStatement, Finder, Builder); 1832} 1833 1834/// \brief Matches the index expression of an array subscript expression. 1835/// 1836/// Given 1837/// \code 1838/// int i[5]; 1839/// void f() { i[1] = 42; } 1840/// \endcode 1841/// arraySubscriptExpression(hasIndex(integerLiteral())) 1842/// matches \c i[1] with the \c integerLiteral() matching \c 1 1843AST_MATCHER_P(ArraySubscriptExpr, hasIndex, 1844 internal::Matcher<Expr>, InnerMatcher) { 1845 if (const Expr* Expression = Node.getIdx()) 1846 return InnerMatcher.matches(*Expression, Finder, Builder); 1847 return false; 1848} 1849 1850/// \brief Matches the base expression of an array subscript expression. 1851/// 1852/// Given 1853/// \code 1854/// int i[5]; 1855/// void f() { i[1] = 42; } 1856/// \endcode 1857/// arraySubscriptExpression(hasBase(implicitCastExpr( 1858/// hasSourceExpression(declRefExpr())))) 1859/// matches \c i[1] with the \c declRefExpr() matching \c i 1860AST_MATCHER_P(ArraySubscriptExpr, hasBase, 1861 internal::Matcher<Expr>, InnerMatcher) { 1862 if (const Expr* Expression = Node.getBase()) 1863 return InnerMatcher.matches(*Expression, Finder, Builder); 1864 return false; 1865} 1866 1867/// \brief Matches a 'for', 'while', or 'do while' statement that has 1868/// a given body. 1869/// 1870/// Given 1871/// \code 1872/// for (;;) {} 1873/// \endcode 1874/// hasBody(compoundStmt()) 1875/// matches 'for (;;) {}' 1876/// with compoundStmt() 1877/// matching '{}' 1878AST_POLYMORPHIC_MATCHER_P(hasBody, internal::Matcher<Stmt>, 1879 InnerMatcher) { 1880 TOOLING_COMPILE_ASSERT( 1881 (llvm::is_base_of<DoStmt, NodeType>::value) || 1882 (llvm::is_base_of<ForStmt, NodeType>::value) || 1883 (llvm::is_base_of<WhileStmt, NodeType>::value), 1884 has_body_requires_for_while_or_do_statement); 1885 const Stmt *const Statement = Node.getBody(); 1886 return (Statement != NULL && 1887 InnerMatcher.matches(*Statement, Finder, Builder)); 1888} 1889 1890/// \brief Matches compound statements where at least one substatement matches 1891/// a given matcher. 1892/// 1893/// Given 1894/// \code 1895/// { {}; 1+2; } 1896/// \endcode 1897/// hasAnySubstatement(compoundStmt()) 1898/// matches '{ {}; 1+2; }' 1899/// with compoundStmt() 1900/// matching '{}' 1901AST_MATCHER_P(CompoundStmt, hasAnySubstatement, 1902 internal::Matcher<Stmt>, InnerMatcher) { 1903 for (CompoundStmt::const_body_iterator It = Node.body_begin(); 1904 It != Node.body_end(); 1905 ++It) { 1906 if (InnerMatcher.matches(**It, Finder, Builder)) return true; 1907 } 1908 return false; 1909} 1910 1911/// \brief Checks that a compound statement contains a specific number of 1912/// child statements. 1913/// 1914/// Example: Given 1915/// \code 1916/// { for (;;) {} } 1917/// \endcode 1918/// compoundStmt(statementCountIs(0))) 1919/// matches '{}' 1920/// but does not match the outer compound statement. 1921AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) { 1922 return Node.size() == N; 1923} 1924 1925/// \brief Matches literals that are equal to the given value. 1926/// 1927/// Example matches true (matcher = boolLiteral(equals(true))) 1928/// \code 1929/// true 1930/// \endcode 1931/// 1932/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>, 1933/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral> 1934template <typename ValueT> 1935internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT> 1936equals(const ValueT &Value) { 1937 return internal::PolymorphicMatcherWithParam1< 1938 internal::ValueEqualsMatcher, 1939 ValueT>(Value); 1940} 1941 1942/// \brief Matches the operator Name of operator expressions (binary or 1943/// unary). 1944/// 1945/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||"))) 1946/// \code 1947/// !(a || b) 1948/// \endcode 1949AST_POLYMORPHIC_MATCHER_P(hasOperatorName, std::string, Name) { 1950 TOOLING_COMPILE_ASSERT( 1951 (llvm::is_base_of<BinaryOperator, NodeType>::value) || 1952 (llvm::is_base_of<UnaryOperator, NodeType>::value), 1953 has_condition_requires_if_statement_or_conditional_operator); 1954 return Name == Node.getOpcodeStr(Node.getOpcode()); 1955} 1956 1957/// \brief Matches the left hand side of binary operator expressions. 1958/// 1959/// Example matches a (matcher = binaryOperator(hasLHS())) 1960/// \code 1961/// a || b 1962/// \endcode 1963AST_MATCHER_P(BinaryOperator, hasLHS, 1964 internal::Matcher<Expr>, InnerMatcher) { 1965 Expr *LeftHandSide = Node.getLHS(); 1966 return (LeftHandSide != NULL && 1967 InnerMatcher.matches(*LeftHandSide, Finder, Builder)); 1968} 1969 1970/// \brief Matches the right hand side of binary operator expressions. 1971/// 1972/// Example matches b (matcher = binaryOperator(hasRHS())) 1973/// \code 1974/// a || b 1975/// \endcode 1976AST_MATCHER_P(BinaryOperator, hasRHS, 1977 internal::Matcher<Expr>, InnerMatcher) { 1978 Expr *RightHandSide = Node.getRHS(); 1979 return (RightHandSide != NULL && 1980 InnerMatcher.matches(*RightHandSide, Finder, Builder)); 1981} 1982 1983/// \brief Matches if either the left hand side or the right hand side of a 1984/// binary operator matches. 1985inline internal::Matcher<BinaryOperator> hasEitherOperand( 1986 const internal::Matcher<Expr> &InnerMatcher) { 1987 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)); 1988} 1989 1990/// \brief Matches if the operand of a unary operator matches. 1991/// 1992/// Example matches true (matcher = hasOperand(boolLiteral(equals(true)))) 1993/// \code 1994/// !true 1995/// \endcode 1996AST_MATCHER_P(UnaryOperator, hasUnaryOperand, 1997 internal::Matcher<Expr>, InnerMatcher) { 1998 const Expr * const Operand = Node.getSubExpr(); 1999 return (Operand != NULL && 2000 InnerMatcher.matches(*Operand, Finder, Builder)); 2001} 2002 2003/// \brief Matches if the cast's source expression matches the given matcher. 2004/// 2005/// Example: matches "a string" (matcher = 2006/// hasSourceExpression(constructExpr())) 2007/// \code 2008/// class URL { URL(string); }; 2009/// URL url = "a string"; 2010AST_MATCHER_P(CastExpr, hasSourceExpression, 2011 internal::Matcher<Expr>, InnerMatcher) { 2012 const Expr* const SubExpression = Node.getSubExpr(); 2013 return (SubExpression != NULL && 2014 InnerMatcher.matches(*SubExpression, Finder, Builder)); 2015} 2016 2017/// \brief Matches casts whose destination type matches a given matcher. 2018/// 2019/// (Note: Clang's AST refers to other conversions as "casts" too, and calls 2020/// actual casts "explicit" casts.) 2021AST_MATCHER_P(ExplicitCastExpr, hasDestinationType, 2022 internal::Matcher<QualType>, InnerMatcher) { 2023 const QualType NodeType = Node.getTypeAsWritten(); 2024 return InnerMatcher.matches(NodeType, Finder, Builder); 2025} 2026 2027/// \brief Matches implicit casts whose destination type matches a given 2028/// matcher. 2029/// 2030/// FIXME: Unit test this matcher 2031AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType, 2032 internal::Matcher<QualType>, InnerMatcher) { 2033 return InnerMatcher.matches(Node.getType(), Finder, Builder); 2034} 2035 2036/// \brief Matches the true branch expression of a conditional operator. 2037/// 2038/// Example matches a 2039/// \code 2040/// condition ? a : b 2041/// \endcode 2042AST_MATCHER_P(ConditionalOperator, hasTrueExpression, 2043 internal::Matcher<Expr>, InnerMatcher) { 2044 Expr *Expression = Node.getTrueExpr(); 2045 return (Expression != NULL && 2046 InnerMatcher.matches(*Expression, Finder, Builder)); 2047} 2048 2049/// \brief Matches the false branch expression of a conditional operator. 2050/// 2051/// Example matches b 2052/// \code 2053/// condition ? a : b 2054/// \endcode 2055AST_MATCHER_P(ConditionalOperator, hasFalseExpression, 2056 internal::Matcher<Expr>, InnerMatcher) { 2057 Expr *Expression = Node.getFalseExpr(); 2058 return (Expression != NULL && 2059 InnerMatcher.matches(*Expression, Finder, Builder)); 2060} 2061 2062/// \brief Matches if a declaration has a body attached. 2063/// 2064/// Example matches A, va, fa 2065/// \code 2066/// class A {}; 2067/// class B; // Doesn't match, as it has no body. 2068/// int va; 2069/// extern int vb; // Doesn't match, as it doesn't define the variable. 2070/// void fa() {} 2071/// void fb(); // Doesn't match, as it has no body. 2072/// \endcode 2073/// 2074/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl> 2075inline internal::PolymorphicMatcherWithParam0<internal::IsDefinitionMatcher> 2076isDefinition() { 2077 return internal::PolymorphicMatcherWithParam0< 2078 internal::IsDefinitionMatcher>(); 2079} 2080 2081/// \brief Matches the class declaration that the given method declaration 2082/// belongs to. 2083/// 2084/// FIXME: Generalize this for other kinds of declarations. 2085/// FIXME: What other kind of declarations would we need to generalize 2086/// this to? 2087/// 2088/// Example matches A() in the last line 2089/// (matcher = constructExpr(hasDeclaration(methodDecl( 2090/// ofClass(hasName("A")))))) 2091/// \code 2092/// class A { 2093/// public: 2094/// A(); 2095/// }; 2096/// A a = A(); 2097/// \endcode 2098AST_MATCHER_P(CXXMethodDecl, ofClass, 2099 internal::Matcher<CXXRecordDecl>, InnerMatcher) { 2100 const CXXRecordDecl *Parent = Node.getParent(); 2101 return (Parent != NULL && 2102 InnerMatcher.matches(*Parent, Finder, Builder)); 2103} 2104 2105/// \brief Matches member expressions that are called with '->' as opposed 2106/// to '.'. 2107/// 2108/// Member calls on the implicit this pointer match as called with '->'. 2109/// 2110/// Given 2111/// \code 2112/// class Y { 2113/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 2114/// int a; 2115/// static int b; 2116/// }; 2117/// \endcode 2118/// memberExpr(isArrow()) 2119/// matches this->x, x, y.x, a, this->b 2120inline internal::Matcher<MemberExpr> isArrow() { 2121 return makeMatcher(new internal::IsArrowMatcher()); 2122} 2123 2124/// \brief Matches QualType nodes that are of integer type. 2125/// 2126/// Given 2127/// \code 2128/// void a(int); 2129/// void b(long); 2130/// void c(double); 2131/// \endcode 2132/// functionDecl(hasAnyParameter(hasType(isInteger()))) 2133/// matches "a(int)", "b(long)", but not "c(double)". 2134AST_MATCHER(QualType, isInteger) { 2135 return Node->isIntegerType(); 2136} 2137 2138/// \brief Matches QualType nodes that are const-qualified, i.e., that 2139/// include "top-level" const. 2140/// 2141/// Given 2142/// \code 2143/// void a(int); 2144/// void b(int const); 2145/// void c(const int); 2146/// void d(const int*); 2147/// void e(int const) {}; 2148/// \endcode 2149/// functionDecl(hasAnyParameter(hasType(isConstQualified()))) 2150/// matches "void b(int const)", "void c(const int)" and 2151/// "void e(int const) {}". It does not match d as there 2152/// is no top-level const on the parameter type "const int *". 2153inline internal::Matcher<QualType> isConstQualified() { 2154 return makeMatcher(new internal::IsConstQualifiedMatcher()); 2155} 2156 2157/// \brief Matches a member expression where the member is matched by a 2158/// given matcher. 2159/// 2160/// Given 2161/// \code 2162/// struct { int first, second; } first, second; 2163/// int i(second.first); 2164/// int j(first.second); 2165/// \endcode 2166/// memberExpr(member(hasName("first"))) 2167/// matches second.first 2168/// but not first.second (because the member name there is "second"). 2169AST_MATCHER_P(MemberExpr, member, 2170 internal::Matcher<ValueDecl>, InnerMatcher) { 2171 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder); 2172} 2173 2174/// \brief Matches a member expression where the object expression is 2175/// matched by a given matcher. 2176/// 2177/// Given 2178/// \code 2179/// struct X { int m; }; 2180/// void f(X x) { x.m; m; } 2181/// \endcode 2182/// memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X"))))))) 2183/// matches "x.m" and "m" 2184/// with hasObjectExpression(...) 2185/// matching "x" and the implicit object expression of "m" which has type X*. 2186AST_MATCHER_P(MemberExpr, hasObjectExpression, 2187 internal::Matcher<Expr>, InnerMatcher) { 2188 return InnerMatcher.matches(*Node.getBase(), Finder, Builder); 2189} 2190 2191/// \brief Matches any using shadow declaration. 2192/// 2193/// Given 2194/// \code 2195/// namespace X { void b(); } 2196/// using X::b; 2197/// \endcode 2198/// usingDecl(hasAnyUsingShadowDecl(hasName("b")))) 2199/// matches \code using X::b \endcode 2200AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl, 2201 internal::Matcher<UsingShadowDecl>, InnerMatcher) { 2202 for (UsingDecl::shadow_iterator II = Node.shadow_begin(); 2203 II != Node.shadow_end(); ++II) { 2204 if (InnerMatcher.matches(**II, Finder, Builder)) 2205 return true; 2206 } 2207 return false; 2208} 2209 2210/// \brief Matches a using shadow declaration where the target declaration is 2211/// matched by the given matcher. 2212/// 2213/// Given 2214/// \code 2215/// namespace X { int a; void b(); } 2216/// using X::a; 2217/// using X::b; 2218/// \endcode 2219/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl()))) 2220/// matches \code using X::b \endcode 2221/// but not \code using X::a \endcode 2222AST_MATCHER_P(UsingShadowDecl, hasTargetDecl, 2223 internal::Matcher<NamedDecl>, InnerMatcher) { 2224 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder); 2225} 2226 2227/// \brief Matches template instantiations of function, class, or static 2228/// member variable template instantiations. 2229/// 2230/// Given 2231/// \code 2232/// template <typename T> class X {}; class A {}; X<A> x; 2233/// \endcode 2234/// or 2235/// \code 2236/// template <typename T> class X {}; class A {}; template class X<A>; 2237/// \endcode 2238/// recordDecl(hasName("::X"), isTemplateInstantiation()) 2239/// matches the template instantiation of X<A>. 2240/// 2241/// But given 2242/// \code 2243/// template <typename T> class X {}; class A {}; 2244/// template <> class X<A> {}; X<A> x; 2245/// \endcode 2246/// recordDecl(hasName("::X"), isTemplateInstantiation()) 2247/// does not match, as X<A> is an explicit template specialization. 2248/// 2249/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> 2250inline internal::PolymorphicMatcherWithParam0< 2251 internal::IsTemplateInstantiationMatcher> 2252isTemplateInstantiation() { 2253 return internal::PolymorphicMatcherWithParam0< 2254 internal::IsTemplateInstantiationMatcher>(); 2255} 2256 2257/// \brief Matches explicit template specializations of function, class, or 2258/// static member variable template instantiations. 2259/// 2260/// Given 2261/// \code 2262/// template<typename T> void A(T t) { } 2263/// template<> void A(int N) { } 2264/// \endcode 2265/// functionDecl(isExplicitTemplateSpecialization()) 2266/// matches the specialization A<int>(). 2267/// 2268/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> 2269inline internal::PolymorphicMatcherWithParam0< 2270 internal::IsExplicitTemplateSpecializationMatcher> 2271isExplicitTemplateSpecialization() { 2272 return internal::PolymorphicMatcherWithParam0< 2273 internal::IsExplicitTemplateSpecializationMatcher>(); 2274} 2275 2276} // end namespace ast_matchers 2277} // end namespace clang 2278 2279#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H 2280