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