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