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