ASTMatchers.h revision 06963013d1972f1f7a58875bb40976b60522700b
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::BoundNodesTreeBuilder; 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<Stmt> StatementMatcher; 112typedef internal::Matcher<QualType> TypeMatcher; 113typedef internal::Matcher<TypeLoc> TypeLocMatcher; 114typedef internal::Matcher<NestedNameSpecifier> NestedNameSpecifierMatcher; 115typedef internal::Matcher<NestedNameSpecifierLoc> NestedNameSpecifierLocMatcher; 116/// @} 117 118/// \brief Matches any node. 119/// 120/// Useful when another matcher requires a child matcher, but there's no 121/// additional constraint. This will often be used with an explicit conversion 122/// to an \c internal::Matcher<> type such as \c TypeMatcher. 123/// 124/// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g., 125/// \code 126/// "int* p" and "void f()" in 127/// int* p; 128/// void f(); 129/// \endcode 130/// 131/// Usable as: Any Matcher 132inline internal::PolymorphicMatcherWithParam0<internal::TrueMatcher> 133anything() { 134 return internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>(); 135} 136 137/// \brief Matches declarations. 138/// 139/// Examples matches \c X, \c C, and the friend declaration inside \c C; 140/// \code 141/// void X(); 142/// class C { 143/// friend X; 144/// }; 145/// \endcode 146const internal::VariadicAllOfMatcher<Decl> decl; 147 148/// \brief Matches a declaration of anything that could have a name. 149/// 150/// Example matches \c X, \c S, the anonymous union type, \c i, and \c U; 151/// \code 152/// typedef int X; 153/// struct S { 154/// union { 155/// int i; 156/// } U; 157/// }; 158/// \endcode 159const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl; 160 161/// \brief Matches a declaration of a namespace. 162/// 163/// Given 164/// \code 165/// namespace {} 166/// namespace test {} 167/// \endcode 168/// namespaceDecl() 169/// matches "namespace {}" and "namespace test {}" 170const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl; 171 172/// \brief Matches C++ class declarations. 173/// 174/// Example matches \c X, \c Z 175/// \code 176/// class X; 177/// template<class T> class Z {}; 178/// \endcode 179const internal::VariadicDynCastAllOfMatcher< 180 Decl, 181 CXXRecordDecl> recordDecl; 182 183/// \brief Matches C++ class template declarations. 184/// 185/// Example matches \c Z 186/// \code 187/// template<class T> class Z {}; 188/// \endcode 189const internal::VariadicDynCastAllOfMatcher< 190 Decl, 191 ClassTemplateDecl> classTemplateDecl; 192 193/// \brief Matches C++ class template specializations. 194/// 195/// Given 196/// \code 197/// template<typename T> class A {}; 198/// template<> class A<double> {}; 199/// A<int> a; 200/// \endcode 201/// classTemplateSpecializationDecl() 202/// matches the specializations \c A<int> and \c A<double> 203const internal::VariadicDynCastAllOfMatcher< 204 Decl, 205 ClassTemplateSpecializationDecl> classTemplateSpecializationDecl; 206 207/// \brief Matches declarator declarations (field, variable, function 208/// and non-type template parameter declarations). 209/// 210/// Given 211/// \code 212/// class X { int y; }; 213/// \endcode 214/// declaratorDecl() 215/// matches \c int y. 216const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl> 217 declaratorDecl; 218 219/// \brief Matches parameter variable declarations. 220/// 221/// Given 222/// \code 223/// void f(int x); 224/// \endcode 225/// parmVarDecl() 226/// matches \c int x. 227const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl> parmVarDecl; 228 229/// \brief Matches C++ access specifier declarations. 230/// 231/// Given 232/// \code 233/// class C { 234/// public: 235/// int a; 236/// }; 237/// \endcode 238/// accessSpecDecl() 239/// matches 'public:' 240const internal::VariadicDynCastAllOfMatcher< 241 Decl, 242 AccessSpecDecl> accessSpecDecl; 243 244/// \brief Matches constructor initializers. 245/// 246/// Examples matches \c i(42). 247/// \code 248/// class C { 249/// C() : i(42) {} 250/// int i; 251/// }; 252/// \endcode 253const internal::VariadicAllOfMatcher<CXXCtorInitializer> ctorInitializer; 254 255/// \brief Matches public C++ declarations. 256/// 257/// Given 258/// \code 259/// class C { 260/// public: int a; 261/// protected: int b; 262/// private: int c; 263/// }; 264/// \endcode 265/// fieldDecl(isPublic()) 266/// matches 'int a;' 267AST_MATCHER(Decl, isPublic) { 268 return Node.getAccess() == AS_public; 269} 270 271/// \brief Matches protected C++ declarations. 272/// 273/// Given 274/// \code 275/// class C { 276/// public: int a; 277/// protected: int b; 278/// private: int c; 279/// }; 280/// \endcode 281/// fieldDecl(isProtected()) 282/// matches 'int b;' 283AST_MATCHER(Decl, isProtected) { 284 return Node.getAccess() == AS_protected; 285} 286 287/// \brief Matches private C++ declarations. 288/// 289/// Given 290/// \code 291/// class C { 292/// public: int a; 293/// protected: int b; 294/// private: int c; 295/// }; 296/// \endcode 297/// fieldDecl(isPrivate()) 298/// matches 'int c;' 299AST_MATCHER(Decl, isPrivate) { 300 return Node.getAccess() == AS_private; 301} 302 303/// \brief Matches classTemplateSpecializations that have at least one 304/// TemplateArgument matching the given InnerMatcher. 305/// 306/// Given 307/// \code 308/// template<typename T> class A {}; 309/// template<> class A<double> {}; 310/// A<int> a; 311/// \endcode 312/// classTemplateSpecializationDecl(hasAnyTemplateArgument( 313/// refersToType(asString("int")))) 314/// matches the specialization \c A<int> 315AST_MATCHER_P(ClassTemplateSpecializationDecl, hasAnyTemplateArgument, 316 internal::Matcher<TemplateArgument>, InnerMatcher) { 317 llvm::ArrayRef<TemplateArgument> List = Node.getTemplateArgs().asArray(); 318 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder, 319 Builder); 320} 321 322/// \brief Matches expressions that match InnerMatcher after any implicit casts 323/// are stripped off. 324/// 325/// Parentheses and explicit casts are not discarded. 326/// Given 327/// \code 328/// int arr[5]; 329/// int a = 0; 330/// char b = 0; 331/// const int c = a; 332/// int *d = arr; 333/// long e = (long) 0l; 334/// \endcode 335/// The matchers 336/// \code 337/// varDecl(hasInitializer(ignoringImpCasts(integerLiteral()))) 338/// varDecl(hasInitializer(ignoringImpCasts(declRefExpr()))) 339/// \endcode 340/// would match the declarations for a, b, c, and d, but not e. 341/// While 342/// \code 343/// varDecl(hasInitializer(integerLiteral())) 344/// varDecl(hasInitializer(declRefExpr())) 345/// \endcode 346/// only match the declarations for b, c, and d. 347AST_MATCHER_P(Expr, ignoringImpCasts, 348 internal::Matcher<Expr>, InnerMatcher) { 349 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder); 350} 351 352/// \brief Matches expressions that match InnerMatcher after parentheses and 353/// casts are stripped off. 354/// 355/// Implicit and non-C Style casts are also discarded. 356/// Given 357/// \code 358/// int a = 0; 359/// char b = (0); 360/// void* c = reinterpret_cast<char*>(0); 361/// char d = char(0); 362/// \endcode 363/// The matcher 364/// varDecl(hasInitializer(ignoringParenCasts(integerLiteral()))) 365/// would match the declarations for a, b, c, and d. 366/// while 367/// varDecl(hasInitializer(integerLiteral())) 368/// only match the declaration for a. 369AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) { 370 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder); 371} 372 373/// \brief Matches expressions that match InnerMatcher after implicit casts and 374/// parentheses are stripped off. 375/// 376/// Explicit casts are not discarded. 377/// Given 378/// \code 379/// int arr[5]; 380/// int a = 0; 381/// char b = (0); 382/// const int c = a; 383/// int *d = (arr); 384/// long e = ((long) 0l); 385/// \endcode 386/// The matchers 387/// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral()))) 388/// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr()))) 389/// would match the declarations for a, b, c, and d, but not e. 390/// while 391/// varDecl(hasInitializer(integerLiteral())) 392/// varDecl(hasInitializer(declRefExpr())) 393/// would only match the declaration for a. 394AST_MATCHER_P(Expr, ignoringParenImpCasts, 395 internal::Matcher<Expr>, InnerMatcher) { 396 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder); 397} 398 399/// \brief Matches classTemplateSpecializations where the n'th TemplateArgument 400/// matches the given InnerMatcher. 401/// 402/// Given 403/// \code 404/// template<typename T, typename U> class A {}; 405/// A<bool, int> b; 406/// A<int, bool> c; 407/// \endcode 408/// classTemplateSpecializationDecl(hasTemplateArgument( 409/// 1, refersToType(asString("int")))) 410/// matches the specialization \c A<bool, int> 411AST_MATCHER_P2(ClassTemplateSpecializationDecl, hasTemplateArgument, 412 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) { 413 const TemplateArgumentList &List = Node.getTemplateArgs(); 414 if (List.size() <= N) 415 return false; 416 return InnerMatcher.matches(List.get(N), Finder, Builder); 417} 418 419/// \brief Matches a TemplateArgument that refers to a certain type. 420/// 421/// Given 422/// \code 423/// struct X {}; 424/// template<typename T> struct A {}; 425/// A<X> a; 426/// \endcode 427/// classTemplateSpecializationDecl(hasAnyTemplateArgument( 428/// refersToType(class(hasName("X"))))) 429/// matches the specialization \c A<X> 430AST_MATCHER_P(TemplateArgument, refersToType, 431 internal::Matcher<QualType>, InnerMatcher) { 432 if (Node.getKind() != TemplateArgument::Type) 433 return false; 434 return InnerMatcher.matches(Node.getAsType(), Finder, Builder); 435} 436 437/// \brief Matches a TemplateArgument that refers to a certain declaration. 438/// 439/// Given 440/// \code 441/// template<typename T> struct A {}; 442/// struct B { B* next; }; 443/// A<&B::next> a; 444/// \endcode 445/// classTemplateSpecializationDecl(hasAnyTemplateArgument( 446/// refersToDeclaration(fieldDecl(hasName("next")))) 447/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching 448/// \c B::next 449AST_MATCHER_P(TemplateArgument, refersToDeclaration, 450 internal::Matcher<Decl>, InnerMatcher) { 451 if (Node.getKind() == TemplateArgument::Declaration) 452 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder); 453 return false; 454} 455 456/// \brief Matches C++ constructor declarations. 457/// 458/// Example matches Foo::Foo() and Foo::Foo(int) 459/// \code 460/// class Foo { 461/// public: 462/// Foo(); 463/// Foo(int); 464/// int DoSomething(); 465/// }; 466/// \endcode 467const internal::VariadicDynCastAllOfMatcher< 468 Decl, 469 CXXConstructorDecl> constructorDecl; 470 471/// \brief Matches explicit C++ destructor declarations. 472/// 473/// Example matches Foo::~Foo() 474/// \code 475/// class Foo { 476/// public: 477/// virtual ~Foo(); 478/// }; 479/// \endcode 480const internal::VariadicDynCastAllOfMatcher< 481 Decl, 482 CXXDestructorDecl> destructorDecl; 483 484/// \brief Matches enum declarations. 485/// 486/// Example matches X 487/// \code 488/// enum X { 489/// A, B, C 490/// }; 491/// \endcode 492const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl; 493 494/// \brief Matches enum constants. 495/// 496/// Example matches A, B, C 497/// \code 498/// enum X { 499/// A, B, C 500/// }; 501/// \endcode 502const internal::VariadicDynCastAllOfMatcher< 503 Decl, 504 EnumConstantDecl> enumConstantDecl; 505 506/// \brief Matches method declarations. 507/// 508/// Example matches y 509/// \code 510/// class X { void y() }; 511/// \endcode 512const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> methodDecl; 513 514/// \brief Matches variable declarations. 515/// 516/// Note: this does not match declarations of member variables, which are 517/// "field" declarations in Clang parlance. 518/// 519/// Example matches a 520/// \code 521/// int a; 522/// \endcode 523const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl; 524 525/// \brief Matches field declarations. 526/// 527/// Given 528/// \code 529/// class X { int m; }; 530/// \endcode 531/// fieldDecl() 532/// matches 'm'. 533const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl; 534 535/// \brief Matches function declarations. 536/// 537/// Example matches f 538/// \code 539/// void f(); 540/// \endcode 541const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl; 542 543/// \brief Matches C++ function template declarations. 544/// 545/// Example matches f 546/// \code 547/// template<class T> void f(T t) {} 548/// \endcode 549const internal::VariadicDynCastAllOfMatcher< 550 Decl, 551 FunctionTemplateDecl> functionTemplateDecl; 552 553/// \brief Matches statements. 554/// 555/// Given 556/// \code 557/// { ++a; } 558/// \endcode 559/// stmt() 560/// matches both the compound statement '{ ++a; }' and '++a'. 561const internal::VariadicAllOfMatcher<Stmt> stmt; 562 563/// \brief Matches declaration statements. 564/// 565/// Given 566/// \code 567/// int a; 568/// \endcode 569/// declStmt() 570/// matches 'int a'. 571const internal::VariadicDynCastAllOfMatcher< 572 Stmt, 573 DeclStmt> declStmt; 574 575/// \brief Matches member expressions. 576/// 577/// Given 578/// \code 579/// class Y { 580/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 581/// int a; static int b; 582/// }; 583/// \endcode 584/// memberExpr() 585/// matches this->x, x, y.x, a, this->b 586const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr; 587 588/// \brief Matches call expressions. 589/// 590/// Example matches x.y() and y() 591/// \code 592/// X x; 593/// x.y(); 594/// y(); 595/// \endcode 596const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr; 597 598/// \brief Matches lambda expressions. 599/// 600/// Example matches [&](){return 5;} 601/// \code 602/// [&](){return 5;} 603/// \endcode 604const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr; 605 606/// \brief Matches member call expressions. 607/// 608/// Example matches x.y() 609/// \code 610/// X x; 611/// x.y(); 612/// \endcode 613const internal::VariadicDynCastAllOfMatcher< 614 Stmt, 615 CXXMemberCallExpr> memberCallExpr; 616 617/// \brief Matches init list expressions. 618/// 619/// Given 620/// \code 621/// int a[] = { 1, 2 }; 622/// struct B { int x, y; }; 623/// B b = { 5, 6 }; 624/// \endcode 625/// initList() 626/// matches "{ 1, 2 }" and "{ 5, 6 }" 627const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr; 628 629/// \brief Matches using declarations. 630/// 631/// Given 632/// \code 633/// namespace X { int x; } 634/// using X::x; 635/// \endcode 636/// usingDecl() 637/// matches \code using X::x \endcode 638const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl; 639 640/// \brief Matches unresolved using value declarations. 641/// 642/// Given 643/// \code 644/// template<typename X> 645/// class C : private X { 646/// using X::x; 647/// }; 648/// \endcode 649/// unresolvedUsingValueDecl() 650/// matches \code using X::x \endcode 651const internal::VariadicDynCastAllOfMatcher< 652 Decl, 653 UnresolvedUsingValueDecl> unresolvedUsingValueDecl; 654 655/// \brief Matches constructor call expressions (including implicit ones). 656/// 657/// Example matches string(ptr, n) and ptr within arguments of f 658/// (matcher = constructExpr()) 659/// \code 660/// void f(const string &a, const string &b); 661/// char *ptr; 662/// int n; 663/// f(string(ptr, n), ptr); 664/// \endcode 665const internal::VariadicDynCastAllOfMatcher< 666 Stmt, 667 CXXConstructExpr> constructExpr; 668 669/// \brief Matches unresolved constructor call expressions. 670/// 671/// Example matches T(t) in return statement of f 672/// (matcher = unresolvedConstructExpr()) 673/// \code 674/// template <typename T> 675/// void f(const T& t) { return T(t); } 676/// \endcode 677const internal::VariadicDynCastAllOfMatcher< 678 Stmt, 679 CXXUnresolvedConstructExpr> unresolvedConstructExpr; 680 681/// \brief Matches implicit and explicit this expressions. 682/// 683/// Example matches the implicit this expression in "return i". 684/// (matcher = thisExpr()) 685/// \code 686/// struct foo { 687/// int i; 688/// int f() { return i; } 689/// }; 690/// \endcode 691const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> thisExpr; 692 693/// \brief Matches nodes where temporaries are created. 694/// 695/// Example matches FunctionTakesString(GetStringByValue()) 696/// (matcher = bindTemporaryExpr()) 697/// \code 698/// FunctionTakesString(GetStringByValue()); 699/// FunctionTakesStringByPointer(GetStringPointer()); 700/// \endcode 701const internal::VariadicDynCastAllOfMatcher< 702 Stmt, 703 CXXBindTemporaryExpr> bindTemporaryExpr; 704 705/// \brief Matches nodes where temporaries are materialized. 706/// 707/// Example: Given 708/// \code 709/// struct T {void func()}; 710/// T f(); 711/// void g(T); 712/// \endcode 713/// materializeTemporaryExpr() matches 'f()' in these statements 714/// \code 715/// T u(f()); 716/// g(f()); 717/// \endcode 718/// but does not match 719/// \code 720/// f(); 721/// f().func(); 722/// \endcode 723const internal::VariadicDynCastAllOfMatcher< 724 Stmt, 725 MaterializeTemporaryExpr> materializeTemporaryExpr; 726 727/// \brief Matches new expressions. 728/// 729/// Given 730/// \code 731/// new X; 732/// \endcode 733/// newExpr() 734/// matches 'new X'. 735const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> newExpr; 736 737/// \brief Matches delete expressions. 738/// 739/// Given 740/// \code 741/// delete X; 742/// \endcode 743/// deleteExpr() 744/// matches 'delete X'. 745const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> deleteExpr; 746 747/// \brief Matches array subscript expressions. 748/// 749/// Given 750/// \code 751/// int i = a[1]; 752/// \endcode 753/// arraySubscriptExpr() 754/// matches "a[1]" 755const internal::VariadicDynCastAllOfMatcher< 756 Stmt, 757 ArraySubscriptExpr> arraySubscriptExpr; 758 759/// \brief Matches the value of a default argument at the call site. 760/// 761/// Example matches the CXXDefaultArgExpr placeholder inserted for the 762/// default value of the second parameter in the call expression f(42) 763/// (matcher = defaultArgExpr()) 764/// \code 765/// void f(int x, int y = 0); 766/// f(42); 767/// \endcode 768const internal::VariadicDynCastAllOfMatcher< 769 Stmt, 770 CXXDefaultArgExpr> defaultArgExpr; 771 772/// \brief Matches overloaded operator calls. 773/// 774/// Note that if an operator isn't overloaded, it won't match. Instead, use 775/// binaryOperator matcher. 776/// Currently it does not match operators such as new delete. 777/// FIXME: figure out why these do not match? 778/// 779/// Example matches both operator<<((o << b), c) and operator<<(o, b) 780/// (matcher = operatorCallExpr()) 781/// \code 782/// ostream &operator<< (ostream &out, int i) { }; 783/// ostream &o; int b = 1, c = 1; 784/// o << b << c; 785/// \endcode 786const internal::VariadicDynCastAllOfMatcher< 787 Stmt, 788 CXXOperatorCallExpr> operatorCallExpr; 789 790/// \brief Matches expressions. 791/// 792/// Example matches x() 793/// \code 794/// void f() { x(); } 795/// \endcode 796const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr; 797 798/// \brief Matches expressions that refer to declarations. 799/// 800/// Example matches x in if (x) 801/// \code 802/// bool x; 803/// if (x) {} 804/// \endcode 805const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr; 806 807/// \brief Matches if statements. 808/// 809/// Example matches 'if (x) {}' 810/// \code 811/// if (x) {} 812/// \endcode 813const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt; 814 815/// \brief Matches for statements. 816/// 817/// Example matches 'for (;;) {}' 818/// \code 819/// for (;;) {} 820/// int i[] = {1, 2, 3}; for (auto a : i); 821/// \endcode 822const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt; 823 824/// \brief Matches range-based for statements. 825/// 826/// forRangeStmt() matches 'for (auto a : i)' 827/// \code 828/// int i[] = {1, 2, 3}; for (auto a : i); 829/// for(int j = 0; j < 5; ++j); 830/// \endcode 831const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt> forRangeStmt; 832 833/// \brief Matches the increment statement of a for loop. 834/// 835/// Example: 836/// forStmt(hasIncrement(unaryOperator(hasOperatorName("++")))) 837/// matches '++x' in 838/// \code 839/// for (x; x < N; ++x) { } 840/// \endcode 841AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>, 842 InnerMatcher) { 843 const Stmt *const Increment = Node.getInc(); 844 return (Increment != NULL && 845 InnerMatcher.matches(*Increment, Finder, Builder)); 846} 847 848/// \brief Matches the initialization statement of a for loop. 849/// 850/// Example: 851/// forStmt(hasLoopInit(declStmt())) 852/// matches 'int x = 0' in 853/// \code 854/// for (int x = 0; x < N; ++x) { } 855/// \endcode 856AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>, 857 InnerMatcher) { 858 const Stmt *const Init = Node.getInit(); 859 return (Init != NULL && InnerMatcher.matches(*Init, Finder, Builder)); 860} 861 862/// \brief Matches while statements. 863/// 864/// Given 865/// \code 866/// while (true) {} 867/// \endcode 868/// whileStmt() 869/// matches 'while (true) {}'. 870const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt; 871 872/// \brief Matches do statements. 873/// 874/// Given 875/// \code 876/// do {} while (true); 877/// \endcode 878/// doStmt() 879/// matches 'do {} while(true)' 880const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt; 881 882/// \brief Matches break statements. 883/// 884/// Given 885/// \code 886/// while (true) { break; } 887/// \endcode 888/// breakStmt() 889/// matches 'break' 890const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt; 891 892/// \brief Matches continue statements. 893/// 894/// Given 895/// \code 896/// while (true) { continue; } 897/// \endcode 898/// continueStmt() 899/// matches 'continue' 900const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt; 901 902/// \brief Matches return statements. 903/// 904/// Given 905/// \code 906/// return 1; 907/// \endcode 908/// returnStmt() 909/// matches 'return 1' 910const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt; 911 912/// \brief Matches goto statements. 913/// 914/// Given 915/// \code 916/// goto FOO; 917/// FOO: bar(); 918/// \endcode 919/// gotoStmt() 920/// matches 'goto FOO' 921const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt; 922 923/// \brief Matches label statements. 924/// 925/// Given 926/// \code 927/// goto FOO; 928/// FOO: bar(); 929/// \endcode 930/// labelStmt() 931/// matches 'FOO:' 932const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt; 933 934/// \brief Matches switch statements. 935/// 936/// Given 937/// \code 938/// switch(a) { case 42: break; default: break; } 939/// \endcode 940/// switchStmt() 941/// matches 'switch(a)'. 942const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt; 943 944/// \brief Matches case and default statements inside switch statements. 945/// 946/// Given 947/// \code 948/// switch(a) { case 42: break; default: break; } 949/// \endcode 950/// switchCase() 951/// matches 'case 42: break;' and 'default: break;'. 952const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase; 953 954/// \brief Matches case statements inside switch statements. 955/// 956/// Given 957/// \code 958/// switch(a) { case 42: break; default: break; } 959/// \endcode 960/// caseStmt() 961/// matches 'case 42: break;'. 962const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt; 963 964/// \brief Matches default statements inside switch statements. 965/// 966/// Given 967/// \code 968/// switch(a) { case 42: break; default: break; } 969/// \endcode 970/// defaultStmt() 971/// matches 'default: break;'. 972const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt> defaultStmt; 973 974/// \brief Matches compound statements. 975/// 976/// Example matches '{}' and '{{}}'in 'for (;;) {{}}' 977/// \code 978/// for (;;) {{}} 979/// \endcode 980const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt; 981 982/// \brief Matches catch statements. 983/// 984/// \code 985/// try {} catch(int i) {} 986/// \endcode 987/// catchStmt() 988/// matches 'catch(int i)' 989const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> catchStmt; 990 991/// \brief Matches try statements. 992/// 993/// \code 994/// try {} catch(int i) {} 995/// \endcode 996/// tryStmt() 997/// matches 'try {}' 998const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> tryStmt; 999 1000/// \brief Matches throw expressions. 1001/// 1002/// \code 1003/// try { throw 5; } catch(int i) {} 1004/// \endcode 1005/// throwExpr() 1006/// matches 'throw 5' 1007const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> throwExpr; 1008 1009/// \brief Matches null statements. 1010/// 1011/// \code 1012/// foo();; 1013/// \endcode 1014/// nullStmt() 1015/// matches the second ';' 1016const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt; 1017 1018/// \brief Matches asm statements. 1019/// 1020/// \code 1021/// int i = 100; 1022/// __asm("mov al, 2"); 1023/// \endcode 1024/// asmStmt() 1025/// matches '__asm("mov al, 2")' 1026const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt; 1027 1028/// \brief Matches bool literals. 1029/// 1030/// Example matches true 1031/// \code 1032/// true 1033/// \endcode 1034const internal::VariadicDynCastAllOfMatcher< 1035 Stmt, 1036 CXXBoolLiteralExpr> boolLiteral; 1037 1038/// \brief Matches string literals (also matches wide string literals). 1039/// 1040/// Example matches "abcd", L"abcd" 1041/// \code 1042/// char *s = "abcd"; wchar_t *ws = L"abcd" 1043/// \endcode 1044const internal::VariadicDynCastAllOfMatcher< 1045 Stmt, 1046 StringLiteral> stringLiteral; 1047 1048/// \brief Matches character literals (also matches wchar_t). 1049/// 1050/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral), 1051/// though. 1052/// 1053/// Example matches 'a', L'a' 1054/// \code 1055/// char ch = 'a'; wchar_t chw = L'a'; 1056/// \endcode 1057const internal::VariadicDynCastAllOfMatcher< 1058 Stmt, 1059 CharacterLiteral> characterLiteral; 1060 1061/// \brief Matches integer literals of all sizes / encodings. 1062/// 1063/// Not matching character-encoded integers such as L'a'. 1064/// 1065/// Example matches 1, 1L, 0x1, 1U 1066const internal::VariadicDynCastAllOfMatcher< 1067 Stmt, 1068 IntegerLiteral> integerLiteral; 1069 1070/// \brief Matches user defined literal operator call. 1071/// 1072/// Example match: "foo"_suffix 1073const internal::VariadicDynCastAllOfMatcher< 1074 Stmt, 1075 UserDefinedLiteral> userDefinedLiteral; 1076 1077/// \brief Matches compound (i.e. non-scalar) literals 1078/// 1079/// Example match: {1}, (1, 2) 1080/// \code 1081/// int array[4] = {1}; vector int myvec = (vector int)(1, 2); 1082/// \endcode 1083const internal::VariadicDynCastAllOfMatcher< 1084 Stmt, 1085 CompoundLiteralExpr> compoundLiteralExpr; 1086 1087/// \brief Matches nullptr literal. 1088const internal::VariadicDynCastAllOfMatcher< 1089 Stmt, 1090 CXXNullPtrLiteralExpr> nullPtrLiteralExpr; 1091 1092/// \brief Matches binary operator expressions. 1093/// 1094/// Example matches a || b 1095/// \code 1096/// !(a || b) 1097/// \endcode 1098const internal::VariadicDynCastAllOfMatcher< 1099 Stmt, 1100 BinaryOperator> binaryOperator; 1101 1102/// \brief Matches unary operator expressions. 1103/// 1104/// Example matches !a 1105/// \code 1106/// !a || b 1107/// \endcode 1108const internal::VariadicDynCastAllOfMatcher< 1109 Stmt, 1110 UnaryOperator> unaryOperator; 1111 1112/// \brief Matches conditional operator expressions. 1113/// 1114/// Example matches a ? b : c 1115/// \code 1116/// (a ? b : c) + 42 1117/// \endcode 1118const internal::VariadicDynCastAllOfMatcher< 1119 Stmt, 1120 ConditionalOperator> conditionalOperator; 1121 1122/// \brief Matches a reinterpret_cast expression. 1123/// 1124/// Either the source expression or the destination type can be matched 1125/// using has(), but hasDestinationType() is more specific and can be 1126/// more readable. 1127/// 1128/// Example matches reinterpret_cast<char*>(&p) in 1129/// \code 1130/// void* p = reinterpret_cast<char*>(&p); 1131/// \endcode 1132const internal::VariadicDynCastAllOfMatcher< 1133 Stmt, 1134 CXXReinterpretCastExpr> reinterpretCastExpr; 1135 1136/// \brief Matches a C++ static_cast expression. 1137/// 1138/// \see hasDestinationType 1139/// \see reinterpretCast 1140/// 1141/// Example: 1142/// staticCastExpr() 1143/// matches 1144/// static_cast<long>(8) 1145/// in 1146/// \code 1147/// long eight(static_cast<long>(8)); 1148/// \endcode 1149const internal::VariadicDynCastAllOfMatcher< 1150 Stmt, 1151 CXXStaticCastExpr> staticCastExpr; 1152 1153/// \brief Matches a dynamic_cast expression. 1154/// 1155/// Example: 1156/// dynamicCastExpr() 1157/// matches 1158/// dynamic_cast<D*>(&b); 1159/// in 1160/// \code 1161/// struct B { virtual ~B() {} }; struct D : B {}; 1162/// B b; 1163/// D* p = dynamic_cast<D*>(&b); 1164/// \endcode 1165const internal::VariadicDynCastAllOfMatcher< 1166 Stmt, 1167 CXXDynamicCastExpr> dynamicCastExpr; 1168 1169/// \brief Matches a const_cast expression. 1170/// 1171/// Example: Matches const_cast<int*>(&r) in 1172/// \code 1173/// int n = 42; 1174/// const int &r(n); 1175/// int* p = const_cast<int*>(&r); 1176/// \endcode 1177const internal::VariadicDynCastAllOfMatcher< 1178 Stmt, 1179 CXXConstCastExpr> constCastExpr; 1180 1181/// \brief Matches a C-style cast expression. 1182/// 1183/// Example: Matches (int*) 2.2f in 1184/// \code 1185/// int i = (int) 2.2f; 1186/// \endcode 1187const internal::VariadicDynCastAllOfMatcher< 1188 Stmt, 1189 CStyleCastExpr> cStyleCastExpr; 1190 1191/// \brief Matches explicit cast expressions. 1192/// 1193/// Matches any cast expression written in user code, whether it be a 1194/// C-style cast, a functional-style cast, or a keyword cast. 1195/// 1196/// Does not match implicit conversions. 1197/// 1198/// Note: the name "explicitCast" is chosen to match Clang's terminology, as 1199/// Clang uses the term "cast" to apply to implicit conversions as well as to 1200/// actual cast expressions. 1201/// 1202/// \see hasDestinationType. 1203/// 1204/// Example: matches all five of the casts in 1205/// \code 1206/// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42))))) 1207/// \endcode 1208/// but does not match the implicit conversion in 1209/// \code 1210/// long ell = 42; 1211/// \endcode 1212const internal::VariadicDynCastAllOfMatcher< 1213 Stmt, 1214 ExplicitCastExpr> explicitCastExpr; 1215 1216/// \brief Matches the implicit cast nodes of Clang's AST. 1217/// 1218/// This matches many different places, including function call return value 1219/// eliding, as well as any type conversions. 1220const internal::VariadicDynCastAllOfMatcher< 1221 Stmt, 1222 ImplicitCastExpr> implicitCastExpr; 1223 1224/// \brief Matches any cast nodes of Clang's AST. 1225/// 1226/// Example: castExpr() matches each of the following: 1227/// \code 1228/// (int) 3; 1229/// const_cast<Expr *>(SubExpr); 1230/// char c = 0; 1231/// \endcode 1232/// but does not match 1233/// \code 1234/// int i = (0); 1235/// int k = 0; 1236/// \endcode 1237const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr; 1238 1239/// \brief Matches functional cast expressions 1240/// 1241/// Example: Matches Foo(bar); 1242/// \code 1243/// Foo f = bar; 1244/// Foo g = (Foo) bar; 1245/// Foo h = Foo(bar); 1246/// \endcode 1247const internal::VariadicDynCastAllOfMatcher< 1248 Stmt, 1249 CXXFunctionalCastExpr> functionalCastExpr; 1250 1251/// \brief Matches \c QualTypes in the clang AST. 1252const internal::VariadicAllOfMatcher<QualType> qualType; 1253 1254/// \brief Matches \c Types in the clang AST. 1255const internal::VariadicAllOfMatcher<Type> type; 1256 1257/// \brief Matches \c TypeLocs in the clang AST. 1258const internal::VariadicAllOfMatcher<TypeLoc> typeLoc; 1259 1260/// \brief Matches if any of the given matchers matches. 1261/// 1262/// Unlike \c anyOf, \c eachOf will generate a match result for each 1263/// matching submatcher. 1264/// 1265/// For example, in: 1266/// \code 1267/// class A { int a; int b; }; 1268/// \endcode 1269/// The matcher: 1270/// \code 1271/// recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")), 1272/// has(fieldDecl(hasName("b")).bind("v")))) 1273/// \endcode 1274/// will generate two results binding "v", the first of which binds 1275/// the field declaration of \c a, the second the field declaration of 1276/// \c b. 1277/// 1278/// Usable as: Any Matcher 1279template <typename M1, typename M2> 1280internal::PolymorphicMatcherWithParam2<internal::EachOfMatcher, M1, M2> 1281eachOf(const M1 &P1, const M2 &P2) { 1282 return internal::PolymorphicMatcherWithParam2<internal::EachOfMatcher, M1, 1283 M2>(P1, P2); 1284} 1285 1286/// \brief Various overloads for the anyOf matcher. 1287/// @{ 1288 1289/// \brief Matches if any of the given matchers matches. 1290/// 1291/// Usable as: Any Matcher 1292template<typename M1, typename M2> 1293internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1, M2> 1294anyOf(const M1 &P1, const M2 &P2) { 1295 return internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 1296 M1, M2 >(P1, P2); 1297} 1298template<typename M1, typename M2, typename M3> 1299internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1, 1300 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2, M3> > 1301anyOf(const M1 &P1, const M2 &P2, const M3 &P3) { 1302 return anyOf(P1, anyOf(P2, P3)); 1303} 1304template<typename M1, typename M2, typename M3, typename M4> 1305internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1, 1306 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2, 1307 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 1308 M3, M4> > > 1309anyOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4) { 1310 return anyOf(P1, anyOf(P2, anyOf(P3, P4))); 1311} 1312template<typename M1, typename M2, typename M3, typename M4, typename M5> 1313internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M1, 1314 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M2, 1315 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, M3, 1316 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 1317 M4, M5> > > > 1318anyOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4, const M5 &P5) { 1319 return anyOf(P1, anyOf(P2, anyOf(P3, anyOf(P4, P5)))); 1320} 1321 1322/// @} 1323 1324/// \brief Various overloads for the allOf matcher. 1325/// @{ 1326 1327/// \brief Matches if all given matchers match. 1328/// 1329/// Usable as: Any Matcher 1330template <typename M1, typename M2> 1331internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M1, M2> 1332allOf(const M1 &P1, const M2 &P2) { 1333 return internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M1, M2>( 1334 P1, P2); 1335} 1336template <typename M1, typename M2, typename M3> 1337internal::PolymorphicMatcherWithParam2< 1338 internal::AllOfMatcher, M1, 1339 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M2, M3> > 1340allOf(const M1 &P1, const M2 &P2, const M3 &P3) { 1341 return allOf(P1, allOf(P2, P3)); 1342} 1343template <typename M1, typename M2, typename M3, typename M4> 1344internal::PolymorphicMatcherWithParam2< 1345 internal::AllOfMatcher, M1, 1346 internal::PolymorphicMatcherWithParam2< 1347 internal::AllOfMatcher, M2, internal::PolymorphicMatcherWithParam2< 1348 internal::AllOfMatcher, M3, M4> > > 1349allOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4) { 1350 return allOf(P1, allOf(P2, P3, P4)); 1351} 1352template <typename M1, typename M2, typename M3, typename M4, typename M5> 1353internal::PolymorphicMatcherWithParam2< 1354 internal::AllOfMatcher, M1, 1355 internal::PolymorphicMatcherWithParam2< 1356 internal::AllOfMatcher, M2, 1357 internal::PolymorphicMatcherWithParam2< 1358 internal::AllOfMatcher, M3, 1359 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, M4, 1360 M5> > > > 1361allOf(const M1 &P1, const M2 &P2, const M3 &P3, const M4 &P4, const M5 &P5) { 1362 return allOf(P1, allOf(P2, P3, P4, P5)); 1363} 1364 1365/// @} 1366 1367/// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL) 1368/// 1369/// Given 1370/// \code 1371/// Foo x = bar; 1372/// int y = sizeof(x) + alignof(x); 1373/// \endcode 1374/// unaryExprOrTypeTraitExpr() 1375/// matches \c sizeof(x) and \c alignof(x) 1376const internal::VariadicDynCastAllOfMatcher< 1377 Stmt, 1378 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr; 1379 1380/// \brief Matches unary expressions that have a specific type of argument. 1381/// 1382/// Given 1383/// \code 1384/// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c); 1385/// \endcode 1386/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int")) 1387/// matches \c sizeof(a) and \c alignof(c) 1388AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType, 1389 internal::Matcher<QualType>, InnerMatcher) { 1390 const QualType ArgumentType = Node.getTypeOfArgument(); 1391 return InnerMatcher.matches(ArgumentType, Finder, Builder); 1392} 1393 1394/// \brief Matches unary expressions of a certain kind. 1395/// 1396/// Given 1397/// \code 1398/// int x; 1399/// int s = sizeof(x) + alignof(x) 1400/// \endcode 1401/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf)) 1402/// matches \c sizeof(x) 1403AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) { 1404 return Node.getKind() == Kind; 1405} 1406 1407/// \brief Same as unaryExprOrTypeTraitExpr, but only matching 1408/// alignof. 1409inline internal::Matcher<Stmt> alignOfExpr( 1410 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) { 1411 return stmt(unaryExprOrTypeTraitExpr(allOf( 1412 ofKind(UETT_AlignOf), InnerMatcher))); 1413} 1414 1415/// \brief Same as unaryExprOrTypeTraitExpr, but only matching 1416/// sizeof. 1417inline internal::Matcher<Stmt> sizeOfExpr( 1418 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) { 1419 return stmt(unaryExprOrTypeTraitExpr( 1420 allOf(ofKind(UETT_SizeOf), InnerMatcher))); 1421} 1422 1423/// \brief Matches NamedDecl nodes that have the specified name. 1424/// 1425/// Supports specifying enclosing namespaces or classes by prefixing the name 1426/// with '<enclosing>::'. 1427/// Does not match typedefs of an underlying type with the given name. 1428/// 1429/// Example matches X (Name == "X") 1430/// \code 1431/// class X; 1432/// \endcode 1433/// 1434/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X") 1435/// \code 1436/// namespace a { namespace b { class X; } } 1437/// \endcode 1438AST_MATCHER_P(NamedDecl, hasName, std::string, Name) { 1439 assert(!Name.empty()); 1440 const std::string FullNameString = "::" + Node.getQualifiedNameAsString(); 1441 const StringRef FullName = FullNameString; 1442 const StringRef Pattern = Name; 1443 if (Pattern.startswith("::")) { 1444 return FullName == Pattern; 1445 } else { 1446 return FullName.endswith(("::" + Pattern).str()); 1447 } 1448} 1449 1450/// \brief Matches NamedDecl nodes whose fully qualified names contain 1451/// a substring matched by the given RegExp. 1452/// 1453/// Supports specifying enclosing namespaces or classes by 1454/// prefixing the name with '<enclosing>::'. Does not match typedefs 1455/// of an underlying type with the given name. 1456/// 1457/// Example matches X (regexp == "::X") 1458/// \code 1459/// class X; 1460/// \endcode 1461/// 1462/// Example matches X (regexp is one of "::X", "^foo::.*X", among others) 1463/// \code 1464/// namespace foo { namespace bar { class X; } } 1465/// \endcode 1466AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) { 1467 assert(!RegExp.empty()); 1468 std::string FullNameString = "::" + Node.getQualifiedNameAsString(); 1469 llvm::Regex RE(RegExp); 1470 return RE.match(FullNameString); 1471} 1472 1473/// \brief Matches overloaded operator names. 1474/// 1475/// Matches overloaded operator names specified in strings without the 1476/// "operator" prefix: e.g. "<<". 1477/// 1478/// Given: 1479/// \code 1480/// class A { int operator*(); }; 1481/// const A &operator<<(const A &a, const A &b); 1482/// A a; 1483/// a << a; // <-- This matches 1484/// \endcode 1485/// 1486/// \c operatorCallExpr(hasOverloadedOperatorName("<<"))) matches the specified 1487/// line and \c recordDecl(hasMethod(hasOverloadedOperatorName("*"))) matches 1488/// the declaration of \c A. 1489/// 1490/// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<CXXMethodDecl> 1491inline internal::PolymorphicMatcherWithParam1< 1492 internal::HasOverloadedOperatorNameMatcher, StringRef, 1493 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CXXOperatorCallExpr, CXXMethodDecl)> 1494hasOverloadedOperatorName(const StringRef Name) { 1495 return internal::PolymorphicMatcherWithParam1< 1496 internal::HasOverloadedOperatorNameMatcher, StringRef, 1497 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CXXOperatorCallExpr, CXXMethodDecl)>( 1498 Name); 1499} 1500 1501/// \brief Matches C++ classes that are directly or indirectly derived from 1502/// a class matching \c Base. 1503/// 1504/// Note that a class is not considered to be derived from itself. 1505/// 1506/// Example matches Y, Z, C (Base == hasName("X")) 1507/// \code 1508/// class X; 1509/// class Y : public X {}; // directly derived 1510/// class Z : public Y {}; // indirectly derived 1511/// typedef X A; 1512/// typedef A B; 1513/// class C : public B {}; // derived from a typedef of X 1514/// \endcode 1515/// 1516/// In the following example, Bar matches isDerivedFrom(hasName("X")): 1517/// \code 1518/// class Foo; 1519/// typedef Foo X; 1520/// class Bar : public Foo {}; // derived from a type that X is a typedef of 1521/// \endcode 1522AST_MATCHER_P(CXXRecordDecl, isDerivedFrom, 1523 internal::Matcher<NamedDecl>, Base) { 1524 return Finder->classIsDerivedFrom(&Node, Base, Builder); 1525} 1526 1527/// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)). 1528inline internal::Matcher<CXXRecordDecl> isDerivedFrom(StringRef BaseName) { 1529 assert(!BaseName.empty()); 1530 return isDerivedFrom(hasName(BaseName)); 1531} 1532 1533/// \brief Similar to \c isDerivedFrom(), but also matches classes that directly 1534/// match \c Base. 1535inline internal::Matcher<CXXRecordDecl> isSameOrDerivedFrom( 1536 internal::Matcher<NamedDecl> Base) { 1537 return anyOf(Base, isDerivedFrom(Base)); 1538} 1539 1540/// \brief Overloaded method as shortcut for 1541/// \c isSameOrDerivedFrom(hasName(...)). 1542inline internal::Matcher<CXXRecordDecl> isSameOrDerivedFrom( 1543 StringRef BaseName) { 1544 assert(!BaseName.empty()); 1545 return isSameOrDerivedFrom(hasName(BaseName)); 1546} 1547 1548/// \brief Matches the first method of a class or struct that satisfies \c 1549/// InnerMatcher. 1550/// 1551/// Given: 1552/// \code 1553/// class A { void func(); }; 1554/// class B { void member(); }; 1555/// \code 1556/// 1557/// \c recordDecl(hasMethod(hasName("func"))) matches the declaration of \c A 1558/// but not \c B. 1559AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>, 1560 InnerMatcher) { 1561 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(), 1562 Node.method_end(), Finder, Builder); 1563} 1564 1565/// \brief Matches AST nodes that have child AST nodes that match the 1566/// provided matcher. 1567/// 1568/// Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X"))) 1569/// \code 1570/// class X {}; // Matches X, because X::X is a class of name X inside X. 1571/// class Y { class X {}; }; 1572/// class Z { class Y { class X {}; }; }; // Does not match Z. 1573/// \endcode 1574/// 1575/// ChildT must be an AST base type. 1576/// 1577/// Usable as: Any Matcher 1578template <typename ChildT> 1579internal::ArgumentAdaptingMatcher<internal::HasMatcher, ChildT> has( 1580 const internal::Matcher<ChildT> &ChildMatcher) { 1581 return internal::ArgumentAdaptingMatcher<internal::HasMatcher, 1582 ChildT>(ChildMatcher); 1583} 1584 1585/// \brief Matches AST nodes that have descendant AST nodes that match the 1586/// provided matcher. 1587/// 1588/// Example matches X, Y, Z 1589/// (matcher = recordDecl(hasDescendant(recordDecl(hasName("X"))))) 1590/// \code 1591/// class X {}; // Matches X, because X::X is a class of name X inside X. 1592/// class Y { class X {}; }; 1593/// class Z { class Y { class X {}; }; }; 1594/// \endcode 1595/// 1596/// DescendantT must be an AST base type. 1597/// 1598/// Usable as: Any Matcher 1599template <typename DescendantT> 1600internal::ArgumentAdaptingMatcher<internal::HasDescendantMatcher, DescendantT> 1601hasDescendant(const internal::Matcher<DescendantT> &DescendantMatcher) { 1602 return internal::ArgumentAdaptingMatcher< 1603 internal::HasDescendantMatcher, 1604 DescendantT>(DescendantMatcher); 1605} 1606 1607/// \brief Matches AST nodes that have child AST nodes that match the 1608/// provided matcher. 1609/// 1610/// Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X"))) 1611/// \code 1612/// class X {}; // Matches X, because X::X is a class of name X inside X. 1613/// class Y { class X {}; }; 1614/// class Z { class Y { class X {}; }; }; // Does not match Z. 1615/// \endcode 1616/// 1617/// ChildT must be an AST base type. 1618/// 1619/// As opposed to 'has', 'forEach' will cause a match for each result that 1620/// matches instead of only on the first one. 1621/// 1622/// Usable as: Any Matcher 1623template <typename ChildT> 1624internal::ArgumentAdaptingMatcher<internal::ForEachMatcher, ChildT> forEach( 1625 const internal::Matcher<ChildT> &ChildMatcher) { 1626 return internal::ArgumentAdaptingMatcher< 1627 internal::ForEachMatcher, 1628 ChildT>(ChildMatcher); 1629} 1630 1631/// \brief Matches AST nodes that have descendant AST nodes that match the 1632/// provided matcher. 1633/// 1634/// Example matches X, A, B, C 1635/// (matcher = recordDecl(forEachDescendant(recordDecl(hasName("X"))))) 1636/// \code 1637/// class X {}; // Matches X, because X::X is a class of name X inside X. 1638/// class A { class X {}; }; 1639/// class B { class C { class X {}; }; }; 1640/// \endcode 1641/// 1642/// DescendantT must be an AST base type. 1643/// 1644/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for 1645/// each result that matches instead of only on the first one. 1646/// 1647/// Note: Recursively combined ForEachDescendant can cause many matches: 1648/// recordDecl(forEachDescendant(recordDecl(forEachDescendant(recordDecl())))) 1649/// will match 10 times (plus injected class name matches) on: 1650/// \code 1651/// class A { class B { class C { class D { class E {}; }; }; }; }; 1652/// \endcode 1653/// 1654/// Usable as: Any Matcher 1655template <typename DescendantT> 1656internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, 1657 DescendantT> 1658forEachDescendant( 1659 const internal::Matcher<DescendantT> &DescendantMatcher) { 1660 return internal::ArgumentAdaptingMatcher< 1661 internal::ForEachDescendantMatcher, 1662 DescendantT>(DescendantMatcher); 1663} 1664 1665/// \brief Matches if the node or any descendant matches. 1666/// 1667/// Generates results for each match. 1668/// 1669/// For example, in: 1670/// \code 1671/// class A { class B {}; class C {}; }; 1672/// \endcode 1673/// The matcher: 1674/// \code 1675/// recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("m"))) 1676/// \endcode 1677/// will generate results for \c A, \c B and \c C. 1678/// 1679/// Usable as: Any Matcher 1680template <typename T> 1681internal::PolymorphicMatcherWithParam2< 1682 internal::EachOfMatcher, internal::Matcher<T>, 1683 internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, T> > 1684findAll(const internal::Matcher<T> &Matcher) { 1685 return eachOf(Matcher, forEachDescendant(Matcher)); 1686} 1687 1688/// \brief Matches AST nodes that have a parent that matches the provided 1689/// matcher. 1690/// 1691/// Given 1692/// \code 1693/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } } 1694/// \endcode 1695/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }". 1696/// 1697/// Usable as: Any Matcher 1698template <typename ParentT> 1699internal::ArgumentAdaptingMatcher<internal::HasParentMatcher, ParentT> 1700hasParent(const internal::Matcher<ParentT> &ParentMatcher) { 1701 return internal::ArgumentAdaptingMatcher< 1702 internal::HasParentMatcher, 1703 ParentT>(ParentMatcher); 1704} 1705 1706/// \brief Matches AST nodes that have an ancestor that matches the provided 1707/// matcher. 1708/// 1709/// Given 1710/// \code 1711/// void f() { if (true) { int x = 42; } } 1712/// void g() { for (;;) { int x = 43; } } 1713/// \endcode 1714/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43. 1715/// 1716/// Usable as: Any Matcher 1717template <typename AncestorT> 1718internal::ArgumentAdaptingMatcher<internal::HasAncestorMatcher, AncestorT> 1719hasAncestor(const internal::Matcher<AncestorT> &AncestorMatcher) { 1720 return internal::ArgumentAdaptingMatcher< 1721 internal::HasAncestorMatcher, 1722 AncestorT>(AncestorMatcher); 1723} 1724 1725/// \brief Matches if the provided matcher does not match. 1726/// 1727/// Example matches Y (matcher = recordDecl(unless(hasName("X")))) 1728/// \code 1729/// class X {}; 1730/// class Y {}; 1731/// \endcode 1732/// 1733/// Usable as: Any Matcher 1734template <typename M> 1735internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M> 1736unless(const M &InnerMatcher) { 1737 return internal::PolymorphicMatcherWithParam1< 1738 internal::NotMatcher, M>(InnerMatcher); 1739} 1740 1741/// \brief Matches a node if the declaration associated with that node 1742/// matches the given matcher. 1743/// 1744/// The associated declaration is: 1745/// - for type nodes, the declaration of the underlying type 1746/// - for CallExpr, the declaration of the callee 1747/// - for MemberExpr, the declaration of the referenced member 1748/// - for CXXConstructExpr, the declaration of the constructor 1749/// 1750/// Also usable as Matcher<T> for any T supporting the getDecl() member 1751/// function. e.g. various subtypes of clang::Type and various expressions. 1752/// FIXME: Add all node types for which this is matcher is usable due to 1753/// getDecl(). 1754/// 1755/// Usable as: Matcher<QualType>, Matcher<CallExpr>, Matcher<CXXConstructExpr>, 1756/// Matcher<MemberExpr>, Matcher<TypedefType>, 1757/// Matcher<TemplateSpecializationType> 1758inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher, 1759 internal::Matcher<Decl> > 1760 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) { 1761 return internal::PolymorphicMatcherWithParam1< 1762 internal::HasDeclarationMatcher, 1763 internal::Matcher<Decl> >(InnerMatcher); 1764} 1765 1766/// \brief Matches on the implicit object argument of a member call expression. 1767/// 1768/// Example matches y.x() (matcher = callExpr(on(hasType(recordDecl(hasName("Y")))))) 1769/// \code 1770/// class Y { public: void x(); }; 1771/// void z() { Y y; y.x(); }", 1772/// \endcode 1773/// 1774/// FIXME: Overload to allow directly matching types? 1775AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>, 1776 InnerMatcher) { 1777 const Expr *ExprNode = Node.getImplicitObjectArgument() 1778 ->IgnoreParenImpCasts(); 1779 return (ExprNode != NULL && 1780 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1781} 1782 1783/// \brief Matches if the call expression's callee expression matches. 1784/// 1785/// Given 1786/// \code 1787/// class Y { void x() { this->x(); x(); Y y; y.x(); } }; 1788/// void f() { f(); } 1789/// \endcode 1790/// callExpr(callee(expr())) 1791/// matches this->x(), x(), y.x(), f() 1792/// with callee(...) 1793/// matching this->x, x, y.x, f respectively 1794/// 1795/// Note: Callee cannot take the more general internal::Matcher<Expr> 1796/// because this introduces ambiguous overloads with calls to Callee taking a 1797/// internal::Matcher<Decl>, as the matcher hierarchy is purely 1798/// implemented in terms of implicit casts. 1799AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>, 1800 InnerMatcher) { 1801 const Expr *ExprNode = Node.getCallee(); 1802 return (ExprNode != NULL && 1803 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1804} 1805 1806/// \brief Matches if the call expression's callee's declaration matches the 1807/// given matcher. 1808/// 1809/// Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x"))))) 1810/// \code 1811/// class Y { public: void x(); }; 1812/// void z() { Y y; y.x(); 1813/// \endcode 1814inline internal::Matcher<CallExpr> callee( 1815 const internal::Matcher<Decl> &InnerMatcher) { 1816 return callExpr(hasDeclaration(InnerMatcher)); 1817} 1818 1819/// \brief Matches if the expression's or declaration's type matches a type 1820/// matcher. 1821/// 1822/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) 1823/// and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) 1824/// \code 1825/// class X {}; 1826/// void y(X &x) { x; X z; } 1827/// \endcode 1828AST_POLYMORPHIC_MATCHER_P(hasType, 1829 AST_POLYMORPHIC_SUPPORTED_TYPES_2(Expr, ValueDecl), 1830 internal::Matcher<QualType>, InnerMatcher) { 1831 return InnerMatcher.matches(Node.getType(), Finder, Builder); 1832} 1833 1834/// \brief Overloaded to match the declaration of the expression's or value 1835/// declaration's type. 1836/// 1837/// In case of a value declaration (for example a variable declaration), 1838/// this resolves one layer of indirection. For example, in the value 1839/// declaration "X x;", recordDecl(hasName("X")) matches the declaration of X, 1840/// while varDecl(hasType(recordDecl(hasName("X")))) matches the declaration 1841/// of x." 1842/// 1843/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) 1844/// and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) 1845/// \code 1846/// class X {}; 1847/// void y(X &x) { x; X z; } 1848/// \endcode 1849/// 1850/// Usable as: Matcher<Expr>, Matcher<ValueDecl> 1851inline internal::PolymorphicMatcherWithParam1< 1852 internal::matcher_hasType0Matcher, internal::Matcher<QualType>, 1853 AST_POLYMORPHIC_SUPPORTED_TYPES_2(Expr, ValueDecl)> 1854hasType(const internal::Matcher<Decl> &InnerMatcher) { 1855 return hasType(qualType(hasDeclaration(InnerMatcher))); 1856} 1857 1858/// \brief Matches if the type location of the declarator decl's type matches 1859/// the inner matcher. 1860/// 1861/// Given 1862/// \code 1863/// int x; 1864/// \endcode 1865/// declaratorDecl(hasTypeLoc(loc(asString("int")))) 1866/// matches int x 1867AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) { 1868 if (!Node.getTypeSourceInfo()) 1869 // This happens for example for implicit destructors. 1870 return false; 1871 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder); 1872} 1873 1874/// \brief Matches if the matched type is represented by the given string. 1875/// 1876/// Given 1877/// \code 1878/// class Y { public: void x(); }; 1879/// void z() { Y* y; y->x(); } 1880/// \endcode 1881/// callExpr(on(hasType(asString("class Y *")))) 1882/// matches y->x() 1883AST_MATCHER_P(QualType, asString, std::string, Name) { 1884 return Name == Node.getAsString(); 1885} 1886 1887/// \brief Matches if the matched type is a pointer type and the pointee type 1888/// matches the specified matcher. 1889/// 1890/// Example matches y->x() 1891/// (matcher = callExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))))) 1892/// \code 1893/// class Y { public: void x(); }; 1894/// void z() { Y *y; y->x(); } 1895/// \endcode 1896AST_MATCHER_P( 1897 QualType, pointsTo, internal::Matcher<QualType>, 1898 InnerMatcher) { 1899 return (!Node.isNull() && Node->isPointerType() && 1900 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1901} 1902 1903/// \brief Overloaded to match the pointee type's declaration. 1904inline internal::Matcher<QualType> pointsTo( 1905 const internal::Matcher<Decl> &InnerMatcher) { 1906 return pointsTo(qualType(hasDeclaration(InnerMatcher))); 1907} 1908 1909/// \brief Matches if the matched type is a reference type and the referenced 1910/// type matches the specified matcher. 1911/// 1912/// Example matches X &x and const X &y 1913/// (matcher = varDecl(hasType(references(recordDecl(hasName("X")))))) 1914/// \code 1915/// class X { 1916/// void a(X b) { 1917/// X &x = b; 1918/// const X &y = b; 1919/// }; 1920/// \endcode 1921AST_MATCHER_P(QualType, references, internal::Matcher<QualType>, 1922 InnerMatcher) { 1923 return (!Node.isNull() && Node->isReferenceType() && 1924 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1925} 1926 1927/// \brief Matches QualTypes whose canonical type matches InnerMatcher. 1928/// 1929/// Given: 1930/// \code 1931/// typedef int &int_ref; 1932/// int a; 1933/// int_ref b = a; 1934/// \code 1935/// 1936/// \c varDecl(hasType(qualType(referenceType()))))) will not match the 1937/// declaration of b but \c 1938/// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does. 1939AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>, 1940 InnerMatcher) { 1941 if (Node.isNull()) 1942 return false; 1943 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder); 1944} 1945 1946/// \brief Overloaded to match the referenced type's declaration. 1947inline internal::Matcher<QualType> references( 1948 const internal::Matcher<Decl> &InnerMatcher) { 1949 return references(qualType(hasDeclaration(InnerMatcher))); 1950} 1951 1952AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument, 1953 internal::Matcher<Expr>, InnerMatcher) { 1954 const Expr *ExprNode = Node.getImplicitObjectArgument(); 1955 return (ExprNode != NULL && 1956 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1957} 1958 1959/// \brief Matches if the expression's type either matches the specified 1960/// matcher, or is a pointer to a type that matches the InnerMatcher. 1961inline internal::Matcher<CXXMemberCallExpr> thisPointerType( 1962 const internal::Matcher<QualType> &InnerMatcher) { 1963 return onImplicitObjectArgument( 1964 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 1965} 1966 1967/// \brief Overloaded to match the type's declaration. 1968inline internal::Matcher<CXXMemberCallExpr> thisPointerType( 1969 const internal::Matcher<Decl> &InnerMatcher) { 1970 return onImplicitObjectArgument( 1971 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 1972} 1973 1974/// \brief Matches a DeclRefExpr that refers to a declaration that matches the 1975/// specified matcher. 1976/// 1977/// Example matches x in if(x) 1978/// (matcher = declRefExpr(to(varDecl(hasName("x"))))) 1979/// \code 1980/// bool x; 1981/// if (x) {} 1982/// \endcode 1983AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>, 1984 InnerMatcher) { 1985 const Decl *DeclNode = Node.getDecl(); 1986 return (DeclNode != NULL && 1987 InnerMatcher.matches(*DeclNode, Finder, Builder)); 1988} 1989 1990/// \brief Matches a \c DeclRefExpr that refers to a declaration through a 1991/// specific using shadow declaration. 1992/// 1993/// FIXME: This currently only works for functions. Fix. 1994/// 1995/// Given 1996/// \code 1997/// namespace a { void f() {} } 1998/// using a::f; 1999/// void g() { 2000/// f(); // Matches this .. 2001/// a::f(); // .. but not this. 2002/// } 2003/// \endcode 2004/// declRefExpr(throughUsingDeclaration(anything())) 2005/// matches \c f() 2006AST_MATCHER_P(DeclRefExpr, throughUsingDecl, 2007 internal::Matcher<UsingShadowDecl>, InnerMatcher) { 2008 const NamedDecl *FoundDecl = Node.getFoundDecl(); 2009 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl)) 2010 return InnerMatcher.matches(*UsingDecl, Finder, Builder); 2011 return false; 2012} 2013 2014/// \brief Matches the Decl of a DeclStmt which has a single declaration. 2015/// 2016/// Given 2017/// \code 2018/// int a, b; 2019/// int c; 2020/// \endcode 2021/// declStmt(hasSingleDecl(anything())) 2022/// matches 'int c;' but not 'int a, b;'. 2023AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) { 2024 if (Node.isSingleDecl()) { 2025 const Decl *FoundDecl = Node.getSingleDecl(); 2026 return InnerMatcher.matches(*FoundDecl, Finder, Builder); 2027 } 2028 return false; 2029} 2030 2031/// \brief Matches a variable declaration that has an initializer expression 2032/// that matches the given matcher. 2033/// 2034/// Example matches x (matcher = varDecl(hasInitializer(callExpr()))) 2035/// \code 2036/// bool y() { return true; } 2037/// bool x = y(); 2038/// \endcode 2039AST_MATCHER_P( 2040 VarDecl, hasInitializer, internal::Matcher<Expr>, 2041 InnerMatcher) { 2042 const Expr *Initializer = Node.getAnyInitializer(); 2043 return (Initializer != NULL && 2044 InnerMatcher.matches(*Initializer, Finder, Builder)); 2045} 2046 2047/// \brief Checks that a call expression or a constructor call expression has 2048/// a specific number of arguments (including absent default arguments). 2049/// 2050/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2))) 2051/// \code 2052/// void f(int x, int y); 2053/// f(0, 0); 2054/// \endcode 2055AST_POLYMORPHIC_MATCHER_P(argumentCountIs, AST_POLYMORPHIC_SUPPORTED_TYPES_2( 2056 CallExpr, CXXConstructExpr), 2057 unsigned, N) { 2058 return Node.getNumArgs() == N; 2059} 2060 2061/// \brief Matches the n'th argument of a call expression or a constructor 2062/// call expression. 2063/// 2064/// Example matches y in x(y) 2065/// (matcher = callExpr(hasArgument(0, declRefExpr()))) 2066/// \code 2067/// void x(int) { int y; x(y); } 2068/// \endcode 2069AST_POLYMORPHIC_MATCHER_P2( 2070 hasArgument, 2071 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CallExpr, CXXConstructExpr), 2072 unsigned, N, internal::Matcher<Expr>, InnerMatcher) { 2073 return (N < Node.getNumArgs() && 2074 InnerMatcher.matches( 2075 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder)); 2076} 2077 2078/// \brief Matches declaration statements that contain a specific number of 2079/// declarations. 2080/// 2081/// Example: Given 2082/// \code 2083/// int a, b; 2084/// int c; 2085/// int d = 2, e; 2086/// \endcode 2087/// declCountIs(2) 2088/// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'. 2089AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) { 2090 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N; 2091} 2092 2093/// \brief Matches the n'th declaration of a declaration statement. 2094/// 2095/// Note that this does not work for global declarations because the AST 2096/// breaks up multiple-declaration DeclStmt's into multiple single-declaration 2097/// DeclStmt's. 2098/// Example: Given non-global declarations 2099/// \code 2100/// int a, b = 0; 2101/// int c; 2102/// int d = 2, e; 2103/// \endcode 2104/// declStmt(containsDeclaration( 2105/// 0, varDecl(hasInitializer(anything())))) 2106/// matches only 'int d = 2, e;', and 2107/// declStmt(containsDeclaration(1, varDecl())) 2108/// \code 2109/// matches 'int a, b = 0' as well as 'int d = 2, e;' 2110/// but 'int c;' is not matched. 2111/// \endcode 2112AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N, 2113 internal::Matcher<Decl>, InnerMatcher) { 2114 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end()); 2115 if (N >= NumDecls) 2116 return false; 2117 DeclStmt::const_decl_iterator Iterator = Node.decl_begin(); 2118 std::advance(Iterator, N); 2119 return InnerMatcher.matches(**Iterator, Finder, Builder); 2120} 2121 2122/// \brief Matches a constructor initializer. 2123/// 2124/// Given 2125/// \code 2126/// struct Foo { 2127/// Foo() : foo_(1) { } 2128/// int foo_; 2129/// }; 2130/// \endcode 2131/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything())))) 2132/// record matches Foo, hasAnyConstructorInitializer matches foo_(1) 2133AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer, 2134 internal::Matcher<CXXCtorInitializer>, InnerMatcher) { 2135 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(), 2136 Node.init_end(), Finder, Builder); 2137} 2138 2139/// \brief Matches the field declaration of a constructor initializer. 2140/// 2141/// Given 2142/// \code 2143/// struct Foo { 2144/// Foo() : foo_(1) { } 2145/// int foo_; 2146/// }; 2147/// \endcode 2148/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer( 2149/// forField(hasName("foo_")))))) 2150/// matches Foo 2151/// with forField matching foo_ 2152AST_MATCHER_P(CXXCtorInitializer, forField, 2153 internal::Matcher<FieldDecl>, InnerMatcher) { 2154 const FieldDecl *NodeAsDecl = Node.getMember(); 2155 return (NodeAsDecl != NULL && 2156 InnerMatcher.matches(*NodeAsDecl, Finder, Builder)); 2157} 2158 2159/// \brief Matches the initializer expression of a constructor initializer. 2160/// 2161/// Given 2162/// \code 2163/// struct Foo { 2164/// Foo() : foo_(1) { } 2165/// int foo_; 2166/// }; 2167/// \endcode 2168/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer( 2169/// withInitializer(integerLiteral(equals(1))))))) 2170/// matches Foo 2171/// with withInitializer matching (1) 2172AST_MATCHER_P(CXXCtorInitializer, withInitializer, 2173 internal::Matcher<Expr>, InnerMatcher) { 2174 const Expr* NodeAsExpr = Node.getInit(); 2175 return (NodeAsExpr != NULL && 2176 InnerMatcher.matches(*NodeAsExpr, Finder, Builder)); 2177} 2178 2179/// \brief Matches a contructor initializer if it is explicitly written in 2180/// code (as opposed to implicitly added by the compiler). 2181/// 2182/// Given 2183/// \code 2184/// struct Foo { 2185/// Foo() { } 2186/// Foo(int) : foo_("A") { } 2187/// string foo_; 2188/// }; 2189/// \endcode 2190/// constructorDecl(hasAnyConstructorInitializer(isWritten())) 2191/// will match Foo(int), but not Foo() 2192AST_MATCHER(CXXCtorInitializer, isWritten) { 2193 return Node.isWritten(); 2194} 2195 2196/// \brief Matches a constructor declaration that has been implicitly added 2197/// by the compiler (eg. implicit default/copy constructors). 2198AST_MATCHER(CXXConstructorDecl, isImplicit) { 2199 return Node.isImplicit(); 2200} 2201 2202/// \brief Matches any argument of a call expression or a constructor call 2203/// expression. 2204/// 2205/// Given 2206/// \code 2207/// void x(int, int, int) { int y; x(1, y, 42); } 2208/// \endcode 2209/// callExpr(hasAnyArgument(declRefExpr())) 2210/// matches x(1, y, 42) 2211/// with hasAnyArgument(...) 2212/// matching y 2213/// 2214/// FIXME: Currently this will ignore parentheses and implicit casts on 2215/// the argument before applying the inner matcher. We'll want to remove 2216/// this to allow for greater control by the user once \c ignoreImplicit() 2217/// has been implemented. 2218AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, AST_POLYMORPHIC_SUPPORTED_TYPES_2( 2219 CallExpr, CXXConstructExpr), 2220 internal::Matcher<Expr>, InnerMatcher) { 2221 for (unsigned I = 0; I < Node.getNumArgs(); ++I) { 2222 BoundNodesTreeBuilder Result(*Builder); 2223 if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(), Finder, 2224 &Result)) { 2225 *Builder = Result; 2226 return true; 2227 } 2228 } 2229 return false; 2230} 2231 2232/// \brief Matches the n'th parameter of a function declaration. 2233/// 2234/// Given 2235/// \code 2236/// class X { void f(int x) {} }; 2237/// \endcode 2238/// methodDecl(hasParameter(0, hasType(varDecl()))) 2239/// matches f(int x) {} 2240/// with hasParameter(...) 2241/// matching int x 2242AST_MATCHER_P2(FunctionDecl, hasParameter, 2243 unsigned, N, internal::Matcher<ParmVarDecl>, 2244 InnerMatcher) { 2245 return (N < Node.getNumParams() && 2246 InnerMatcher.matches( 2247 *Node.getParamDecl(N), Finder, Builder)); 2248} 2249 2250/// \brief Matches any parameter of a function declaration. 2251/// 2252/// Does not match the 'this' parameter of a method. 2253/// 2254/// Given 2255/// \code 2256/// class X { void f(int x, int y, int z) {} }; 2257/// \endcode 2258/// methodDecl(hasAnyParameter(hasName("y"))) 2259/// matches f(int x, int y, int z) {} 2260/// with hasAnyParameter(...) 2261/// matching int y 2262AST_MATCHER_P(FunctionDecl, hasAnyParameter, 2263 internal::Matcher<ParmVarDecl>, InnerMatcher) { 2264 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(), 2265 Node.param_end(), Finder, Builder); 2266} 2267 2268/// \brief Matches \c FunctionDecls that have a specific parameter count. 2269/// 2270/// Given 2271/// \code 2272/// void f(int i) {} 2273/// void g(int i, int j) {} 2274/// \endcode 2275/// functionDecl(parameterCountIs(2)) 2276/// matches g(int i, int j) {} 2277AST_MATCHER_P(FunctionDecl, parameterCountIs, unsigned, N) { 2278 return Node.getNumParams() == N; 2279} 2280 2281/// \brief Matches the return type of a function declaration. 2282/// 2283/// Given: 2284/// \code 2285/// class X { int f() { return 1; } }; 2286/// \endcode 2287/// methodDecl(returns(asString("int"))) 2288/// matches int f() { return 1; } 2289AST_MATCHER_P(FunctionDecl, returns, 2290 internal::Matcher<QualType>, InnerMatcher) { 2291 return InnerMatcher.matches(Node.getResultType(), Finder, Builder); 2292} 2293 2294/// \brief Matches extern "C" function declarations. 2295/// 2296/// Given: 2297/// \code 2298/// extern "C" void f() {} 2299/// extern "C" { void g() {} } 2300/// void h() {} 2301/// \endcode 2302/// functionDecl(isExternC()) 2303/// matches the declaration of f and g, but not the declaration h 2304AST_MATCHER(FunctionDecl, isExternC) { 2305 return Node.isExternC(); 2306} 2307 2308/// \brief Matches the condition expression of an if statement, for loop, 2309/// or conditional operator. 2310/// 2311/// Example matches true (matcher = hasCondition(boolLiteral(equals(true)))) 2312/// \code 2313/// if (true) {} 2314/// \endcode 2315AST_POLYMORPHIC_MATCHER_P( 2316 hasCondition, AST_POLYMORPHIC_SUPPORTED_TYPES_5( 2317 IfStmt, ForStmt, WhileStmt, DoStmt, ConditionalOperator), 2318 internal::Matcher<Expr>, InnerMatcher) { 2319 const Expr *const Condition = Node.getCond(); 2320 return (Condition != NULL && 2321 InnerMatcher.matches(*Condition, Finder, Builder)); 2322} 2323 2324namespace internal { 2325struct NotEqualsBoundNodePredicate { 2326 bool operator()(const internal::BoundNodesMap &Nodes) const { 2327 return Nodes.getNode(ID) != Node; 2328 } 2329 std::string ID; 2330 ast_type_traits::DynTypedNode Node; 2331}; 2332} // namespace internal 2333 2334/// \brief Matches if a node equals a previously bound node. 2335/// 2336/// Matches a node if it equals the node previously bound to \p ID. 2337/// 2338/// Given 2339/// \code 2340/// class X { int a; int b; }; 2341/// \endcode 2342/// recordDecl( 2343/// has(fieldDecl(hasName("a"), hasType(type().bind("t")))), 2344/// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t")))))) 2345/// matches the class \c X, as \c a and \c b have the same type. 2346/// 2347/// Note that when multiple matches are involved via \c forEach* matchers, 2348/// \c equalsBoundNodes acts as a filter. 2349/// For example: 2350/// compoundStmt( 2351/// forEachDescendant(varDecl().bind("d")), 2352/// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))) 2353/// will trigger a match for each combination of variable declaration 2354/// and reference to that variable declaration within a compound statement. 2355AST_POLYMORPHIC_MATCHER_P(equalsBoundNode, AST_POLYMORPHIC_SUPPORTED_TYPES_4( 2356 Stmt, Decl, Type, QualType), 2357 std::string, ID) { 2358 // FIXME: Figure out whether it makes sense to allow this 2359 // on any other node types. 2360 // For *Loc it probably does not make sense, as those seem 2361 // unique. For NestedNameSepcifier it might make sense, as 2362 // those also have pointer identity, but I'm not sure whether 2363 // they're ever reused. 2364 internal::NotEqualsBoundNodePredicate Predicate; 2365 Predicate.ID = ID; 2366 Predicate.Node = ast_type_traits::DynTypedNode::create(Node); 2367 return Builder->removeBindings(Predicate); 2368} 2369 2370/// \brief Matches the condition variable statement in an if statement. 2371/// 2372/// Given 2373/// \code 2374/// if (A* a = GetAPointer()) {} 2375/// \endcode 2376/// hasConditionVariableStatment(...) 2377/// matches 'A* a = GetAPointer()'. 2378AST_MATCHER_P(IfStmt, hasConditionVariableStatement, 2379 internal::Matcher<DeclStmt>, InnerMatcher) { 2380 const DeclStmt* const DeclarationStatement = 2381 Node.getConditionVariableDeclStmt(); 2382 return DeclarationStatement != NULL && 2383 InnerMatcher.matches(*DeclarationStatement, Finder, Builder); 2384} 2385 2386/// \brief Matches the index expression of an array subscript expression. 2387/// 2388/// Given 2389/// \code 2390/// int i[5]; 2391/// void f() { i[1] = 42; } 2392/// \endcode 2393/// arraySubscriptExpression(hasIndex(integerLiteral())) 2394/// matches \c i[1] with the \c integerLiteral() matching \c 1 2395AST_MATCHER_P(ArraySubscriptExpr, hasIndex, 2396 internal::Matcher<Expr>, InnerMatcher) { 2397 if (const Expr* Expression = Node.getIdx()) 2398 return InnerMatcher.matches(*Expression, Finder, Builder); 2399 return false; 2400} 2401 2402/// \brief Matches the base expression of an array subscript expression. 2403/// 2404/// Given 2405/// \code 2406/// int i[5]; 2407/// void f() { i[1] = 42; } 2408/// \endcode 2409/// arraySubscriptExpression(hasBase(implicitCastExpr( 2410/// hasSourceExpression(declRefExpr())))) 2411/// matches \c i[1] with the \c declRefExpr() matching \c i 2412AST_MATCHER_P(ArraySubscriptExpr, hasBase, 2413 internal::Matcher<Expr>, InnerMatcher) { 2414 if (const Expr* Expression = Node.getBase()) 2415 return InnerMatcher.matches(*Expression, Finder, Builder); 2416 return false; 2417} 2418 2419/// \brief Matches a 'for', 'while', or 'do while' statement that has 2420/// a given body. 2421/// 2422/// Given 2423/// \code 2424/// for (;;) {} 2425/// \endcode 2426/// hasBody(compoundStmt()) 2427/// matches 'for (;;) {}' 2428/// with compoundStmt() 2429/// matching '{}' 2430AST_POLYMORPHIC_MATCHER_P( 2431 hasBody, AST_POLYMORPHIC_SUPPORTED_TYPES_3(DoStmt, ForStmt, WhileStmt), 2432 internal::Matcher<Stmt>, InnerMatcher) { 2433 const Stmt *const Statement = Node.getBody(); 2434 return (Statement != NULL && 2435 InnerMatcher.matches(*Statement, Finder, Builder)); 2436} 2437 2438/// \brief Matches compound statements where at least one substatement matches 2439/// a given matcher. 2440/// 2441/// Given 2442/// \code 2443/// { {}; 1+2; } 2444/// \endcode 2445/// hasAnySubstatement(compoundStmt()) 2446/// matches '{ {}; 1+2; }' 2447/// with compoundStmt() 2448/// matching '{}' 2449AST_MATCHER_P(CompoundStmt, hasAnySubstatement, 2450 internal::Matcher<Stmt>, InnerMatcher) { 2451 return matchesFirstInPointerRange(InnerMatcher, Node.body_begin(), 2452 Node.body_end(), Finder, Builder); 2453} 2454 2455/// \brief Checks that a compound statement contains a specific number of 2456/// child statements. 2457/// 2458/// Example: Given 2459/// \code 2460/// { for (;;) {} } 2461/// \endcode 2462/// compoundStmt(statementCountIs(0))) 2463/// matches '{}' 2464/// but does not match the outer compound statement. 2465AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) { 2466 return Node.size() == N; 2467} 2468 2469/// \brief Matches literals that are equal to the given value. 2470/// 2471/// Example matches true (matcher = boolLiteral(equals(true))) 2472/// \code 2473/// true 2474/// \endcode 2475/// 2476/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>, 2477/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral> 2478template <typename ValueT> 2479internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT> 2480equals(const ValueT &Value) { 2481 return internal::PolymorphicMatcherWithParam1< 2482 internal::ValueEqualsMatcher, 2483 ValueT>(Value); 2484} 2485 2486/// \brief Matches the operator Name of operator expressions (binary or 2487/// unary). 2488/// 2489/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||"))) 2490/// \code 2491/// !(a || b) 2492/// \endcode 2493AST_POLYMORPHIC_MATCHER_P(hasOperatorName, AST_POLYMORPHIC_SUPPORTED_TYPES_2( 2494 BinaryOperator, UnaryOperator), 2495 std::string, Name) { 2496 return Name == Node.getOpcodeStr(Node.getOpcode()); 2497} 2498 2499/// \brief Matches the left hand side of binary operator expressions. 2500/// 2501/// Example matches a (matcher = binaryOperator(hasLHS())) 2502/// \code 2503/// a || b 2504/// \endcode 2505AST_MATCHER_P(BinaryOperator, hasLHS, 2506 internal::Matcher<Expr>, InnerMatcher) { 2507 Expr *LeftHandSide = Node.getLHS(); 2508 return (LeftHandSide != NULL && 2509 InnerMatcher.matches(*LeftHandSide, Finder, Builder)); 2510} 2511 2512/// \brief Matches the right hand side of binary operator expressions. 2513/// 2514/// Example matches b (matcher = binaryOperator(hasRHS())) 2515/// \code 2516/// a || b 2517/// \endcode 2518AST_MATCHER_P(BinaryOperator, hasRHS, 2519 internal::Matcher<Expr>, InnerMatcher) { 2520 Expr *RightHandSide = Node.getRHS(); 2521 return (RightHandSide != NULL && 2522 InnerMatcher.matches(*RightHandSide, Finder, Builder)); 2523} 2524 2525/// \brief Matches if either the left hand side or the right hand side of a 2526/// binary operator matches. 2527inline internal::Matcher<BinaryOperator> hasEitherOperand( 2528 const internal::Matcher<Expr> &InnerMatcher) { 2529 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)); 2530} 2531 2532/// \brief Matches if the operand of a unary operator matches. 2533/// 2534/// Example matches true (matcher = hasUnaryOperand(boolLiteral(equals(true)))) 2535/// \code 2536/// !true 2537/// \endcode 2538AST_MATCHER_P(UnaryOperator, hasUnaryOperand, 2539 internal::Matcher<Expr>, InnerMatcher) { 2540 const Expr * const Operand = Node.getSubExpr(); 2541 return (Operand != NULL && 2542 InnerMatcher.matches(*Operand, Finder, Builder)); 2543} 2544 2545/// \brief Matches if the cast's source expression matches the given matcher. 2546/// 2547/// Example: matches "a string" (matcher = 2548/// hasSourceExpression(constructExpr())) 2549/// \code 2550/// class URL { URL(string); }; 2551/// URL url = "a string"; 2552AST_MATCHER_P(CastExpr, hasSourceExpression, 2553 internal::Matcher<Expr>, InnerMatcher) { 2554 const Expr* const SubExpression = Node.getSubExpr(); 2555 return (SubExpression != NULL && 2556 InnerMatcher.matches(*SubExpression, Finder, Builder)); 2557} 2558 2559/// \brief Matches casts whose destination type matches a given matcher. 2560/// 2561/// (Note: Clang's AST refers to other conversions as "casts" too, and calls 2562/// actual casts "explicit" casts.) 2563AST_MATCHER_P(ExplicitCastExpr, hasDestinationType, 2564 internal::Matcher<QualType>, InnerMatcher) { 2565 const QualType NodeType = Node.getTypeAsWritten(); 2566 return InnerMatcher.matches(NodeType, Finder, Builder); 2567} 2568 2569/// \brief Matches implicit casts whose destination type matches a given 2570/// matcher. 2571/// 2572/// FIXME: Unit test this matcher 2573AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType, 2574 internal::Matcher<QualType>, InnerMatcher) { 2575 return InnerMatcher.matches(Node.getType(), Finder, Builder); 2576} 2577 2578/// \brief Matches the true branch expression of a conditional operator. 2579/// 2580/// Example matches a 2581/// \code 2582/// condition ? a : b 2583/// \endcode 2584AST_MATCHER_P(ConditionalOperator, hasTrueExpression, 2585 internal::Matcher<Expr>, InnerMatcher) { 2586 Expr *Expression = Node.getTrueExpr(); 2587 return (Expression != NULL && 2588 InnerMatcher.matches(*Expression, Finder, Builder)); 2589} 2590 2591/// \brief Matches the false branch expression of a conditional operator. 2592/// 2593/// Example matches b 2594/// \code 2595/// condition ? a : b 2596/// \endcode 2597AST_MATCHER_P(ConditionalOperator, hasFalseExpression, 2598 internal::Matcher<Expr>, InnerMatcher) { 2599 Expr *Expression = Node.getFalseExpr(); 2600 return (Expression != NULL && 2601 InnerMatcher.matches(*Expression, Finder, Builder)); 2602} 2603 2604/// \brief Matches if a declaration has a body attached. 2605/// 2606/// Example matches A, va, fa 2607/// \code 2608/// class A {}; 2609/// class B; // Doesn't match, as it has no body. 2610/// int va; 2611/// extern int vb; // Doesn't match, as it doesn't define the variable. 2612/// void fa() {} 2613/// void fb(); // Doesn't match, as it has no body. 2614/// \endcode 2615/// 2616/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl> 2617AST_POLYMORPHIC_MATCHER(isDefinition, AST_POLYMORPHIC_SUPPORTED_TYPES_3( 2618 TagDecl, VarDecl, FunctionDecl)) { 2619 return Node.isThisDeclarationADefinition(); 2620} 2621 2622/// \brief Matches the class declaration that the given method declaration 2623/// belongs to. 2624/// 2625/// FIXME: Generalize this for other kinds of declarations. 2626/// FIXME: What other kind of declarations would we need to generalize 2627/// this to? 2628/// 2629/// Example matches A() in the last line 2630/// (matcher = constructExpr(hasDeclaration(methodDecl( 2631/// ofClass(hasName("A")))))) 2632/// \code 2633/// class A { 2634/// public: 2635/// A(); 2636/// }; 2637/// A a = A(); 2638/// \endcode 2639AST_MATCHER_P(CXXMethodDecl, ofClass, 2640 internal::Matcher<CXXRecordDecl>, InnerMatcher) { 2641 const CXXRecordDecl *Parent = Node.getParent(); 2642 return (Parent != NULL && 2643 InnerMatcher.matches(*Parent, Finder, Builder)); 2644} 2645 2646/// \brief Matches if the given method declaration is virtual. 2647/// 2648/// Given 2649/// \code 2650/// class A { 2651/// public: 2652/// virtual void x(); 2653/// }; 2654/// \endcode 2655/// matches A::x 2656AST_MATCHER(CXXMethodDecl, isVirtual) { 2657 return Node.isVirtual(); 2658} 2659 2660/// \brief Matches if the given method declaration is const. 2661/// 2662/// Given 2663/// \code 2664/// struct A { 2665/// void foo() const; 2666/// void bar(); 2667/// }; 2668/// \endcode 2669/// 2670/// methodDecl(isConst()) matches A::foo() but not A::bar() 2671AST_MATCHER(CXXMethodDecl, isConst) { 2672 return Node.isConst(); 2673} 2674 2675/// \brief Matches if the given method declaration overrides another method. 2676/// 2677/// Given 2678/// \code 2679/// class A { 2680/// public: 2681/// virtual void x(); 2682/// }; 2683/// class B : public A { 2684/// public: 2685/// virtual void x(); 2686/// }; 2687/// \endcode 2688/// matches B::x 2689AST_MATCHER(CXXMethodDecl, isOverride) { 2690 return Node.size_overridden_methods() > 0; 2691} 2692 2693/// \brief Matches member expressions that are called with '->' as opposed 2694/// to '.'. 2695/// 2696/// Member calls on the implicit this pointer match as called with '->'. 2697/// 2698/// Given 2699/// \code 2700/// class Y { 2701/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 2702/// int a; 2703/// static int b; 2704/// }; 2705/// \endcode 2706/// memberExpr(isArrow()) 2707/// matches this->x, x, y.x, a, this->b 2708AST_MATCHER(MemberExpr, isArrow) { 2709 return Node.isArrow(); 2710} 2711 2712/// \brief Matches QualType nodes that are of integer type. 2713/// 2714/// Given 2715/// \code 2716/// void a(int); 2717/// void b(long); 2718/// void c(double); 2719/// \endcode 2720/// functionDecl(hasAnyParameter(hasType(isInteger()))) 2721/// matches "a(int)", "b(long)", but not "c(double)". 2722AST_MATCHER(QualType, isInteger) { 2723 return Node->isIntegerType(); 2724} 2725 2726/// \brief Matches QualType nodes that are const-qualified, i.e., that 2727/// include "top-level" const. 2728/// 2729/// Given 2730/// \code 2731/// void a(int); 2732/// void b(int const); 2733/// void c(const int); 2734/// void d(const int*); 2735/// void e(int const) {}; 2736/// \endcode 2737/// functionDecl(hasAnyParameter(hasType(isConstQualified()))) 2738/// matches "void b(int const)", "void c(const int)" and 2739/// "void e(int const) {}". It does not match d as there 2740/// is no top-level const on the parameter type "const int *". 2741AST_MATCHER(QualType, isConstQualified) { 2742 return Node.isConstQualified(); 2743} 2744 2745/// \brief Matches QualType nodes that have local CV-qualifiers attached to 2746/// the node, not hidden within a typedef. 2747/// 2748/// Given 2749/// \code 2750/// typedef const int const_int; 2751/// const_int i; 2752/// int *const j; 2753/// int *volatile k; 2754/// int m; 2755/// \endcode 2756/// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k. 2757/// \c i is const-qualified but the qualifier is not local. 2758AST_MATCHER(QualType, hasLocalQualifiers) { 2759 return Node.hasLocalQualifiers(); 2760} 2761 2762/// \brief Matches a member expression where the member is matched by a 2763/// given matcher. 2764/// 2765/// Given 2766/// \code 2767/// struct { int first, second; } first, second; 2768/// int i(second.first); 2769/// int j(first.second); 2770/// \endcode 2771/// memberExpr(member(hasName("first"))) 2772/// matches second.first 2773/// but not first.second (because the member name there is "second"). 2774AST_MATCHER_P(MemberExpr, member, 2775 internal::Matcher<ValueDecl>, InnerMatcher) { 2776 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder); 2777} 2778 2779/// \brief Matches a member expression where the object expression is 2780/// matched by a given matcher. 2781/// 2782/// Given 2783/// \code 2784/// struct X { int m; }; 2785/// void f(X x) { x.m; m; } 2786/// \endcode 2787/// memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X"))))))) 2788/// matches "x.m" and "m" 2789/// with hasObjectExpression(...) 2790/// matching "x" and the implicit object expression of "m" which has type X*. 2791AST_MATCHER_P(MemberExpr, hasObjectExpression, 2792 internal::Matcher<Expr>, InnerMatcher) { 2793 return InnerMatcher.matches(*Node.getBase(), Finder, Builder); 2794} 2795 2796/// \brief Matches any using shadow declaration. 2797/// 2798/// Given 2799/// \code 2800/// namespace X { void b(); } 2801/// using X::b; 2802/// \endcode 2803/// usingDecl(hasAnyUsingShadowDecl(hasName("b")))) 2804/// matches \code using X::b \endcode 2805AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl, 2806 internal::Matcher<UsingShadowDecl>, InnerMatcher) { 2807 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(), 2808 Node.shadow_end(), Finder, Builder); 2809} 2810 2811/// \brief Matches a using shadow declaration where the target declaration is 2812/// matched by the given matcher. 2813/// 2814/// Given 2815/// \code 2816/// namespace X { int a; void b(); } 2817/// using X::a; 2818/// using X::b; 2819/// \endcode 2820/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl()))) 2821/// matches \code using X::b \endcode 2822/// but not \code using X::a \endcode 2823AST_MATCHER_P(UsingShadowDecl, hasTargetDecl, 2824 internal::Matcher<NamedDecl>, InnerMatcher) { 2825 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder); 2826} 2827 2828/// \brief Matches template instantiations of function, class, or static 2829/// member variable template instantiations. 2830/// 2831/// Given 2832/// \code 2833/// template <typename T> class X {}; class A {}; X<A> x; 2834/// \endcode 2835/// or 2836/// \code 2837/// template <typename T> class X {}; class A {}; template class X<A>; 2838/// \endcode 2839/// recordDecl(hasName("::X"), isTemplateInstantiation()) 2840/// matches the template instantiation of X<A>. 2841/// 2842/// But given 2843/// \code 2844/// template <typename T> class X {}; class A {}; 2845/// template <> class X<A> {}; X<A> x; 2846/// \endcode 2847/// recordDecl(hasName("::X"), isTemplateInstantiation()) 2848/// does not match, as X<A> is an explicit template specialization. 2849/// 2850/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> 2851AST_POLYMORPHIC_MATCHER( 2852 isTemplateInstantiation, 2853 AST_POLYMORPHIC_SUPPORTED_TYPES_3(FunctionDecl, VarDecl, CXXRecordDecl)) { 2854 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation || 2855 Node.getTemplateSpecializationKind() == 2856 TSK_ExplicitInstantiationDefinition); 2857} 2858 2859/// \brief Matches explicit template specializations of function, class, or 2860/// static member variable template instantiations. 2861/// 2862/// Given 2863/// \code 2864/// template<typename T> void A(T t) { } 2865/// template<> void A(int N) { } 2866/// \endcode 2867/// functionDecl(isExplicitTemplateSpecialization()) 2868/// matches the specialization A<int>(). 2869/// 2870/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> 2871AST_POLYMORPHIC_MATCHER( 2872 isExplicitTemplateSpecialization, 2873 AST_POLYMORPHIC_SUPPORTED_TYPES_3(FunctionDecl, VarDecl, CXXRecordDecl)) { 2874 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization); 2875} 2876 2877/// \brief Matches \c TypeLocs for which the given inner 2878/// QualType-matcher matches. 2879inline internal::BindableMatcher<TypeLoc> loc( 2880 const internal::Matcher<QualType> &InnerMatcher) { 2881 return internal::BindableMatcher<TypeLoc>( 2882 new internal::TypeLocTypeMatcher(InnerMatcher)); 2883} 2884 2885/// \brief Matches builtin Types. 2886/// 2887/// Given 2888/// \code 2889/// struct A {}; 2890/// A a; 2891/// int b; 2892/// float c; 2893/// bool d; 2894/// \endcode 2895/// builtinType() 2896/// matches "int b", "float c" and "bool d" 2897AST_TYPE_MATCHER(BuiltinType, builtinType); 2898 2899/// \brief Matches all kinds of arrays. 2900/// 2901/// Given 2902/// \code 2903/// int a[] = { 2, 3 }; 2904/// int b[4]; 2905/// void f() { int c[a[0]]; } 2906/// \endcode 2907/// arrayType() 2908/// matches "int a[]", "int b[4]" and "int c[a[0]]"; 2909AST_TYPE_MATCHER(ArrayType, arrayType); 2910 2911/// \brief Matches C99 complex types. 2912/// 2913/// Given 2914/// \code 2915/// _Complex float f; 2916/// \endcode 2917/// complexType() 2918/// matches "_Complex float f" 2919AST_TYPE_MATCHER(ComplexType, complexType); 2920 2921/// \brief Matches arrays and C99 complex types that have a specific element 2922/// type. 2923/// 2924/// Given 2925/// \code 2926/// struct A {}; 2927/// A a[7]; 2928/// int b[7]; 2929/// \endcode 2930/// arrayType(hasElementType(builtinType())) 2931/// matches "int b[7]" 2932/// 2933/// Usable as: Matcher<ArrayType>, Matcher<ComplexType> 2934AST_TYPELOC_TRAVERSE_MATCHER( 2935 hasElementType, getElement, 2936 AST_POLYMORPHIC_SUPPORTED_TYPES_2(ArrayType, ComplexType)); 2937 2938/// \brief Matches C arrays with a specified constant size. 2939/// 2940/// Given 2941/// \code 2942/// void() { 2943/// int a[2]; 2944/// int b[] = { 2, 3 }; 2945/// int c[b[0]]; 2946/// } 2947/// \endcode 2948/// constantArrayType() 2949/// matches "int a[2]" 2950AST_TYPE_MATCHER(ConstantArrayType, constantArrayType); 2951 2952/// \brief Matches \c ConstantArrayType nodes that have the specified size. 2953/// 2954/// Given 2955/// \code 2956/// int a[42]; 2957/// int b[2 * 21]; 2958/// int c[41], d[43]; 2959/// \endcode 2960/// constantArrayType(hasSize(42)) 2961/// matches "int a[42]" and "int b[2 * 21]" 2962AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) { 2963 return Node.getSize() == N; 2964} 2965 2966/// \brief Matches C++ arrays whose size is a value-dependent expression. 2967/// 2968/// Given 2969/// \code 2970/// template<typename T, int Size> 2971/// class array { 2972/// T data[Size]; 2973/// }; 2974/// \endcode 2975/// dependentSizedArrayType 2976/// matches "T data[Size]" 2977AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType); 2978 2979/// \brief Matches C arrays with unspecified size. 2980/// 2981/// Given 2982/// \code 2983/// int a[] = { 2, 3 }; 2984/// int b[42]; 2985/// void f(int c[]) { int d[a[0]]; }; 2986/// \endcode 2987/// incompleteArrayType() 2988/// matches "int a[]" and "int c[]" 2989AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType); 2990 2991/// \brief Matches C arrays with a specified size that is not an 2992/// integer-constant-expression. 2993/// 2994/// Given 2995/// \code 2996/// void f() { 2997/// int a[] = { 2, 3 } 2998/// int b[42]; 2999/// int c[a[0]]; 3000/// \endcode 3001/// variableArrayType() 3002/// matches "int c[a[0]]" 3003AST_TYPE_MATCHER(VariableArrayType, variableArrayType); 3004 3005/// \brief Matches \c VariableArrayType nodes that have a specific size 3006/// expression. 3007/// 3008/// Given 3009/// \code 3010/// void f(int b) { 3011/// int a[b]; 3012/// } 3013/// \endcode 3014/// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to( 3015/// varDecl(hasName("b"))))))) 3016/// matches "int a[b]" 3017AST_MATCHER_P(VariableArrayType, hasSizeExpr, 3018 internal::Matcher<Expr>, InnerMatcher) { 3019 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder); 3020} 3021 3022/// \brief Matches atomic types. 3023/// 3024/// Given 3025/// \code 3026/// _Atomic(int) i; 3027/// \endcode 3028/// atomicType() 3029/// matches "_Atomic(int) i" 3030AST_TYPE_MATCHER(AtomicType, atomicType); 3031 3032/// \brief Matches atomic types with a specific value type. 3033/// 3034/// Given 3035/// \code 3036/// _Atomic(int) i; 3037/// _Atomic(float) f; 3038/// \endcode 3039/// atomicType(hasValueType(isInteger())) 3040/// matches "_Atomic(int) i" 3041/// 3042/// Usable as: Matcher<AtomicType> 3043AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue, 3044 AST_POLYMORPHIC_SUPPORTED_TYPES_1(AtomicType)); 3045 3046/// \brief Matches types nodes representing C++11 auto types. 3047/// 3048/// Given: 3049/// \code 3050/// auto n = 4; 3051/// int v[] = { 2, 3 } 3052/// for (auto i : v) { } 3053/// \endcode 3054/// autoType() 3055/// matches "auto n" and "auto i" 3056AST_TYPE_MATCHER(AutoType, autoType); 3057 3058/// \brief Matches \c AutoType nodes where the deduced type is a specific type. 3059/// 3060/// Note: There is no \c TypeLoc for the deduced type and thus no 3061/// \c getDeducedLoc() matcher. 3062/// 3063/// Given 3064/// \code 3065/// auto a = 1; 3066/// auto b = 2.0; 3067/// \endcode 3068/// autoType(hasDeducedType(isInteger())) 3069/// matches "auto a" 3070/// 3071/// Usable as: Matcher<AutoType> 3072AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType, 3073 AST_POLYMORPHIC_SUPPORTED_TYPES_1(AutoType)); 3074 3075/// \brief Matches \c FunctionType nodes. 3076/// 3077/// Given 3078/// \code 3079/// int (*f)(int); 3080/// void g(); 3081/// \endcode 3082/// functionType() 3083/// matches "int (*f)(int)" and the type of "g". 3084AST_TYPE_MATCHER(FunctionType, functionType); 3085 3086/// \brief Matches \c ParenType nodes. 3087/// 3088/// Given 3089/// \code 3090/// int (*ptr_to_array)[4]; 3091/// int *array_of_ptrs[4]; 3092/// \endcode 3093/// 3094/// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not 3095/// \c array_of_ptrs. 3096AST_TYPE_MATCHER(ParenType, parenType); 3097 3098/// \brief Matches \c ParenType nodes where the inner type is a specific type. 3099/// 3100/// Given 3101/// \code 3102/// int (*ptr_to_array)[4]; 3103/// int (*ptr_to_func)(int); 3104/// \endcode 3105/// 3106/// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches 3107/// \c ptr_to_func but not \c ptr_to_array. 3108/// 3109/// Usable as: Matcher<ParenType> 3110AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType, 3111 AST_POLYMORPHIC_SUPPORTED_TYPES_1(ParenType)); 3112 3113/// \brief Matches block pointer types, i.e. types syntactically represented as 3114/// "void (^)(int)". 3115/// 3116/// The \c pointee is always required to be a \c FunctionType. 3117AST_TYPE_MATCHER(BlockPointerType, blockPointerType); 3118 3119/// \brief Matches member pointer types. 3120/// Given 3121/// \code 3122/// struct A { int i; } 3123/// A::* ptr = A::i; 3124/// \endcode 3125/// memberPointerType() 3126/// matches "A::* ptr" 3127AST_TYPE_MATCHER(MemberPointerType, memberPointerType); 3128 3129/// \brief Matches pointer types. 3130/// 3131/// Given 3132/// \code 3133/// int *a; 3134/// int &b = *a; 3135/// int c = 5; 3136/// \endcode 3137/// pointerType() 3138/// matches "int *a" 3139AST_TYPE_MATCHER(PointerType, pointerType); 3140 3141/// \brief Matches both lvalue and rvalue reference types. 3142/// 3143/// Given 3144/// \code 3145/// int *a; 3146/// int &b = *a; 3147/// int &&c = 1; 3148/// auto &d = b; 3149/// auto &&e = c; 3150/// auto &&f = 2; 3151/// int g = 5; 3152/// \endcode 3153/// 3154/// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f. 3155AST_TYPE_MATCHER(ReferenceType, referenceType); 3156 3157/// \brief Matches lvalue reference types. 3158/// 3159/// Given: 3160/// \code 3161/// int *a; 3162/// int &b = *a; 3163/// int &&c = 1; 3164/// auto &d = b; 3165/// auto &&e = c; 3166/// auto &&f = 2; 3167/// int g = 5; 3168/// \endcode 3169/// 3170/// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is 3171/// matched since the type is deduced as int& by reference collapsing rules. 3172AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType); 3173 3174/// \brief Matches rvalue reference types. 3175/// 3176/// Given: 3177/// \code 3178/// int *a; 3179/// int &b = *a; 3180/// int &&c = 1; 3181/// auto &d = b; 3182/// auto &&e = c; 3183/// auto &&f = 2; 3184/// int g = 5; 3185/// \endcode 3186/// 3187/// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not 3188/// matched as it is deduced to int& by reference collapsing rules. 3189AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType); 3190 3191/// \brief Narrows PointerType (and similar) matchers to those where the 3192/// \c pointee matches a given matcher. 3193/// 3194/// Given 3195/// \code 3196/// int *a; 3197/// int const *b; 3198/// float const *f; 3199/// \endcode 3200/// pointerType(pointee(isConstQualified(), isInteger())) 3201/// matches "int const *b" 3202/// 3203/// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>, 3204/// Matcher<PointerType>, Matcher<ReferenceType> 3205AST_TYPELOC_TRAVERSE_MATCHER( 3206 pointee, getPointee, 3207 AST_POLYMORPHIC_SUPPORTED_TYPES_4(BlockPointerType, MemberPointerType, 3208 PointerType, ReferenceType)); 3209 3210/// \brief Matches typedef types. 3211/// 3212/// Given 3213/// \code 3214/// typedef int X; 3215/// \endcode 3216/// typedefType() 3217/// matches "typedef int X" 3218AST_TYPE_MATCHER(TypedefType, typedefType); 3219 3220/// \brief Matches template specialization types. 3221/// 3222/// Given 3223/// \code 3224/// template <typename T> 3225/// class C { }; 3226/// 3227/// template class C<int>; // A 3228/// C<char> var; // B 3229/// \code 3230/// 3231/// \c templateSpecializationType() matches the type of the explicit 3232/// instantiation in \c A and the type of the variable declaration in \c B. 3233AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType); 3234 3235/// \brief Matches types nodes representing unary type transformations. 3236/// 3237/// Given: 3238/// \code 3239/// typedef __underlying_type(T) type; 3240/// \endcode 3241/// unaryTransformType() 3242/// matches "__underlying_type(T)" 3243AST_TYPE_MATCHER(UnaryTransformType, unaryTransformType); 3244 3245/// \brief Matches record types (e.g. structs, classes). 3246/// 3247/// Given 3248/// \code 3249/// class C {}; 3250/// struct S {}; 3251/// 3252/// C c; 3253/// S s; 3254/// \code 3255/// 3256/// \c recordType() matches the type of the variable declarations of both \c c 3257/// and \c s. 3258AST_TYPE_MATCHER(RecordType, recordType); 3259 3260/// \brief Matches types specified with an elaborated type keyword or with a 3261/// qualified name. 3262/// 3263/// Given 3264/// \code 3265/// namespace N { 3266/// namespace M { 3267/// class D {}; 3268/// } 3269/// } 3270/// class C {}; 3271/// 3272/// class C c; 3273/// N::M::D d; 3274/// \code 3275/// 3276/// \c elaboratedType() matches the type of the variable declarations of both 3277/// \c c and \c d. 3278AST_TYPE_MATCHER(ElaboratedType, elaboratedType); 3279 3280/// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier, 3281/// matches \c InnerMatcher if the qualifier exists. 3282/// 3283/// Given 3284/// \code 3285/// namespace N { 3286/// namespace M { 3287/// class D {}; 3288/// } 3289/// } 3290/// N::M::D d; 3291/// \code 3292/// 3293/// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))) 3294/// matches the type of the variable declaration of \c d. 3295AST_MATCHER_P(ElaboratedType, hasQualifier, 3296 internal::Matcher<NestedNameSpecifier>, InnerMatcher) { 3297 if (const NestedNameSpecifier *Qualifier = Node.getQualifier()) 3298 return InnerMatcher.matches(*Qualifier, Finder, Builder); 3299 3300 return false; 3301} 3302 3303/// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher. 3304/// 3305/// Given 3306/// \code 3307/// namespace N { 3308/// namespace M { 3309/// class D {}; 3310/// } 3311/// } 3312/// N::M::D d; 3313/// \code 3314/// 3315/// \c elaboratedType(namesType(recordType( 3316/// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable 3317/// declaration of \c d. 3318AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>, 3319 InnerMatcher) { 3320 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder); 3321} 3322 3323/// \brief Matches declarations whose declaration context, interpreted as a 3324/// Decl, matches \c InnerMatcher. 3325/// 3326/// Given 3327/// \code 3328/// namespace N { 3329/// namespace M { 3330/// class D {}; 3331/// } 3332/// } 3333/// \code 3334/// 3335/// \c recordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the 3336/// declaration of \c class \c D. 3337AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) { 3338 return InnerMatcher.matches(*Decl::castFromDeclContext(Node.getDeclContext()), 3339 Finder, Builder); 3340} 3341 3342/// \brief Matches nested name specifiers. 3343/// 3344/// Given 3345/// \code 3346/// namespace ns { 3347/// struct A { static void f(); }; 3348/// void A::f() {} 3349/// void g() { A::f(); } 3350/// } 3351/// ns::A a; 3352/// \endcode 3353/// nestedNameSpecifier() 3354/// matches "ns::" and both "A::" 3355const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier; 3356 3357/// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc. 3358const internal::VariadicAllOfMatcher< 3359 NestedNameSpecifierLoc> nestedNameSpecifierLoc; 3360 3361/// \brief Matches \c NestedNameSpecifierLocs for which the given inner 3362/// NestedNameSpecifier-matcher matches. 3363inline internal::BindableMatcher<NestedNameSpecifierLoc> loc( 3364 const internal::Matcher<NestedNameSpecifier> &InnerMatcher) { 3365 return internal::BindableMatcher<NestedNameSpecifierLoc>( 3366 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>( 3367 InnerMatcher)); 3368} 3369 3370/// \brief Matches nested name specifiers that specify a type matching the 3371/// given \c QualType matcher without qualifiers. 3372/// 3373/// Given 3374/// \code 3375/// struct A { struct B { struct C {}; }; }; 3376/// A::B::C c; 3377/// \endcode 3378/// nestedNameSpecifier(specifiesType(hasDeclaration(recordDecl(hasName("A"))))) 3379/// matches "A::" 3380AST_MATCHER_P(NestedNameSpecifier, specifiesType, 3381 internal::Matcher<QualType>, InnerMatcher) { 3382 if (Node.getAsType() == NULL) 3383 return false; 3384 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder); 3385} 3386 3387/// \brief Matches nested name specifier locs that specify a type matching the 3388/// given \c TypeLoc. 3389/// 3390/// Given 3391/// \code 3392/// struct A { struct B { struct C {}; }; }; 3393/// A::B::C c; 3394/// \endcode 3395/// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type( 3396/// hasDeclaration(recordDecl(hasName("A"))))))) 3397/// matches "A::" 3398AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc, 3399 internal::Matcher<TypeLoc>, InnerMatcher) { 3400 return InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder); 3401} 3402 3403/// \brief Matches on the prefix of a \c NestedNameSpecifier. 3404/// 3405/// Given 3406/// \code 3407/// struct A { struct B { struct C {}; }; }; 3408/// A::B::C c; 3409/// \endcode 3410/// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and 3411/// matches "A::" 3412AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix, 3413 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 3414 0) { 3415 NestedNameSpecifier *NextNode = Node.getPrefix(); 3416 if (NextNode == NULL) 3417 return false; 3418 return InnerMatcher.matches(*NextNode, Finder, Builder); 3419} 3420 3421/// \brief Matches on the prefix of a \c NestedNameSpecifierLoc. 3422/// 3423/// Given 3424/// \code 3425/// struct A { struct B { struct C {}; }; }; 3426/// A::B::C c; 3427/// \endcode 3428/// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A"))))) 3429/// matches "A::" 3430AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix, 3431 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher, 3432 1) { 3433 NestedNameSpecifierLoc NextNode = Node.getPrefix(); 3434 if (!NextNode) 3435 return false; 3436 return InnerMatcher.matches(NextNode, Finder, Builder); 3437} 3438 3439/// \brief Matches nested name specifiers that specify a namespace matching the 3440/// given namespace matcher. 3441/// 3442/// Given 3443/// \code 3444/// namespace ns { struct A {}; } 3445/// ns::A a; 3446/// \endcode 3447/// nestedNameSpecifier(specifiesNamespace(hasName("ns"))) 3448/// matches "ns::" 3449AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace, 3450 internal::Matcher<NamespaceDecl>, InnerMatcher) { 3451 if (Node.getAsNamespace() == NULL) 3452 return false; 3453 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder); 3454} 3455 3456/// \brief Overloads for the \c equalsNode matcher. 3457/// FIXME: Implement for other node types. 3458/// @{ 3459 3460/// \brief Matches if a node equals another node. 3461/// 3462/// \c Decl has pointer identity in the AST. 3463AST_MATCHER_P_OVERLOAD(Decl, equalsNode, Decl*, Other, 0) { 3464 return &Node == Other; 3465} 3466/// \brief Matches if a node equals another node. 3467/// 3468/// \c Stmt has pointer identity in the AST. 3469/// 3470AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, Stmt*, Other, 1) { 3471 return &Node == Other; 3472} 3473 3474/// @} 3475 3476/// \brief Matches each case or default statement belonging to the given switch 3477/// statement. This matcher may produce multiple matches. 3478/// 3479/// Given 3480/// \code 3481/// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } } 3482/// \endcode 3483/// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s") 3484/// matches four times, with "c" binding each of "case 1:", "case 2:", 3485/// "case 3:" and "case 4:", and "s" respectively binding "switch (1)", 3486/// "switch (1)", "switch (2)" and "switch (2)". 3487AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>, 3488 InnerMatcher) { 3489 BoundNodesTreeBuilder Result; 3490 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable 3491 // iteration order. We should use the more general iterating matchers once 3492 // they are capable of expressing this matcher (for example, it should ignore 3493 // case statements belonging to nested switch statements). 3494 bool Matched = false; 3495 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC; 3496 SC = SC->getNextSwitchCase()) { 3497 BoundNodesTreeBuilder CaseBuilder(*Builder); 3498 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder); 3499 if (CaseMatched) { 3500 Matched = true; 3501 Result.addMatch(CaseBuilder); 3502 } 3503 } 3504 *Builder = Result; 3505 return Matched; 3506} 3507 3508/// \brief Matches each constructor initializer in a constructor definition. 3509/// 3510/// Given 3511/// \code 3512/// class A { A() : i(42), j(42) {} int i; int j; }; 3513/// \endcode 3514/// constructorDecl(forEachConstructorInitializer(forField(decl().bind("x")))) 3515/// will trigger two matches, binding for 'i' and 'j' respectively. 3516AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer, 3517 internal::Matcher<CXXCtorInitializer>, InnerMatcher) { 3518 BoundNodesTreeBuilder Result; 3519 bool Matched = false; 3520 for (CXXConstructorDecl::init_const_iterator I = Node.init_begin(), 3521 E = Node.init_end(); 3522 I != E; ++I) { 3523 BoundNodesTreeBuilder InitBuilder(*Builder); 3524 if (InnerMatcher.matches(**I, Finder, &InitBuilder)) { 3525 Matched = true; 3526 Result.addMatch(InitBuilder); 3527 } 3528 } 3529 *Builder = Result; 3530 return Matched; 3531} 3532 3533/// \brief If the given case statement does not use the GNU case range 3534/// extension, matches the constant given in the statement. 3535/// 3536/// Given 3537/// \code 3538/// switch (1) { case 1: case 1+1: case 3 ... 4: ; } 3539/// \endcode 3540/// caseStmt(hasCaseConstant(integerLiteral())) 3541/// matches "case 1:" 3542AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>, 3543 InnerMatcher) { 3544 if (Node.getRHS()) 3545 return false; 3546 3547 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder); 3548} 3549 3550} // end namespace ast_matchers 3551} // end namespace clang 3552 3553#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H 3554