ASTMatchers.h revision 799bf2d371bb1cba04317c216ce1cd707d389c74
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 \c QualTypes in the clang AST. 1273const internal::VariadicAllOfMatcher<QualType> qualType; 1274 1275/// \brief Matches \c Types in the clang AST. 1276const internal::VariadicAllOfMatcher<Type> type; 1277 1278/// \brief Matches \c TypeLocs in the clang AST. 1279const internal::VariadicAllOfMatcher<TypeLoc> typeLoc; 1280 1281/// \brief Matches if any of the given matchers matches. 1282/// 1283/// Unlike \c anyOf, \c eachOf will generate a match result for each 1284/// matching submatcher. 1285/// 1286/// For example, in: 1287/// \code 1288/// class A { int a; int b; }; 1289/// \endcode 1290/// The matcher: 1291/// \code 1292/// recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")), 1293/// has(fieldDecl(hasName("b")).bind("v")))) 1294/// \endcode 1295/// will generate two results binding "v", the first of which binds 1296/// the field declaration of \c a, the second the field declaration of 1297/// \c b. 1298/// 1299/// Usable as: Any Matcher 1300const internal::VariadicOperatorMatcherFunc eachOf = { 1301 internal::EachOfVariadicOperator 1302}; 1303 1304/// \brief Matches if any of the given matchers matches. 1305/// 1306/// Usable as: Any Matcher 1307const internal::VariadicOperatorMatcherFunc anyOf = { 1308 internal::AnyOfVariadicOperator 1309}; 1310 1311/// \brief Matches if all given matchers match. 1312/// 1313/// Usable as: Any Matcher 1314const internal::VariadicOperatorMatcherFunc allOf = { 1315 internal::AllOfVariadicOperator 1316}; 1317 1318/// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL) 1319/// 1320/// Given 1321/// \code 1322/// Foo x = bar; 1323/// int y = sizeof(x) + alignof(x); 1324/// \endcode 1325/// unaryExprOrTypeTraitExpr() 1326/// matches \c sizeof(x) and \c alignof(x) 1327const internal::VariadicDynCastAllOfMatcher< 1328 Stmt, 1329 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr; 1330 1331/// \brief Matches unary expressions that have a specific type of argument. 1332/// 1333/// Given 1334/// \code 1335/// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c); 1336/// \endcode 1337/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int")) 1338/// matches \c sizeof(a) and \c alignof(c) 1339AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType, 1340 internal::Matcher<QualType>, InnerMatcher) { 1341 const QualType ArgumentType = Node.getTypeOfArgument(); 1342 return InnerMatcher.matches(ArgumentType, Finder, Builder); 1343} 1344 1345/// \brief Matches unary expressions of a certain kind. 1346/// 1347/// Given 1348/// \code 1349/// int x; 1350/// int s = sizeof(x) + alignof(x) 1351/// \endcode 1352/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf)) 1353/// matches \c sizeof(x) 1354AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) { 1355 return Node.getKind() == Kind; 1356} 1357 1358/// \brief Same as unaryExprOrTypeTraitExpr, but only matching 1359/// alignof. 1360inline internal::Matcher<Stmt> alignOfExpr( 1361 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) { 1362 return stmt(unaryExprOrTypeTraitExpr(allOf( 1363 ofKind(UETT_AlignOf), InnerMatcher))); 1364} 1365 1366/// \brief Same as unaryExprOrTypeTraitExpr, but only matching 1367/// sizeof. 1368inline internal::Matcher<Stmt> sizeOfExpr( 1369 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) { 1370 return stmt(unaryExprOrTypeTraitExpr( 1371 allOf(ofKind(UETT_SizeOf), InnerMatcher))); 1372} 1373 1374/// \brief Matches NamedDecl nodes that have the specified name. 1375/// 1376/// Supports specifying enclosing namespaces or classes by prefixing the name 1377/// with '<enclosing>::'. 1378/// Does not match typedefs of an underlying type with the given name. 1379/// 1380/// Example matches X (Name == "X") 1381/// \code 1382/// class X; 1383/// \endcode 1384/// 1385/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X") 1386/// \code 1387/// namespace a { namespace b { class X; } } 1388/// \endcode 1389AST_MATCHER_P(NamedDecl, hasName, std::string, Name) { 1390 assert(!Name.empty()); 1391 const std::string FullNameString = "::" + Node.getQualifiedNameAsString(); 1392 const StringRef FullName = FullNameString; 1393 const StringRef Pattern = Name; 1394 if (Pattern.startswith("::")) { 1395 return FullName == Pattern; 1396 } else { 1397 return FullName.endswith(("::" + Pattern).str()); 1398 } 1399} 1400 1401/// \brief Matches NamedDecl nodes whose fully qualified names contain 1402/// a substring matched by the given RegExp. 1403/// 1404/// Supports specifying enclosing namespaces or classes by 1405/// prefixing the name with '<enclosing>::'. Does not match typedefs 1406/// of an underlying type with the given name. 1407/// 1408/// Example matches X (regexp == "::X") 1409/// \code 1410/// class X; 1411/// \endcode 1412/// 1413/// Example matches X (regexp is one of "::X", "^foo::.*X", among others) 1414/// \code 1415/// namespace foo { namespace bar { class X; } } 1416/// \endcode 1417AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) { 1418 assert(!RegExp.empty()); 1419 std::string FullNameString = "::" + Node.getQualifiedNameAsString(); 1420 llvm::Regex RE(RegExp); 1421 return RE.match(FullNameString); 1422} 1423 1424/// \brief Matches overloaded operator names. 1425/// 1426/// Matches overloaded operator names specified in strings without the 1427/// "operator" prefix: e.g. "<<". 1428/// 1429/// Given: 1430/// \code 1431/// class A { int operator*(); }; 1432/// const A &operator<<(const A &a, const A &b); 1433/// A a; 1434/// a << a; // <-- This matches 1435/// \endcode 1436/// 1437/// \c operatorCallExpr(hasOverloadedOperatorName("<<"))) matches the specified 1438/// line and \c recordDecl(hasMethod(hasOverloadedOperatorName("*"))) matches 1439/// the declaration of \c A. 1440/// 1441/// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<CXXMethodDecl> 1442inline internal::PolymorphicMatcherWithParam1< 1443 internal::HasOverloadedOperatorNameMatcher, StringRef, 1444 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CXXOperatorCallExpr, CXXMethodDecl)> 1445hasOverloadedOperatorName(const StringRef Name) { 1446 return internal::PolymorphicMatcherWithParam1< 1447 internal::HasOverloadedOperatorNameMatcher, StringRef, 1448 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CXXOperatorCallExpr, CXXMethodDecl)>( 1449 Name); 1450} 1451 1452/// \brief Matches C++ classes that are directly or indirectly derived from 1453/// a class matching \c Base. 1454/// 1455/// Note that a class is not considered to be derived from itself. 1456/// 1457/// Example matches Y, Z, C (Base == hasName("X")) 1458/// \code 1459/// class X; 1460/// class Y : public X {}; // directly derived 1461/// class Z : public Y {}; // indirectly derived 1462/// typedef X A; 1463/// typedef A B; 1464/// class C : public B {}; // derived from a typedef of X 1465/// \endcode 1466/// 1467/// In the following example, Bar matches isDerivedFrom(hasName("X")): 1468/// \code 1469/// class Foo; 1470/// typedef Foo X; 1471/// class Bar : public Foo {}; // derived from a type that X is a typedef of 1472/// \endcode 1473AST_MATCHER_P(CXXRecordDecl, isDerivedFrom, 1474 internal::Matcher<NamedDecl>, Base) { 1475 return Finder->classIsDerivedFrom(&Node, Base, Builder); 1476} 1477 1478/// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)). 1479AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, StringRef, BaseName, 1) { 1480 assert(!BaseName.empty()); 1481 return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder); 1482} 1483 1484/// \brief Similar to \c isDerivedFrom(), but also matches classes that directly 1485/// match \c Base. 1486AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, 1487 internal::Matcher<NamedDecl>, Base, 0) { 1488 return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base))) 1489 .matches(Node, Finder, Builder); 1490} 1491 1492/// \brief Overloaded method as shortcut for 1493/// \c isSameOrDerivedFrom(hasName(...)). 1494AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, StringRef, BaseName, 1495 1) { 1496 assert(!BaseName.empty()); 1497 return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder); 1498} 1499 1500/// \brief Matches the first method of a class or struct that satisfies \c 1501/// InnerMatcher. 1502/// 1503/// Given: 1504/// \code 1505/// class A { void func(); }; 1506/// class B { void member(); }; 1507/// \code 1508/// 1509/// \c recordDecl(hasMethod(hasName("func"))) matches the declaration of \c A 1510/// but not \c B. 1511AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>, 1512 InnerMatcher) { 1513 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(), 1514 Node.method_end(), Finder, Builder); 1515} 1516 1517/// \brief Matches AST nodes that have child AST nodes that match the 1518/// provided matcher. 1519/// 1520/// Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X"))) 1521/// \code 1522/// class X {}; // Matches X, because X::X is a class of name X inside X. 1523/// class Y { class X {}; }; 1524/// class Z { class Y { class X {}; }; }; // Does not match Z. 1525/// \endcode 1526/// 1527/// ChildT must be an AST base type. 1528/// 1529/// Usable as: Any Matcher 1530const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> 1531LLVM_ATTRIBUTE_UNUSED has = {}; 1532 1533/// \brief Matches AST nodes that have descendant AST nodes that match the 1534/// provided matcher. 1535/// 1536/// Example matches X, Y, Z 1537/// (matcher = recordDecl(hasDescendant(recordDecl(hasName("X"))))) 1538/// \code 1539/// class X {}; // Matches X, because X::X is a class of name X inside X. 1540/// class Y { class X {}; }; 1541/// class Z { class Y { class X {}; }; }; 1542/// \endcode 1543/// 1544/// DescendantT must be an AST base type. 1545/// 1546/// Usable as: Any Matcher 1547const internal::ArgumentAdaptingMatcherFunc<internal::HasDescendantMatcher> 1548LLVM_ATTRIBUTE_UNUSED hasDescendant = {}; 1549 1550/// \brief Matches AST nodes that have child AST nodes that match the 1551/// provided matcher. 1552/// 1553/// Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X"))) 1554/// \code 1555/// class X {}; // Matches X, because X::X is a class of name X inside X. 1556/// class Y { class X {}; }; 1557/// class Z { class Y { class X {}; }; }; // Does not match Z. 1558/// \endcode 1559/// 1560/// ChildT must be an AST base type. 1561/// 1562/// As opposed to 'has', 'forEach' will cause a match for each result that 1563/// matches instead of only on the first one. 1564/// 1565/// Usable as: Any Matcher 1566const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher> 1567LLVM_ATTRIBUTE_UNUSED forEach = {}; 1568 1569/// \brief Matches AST nodes that have descendant AST nodes that match the 1570/// provided matcher. 1571/// 1572/// Example matches X, A, B, C 1573/// (matcher = recordDecl(forEachDescendant(recordDecl(hasName("X"))))) 1574/// \code 1575/// class X {}; // Matches X, because X::X is a class of name X inside X. 1576/// class A { class X {}; }; 1577/// class B { class C { class X {}; }; }; 1578/// \endcode 1579/// 1580/// DescendantT must be an AST base type. 1581/// 1582/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for 1583/// each result that matches instead of only on the first one. 1584/// 1585/// Note: Recursively combined ForEachDescendant can cause many matches: 1586/// recordDecl(forEachDescendant(recordDecl(forEachDescendant(recordDecl())))) 1587/// will match 10 times (plus injected class name matches) on: 1588/// \code 1589/// class A { class B { class C { class D { class E {}; }; }; }; }; 1590/// \endcode 1591/// 1592/// Usable as: Any Matcher 1593const internal::ArgumentAdaptingMatcherFunc<internal::ForEachDescendantMatcher> 1594LLVM_ATTRIBUTE_UNUSED forEachDescendant = {}; 1595 1596/// \brief Matches if the node or any descendant matches. 1597/// 1598/// Generates results for each match. 1599/// 1600/// For example, in: 1601/// \code 1602/// class A { class B {}; class C {}; }; 1603/// \endcode 1604/// The matcher: 1605/// \code 1606/// recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("m"))) 1607/// \endcode 1608/// will generate results for \c A, \c B and \c C. 1609/// 1610/// Usable as: Any Matcher 1611template <typename T> 1612internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) { 1613 return eachOf(Matcher, forEachDescendant(Matcher)); 1614} 1615 1616/// \brief Matches AST nodes that have a parent that matches the provided 1617/// matcher. 1618/// 1619/// Given 1620/// \code 1621/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } } 1622/// \endcode 1623/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }". 1624/// 1625/// Usable as: Any Matcher 1626const internal::ArgumentAdaptingMatcherFunc< 1627 internal::HasParentMatcher, internal::TypeList<Decl, Stmt>, 1628 internal::TypeList<Decl, Stmt> > hasParent = {}; 1629 1630/// \brief Matches AST nodes that have an ancestor that matches the provided 1631/// matcher. 1632/// 1633/// Given 1634/// \code 1635/// void f() { if (true) { int x = 42; } } 1636/// void g() { for (;;) { int x = 43; } } 1637/// \endcode 1638/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43. 1639/// 1640/// Usable as: Any Matcher 1641const internal::ArgumentAdaptingMatcherFunc< 1642 internal::HasAncestorMatcher, internal::TypeList<Decl, Stmt>, 1643 internal::TypeList<Decl, Stmt> > hasAncestor = {}; 1644 1645/// \brief Matches if the provided matcher does not match. 1646/// 1647/// Example matches Y (matcher = recordDecl(unless(hasName("X")))) 1648/// \code 1649/// class X {}; 1650/// class Y {}; 1651/// \endcode 1652/// 1653/// Usable as: Any Matcher 1654template <typename M> 1655internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M> 1656unless(const M &InnerMatcher) { 1657 return internal::PolymorphicMatcherWithParam1< 1658 internal::NotMatcher, M>(InnerMatcher); 1659} 1660 1661/// \brief Matches a node if the declaration associated with that node 1662/// matches the given matcher. 1663/// 1664/// The associated declaration is: 1665/// - for type nodes, the declaration of the underlying type 1666/// - for CallExpr, the declaration of the callee 1667/// - for MemberExpr, the declaration of the referenced member 1668/// - for CXXConstructExpr, the declaration of the constructor 1669/// 1670/// Also usable as Matcher<T> for any T supporting the getDecl() member 1671/// function. e.g. various subtypes of clang::Type and various expressions. 1672/// FIXME: Add all node types for which this is matcher is usable due to 1673/// getDecl(). 1674/// 1675/// Usable as: Matcher<QualType>, Matcher<CallExpr>, Matcher<CXXConstructExpr>, 1676/// Matcher<MemberExpr>, Matcher<TypedefType>, 1677/// Matcher<TemplateSpecializationType> 1678inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher, 1679 internal::Matcher<Decl> > 1680 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) { 1681 return internal::PolymorphicMatcherWithParam1< 1682 internal::HasDeclarationMatcher, 1683 internal::Matcher<Decl> >(InnerMatcher); 1684} 1685 1686/// \brief Matches on the implicit object argument of a member call expression. 1687/// 1688/// Example matches y.x() (matcher = callExpr(on(hasType(recordDecl(hasName("Y")))))) 1689/// \code 1690/// class Y { public: void x(); }; 1691/// void z() { Y y; y.x(); }", 1692/// \endcode 1693/// 1694/// FIXME: Overload to allow directly matching types? 1695AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>, 1696 InnerMatcher) { 1697 const Expr *ExprNode = Node.getImplicitObjectArgument() 1698 ->IgnoreParenImpCasts(); 1699 return (ExprNode != NULL && 1700 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1701} 1702 1703/// \brief Matches if the call expression's callee expression matches. 1704/// 1705/// Given 1706/// \code 1707/// class Y { void x() { this->x(); x(); Y y; y.x(); } }; 1708/// void f() { f(); } 1709/// \endcode 1710/// callExpr(callee(expr())) 1711/// matches this->x(), x(), y.x(), f() 1712/// with callee(...) 1713/// matching this->x, x, y.x, f respectively 1714/// 1715/// Note: Callee cannot take the more general internal::Matcher<Expr> 1716/// because this introduces ambiguous overloads with calls to Callee taking a 1717/// internal::Matcher<Decl>, as the matcher hierarchy is purely 1718/// implemented in terms of implicit casts. 1719AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>, 1720 InnerMatcher) { 1721 const Expr *ExprNode = Node.getCallee(); 1722 return (ExprNode != NULL && 1723 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1724} 1725 1726/// \brief Matches if the call expression's callee's declaration matches the 1727/// given matcher. 1728/// 1729/// Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x"))))) 1730/// \code 1731/// class Y { public: void x(); }; 1732/// void z() { Y y; y.x(); 1733/// \endcode 1734AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher, 1735 1) { 1736 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder); 1737} 1738 1739/// \brief Matches if the expression's or declaration's type matches a type 1740/// matcher. 1741/// 1742/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) 1743/// and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) 1744/// \code 1745/// class X {}; 1746/// void y(X &x) { x; X z; } 1747/// \endcode 1748AST_POLYMORPHIC_MATCHER_P_OVERLOAD( 1749 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES_2(Expr, ValueDecl), 1750 internal::Matcher<QualType>, InnerMatcher, 0) { 1751 return InnerMatcher.matches(Node.getType(), Finder, Builder); 1752} 1753 1754/// \brief Overloaded to match the declaration of the expression's or value 1755/// declaration's type. 1756/// 1757/// In case of a value declaration (for example a variable declaration), 1758/// this resolves one layer of indirection. For example, in the value 1759/// declaration "X x;", recordDecl(hasName("X")) matches the declaration of X, 1760/// while varDecl(hasType(recordDecl(hasName("X")))) matches the declaration 1761/// of x." 1762/// 1763/// Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) 1764/// and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) 1765/// \code 1766/// class X {}; 1767/// void y(X &x) { x; X z; } 1768/// \endcode 1769/// 1770/// Usable as: Matcher<Expr>, Matcher<ValueDecl> 1771AST_POLYMORPHIC_MATCHER_P_OVERLOAD( 1772 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES_2(Expr, ValueDecl), 1773 internal::Matcher<Decl>, InnerMatcher, 1) { 1774 return qualType(hasDeclaration(InnerMatcher)) 1775 .matches(Node.getType(), Finder, Builder); 1776} 1777 1778/// \brief Matches if the type location of the declarator decl's type matches 1779/// the inner matcher. 1780/// 1781/// Given 1782/// \code 1783/// int x; 1784/// \endcode 1785/// declaratorDecl(hasTypeLoc(loc(asString("int")))) 1786/// matches int x 1787AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) { 1788 if (!Node.getTypeSourceInfo()) 1789 // This happens for example for implicit destructors. 1790 return false; 1791 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder); 1792} 1793 1794/// \brief Matches if the matched type is represented by the given string. 1795/// 1796/// Given 1797/// \code 1798/// class Y { public: void x(); }; 1799/// void z() { Y* y; y->x(); } 1800/// \endcode 1801/// callExpr(on(hasType(asString("class Y *")))) 1802/// matches y->x() 1803AST_MATCHER_P(QualType, asString, std::string, Name) { 1804 return Name == Node.getAsString(); 1805} 1806 1807/// \brief Matches if the matched type is a pointer type and the pointee type 1808/// matches the specified matcher. 1809/// 1810/// Example matches y->x() 1811/// (matcher = callExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))))) 1812/// \code 1813/// class Y { public: void x(); }; 1814/// void z() { Y *y; y->x(); } 1815/// \endcode 1816AST_MATCHER_P( 1817 QualType, pointsTo, internal::Matcher<QualType>, 1818 InnerMatcher) { 1819 return (!Node.isNull() && Node->isPointerType() && 1820 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1821} 1822 1823/// \brief Overloaded to match the pointee type's declaration. 1824AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>, 1825 InnerMatcher, 1) { 1826 return pointsTo(qualType(hasDeclaration(InnerMatcher))) 1827 .matches(Node, Finder, Builder); 1828} 1829 1830/// \brief Matches if the matched type is a reference type and the referenced 1831/// type matches the specified matcher. 1832/// 1833/// Example matches X &x and const X &y 1834/// (matcher = varDecl(hasType(references(recordDecl(hasName("X")))))) 1835/// \code 1836/// class X { 1837/// void a(X b) { 1838/// X &x = b; 1839/// const X &y = b; 1840/// }; 1841/// \endcode 1842AST_MATCHER_P(QualType, references, internal::Matcher<QualType>, 1843 InnerMatcher) { 1844 return (!Node.isNull() && Node->isReferenceType() && 1845 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1846} 1847 1848/// \brief Matches QualTypes whose canonical type matches InnerMatcher. 1849/// 1850/// Given: 1851/// \code 1852/// typedef int &int_ref; 1853/// int a; 1854/// int_ref b = a; 1855/// \code 1856/// 1857/// \c varDecl(hasType(qualType(referenceType()))))) will not match the 1858/// declaration of b but \c 1859/// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does. 1860AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>, 1861 InnerMatcher) { 1862 if (Node.isNull()) 1863 return false; 1864 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder); 1865} 1866 1867/// \brief Overloaded to match the referenced type's declaration. 1868AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>, 1869 InnerMatcher, 1) { 1870 return references(qualType(hasDeclaration(InnerMatcher))) 1871 .matches(Node, Finder, Builder); 1872} 1873 1874AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument, 1875 internal::Matcher<Expr>, InnerMatcher) { 1876 const Expr *ExprNode = Node.getImplicitObjectArgument(); 1877 return (ExprNode != NULL && 1878 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1879} 1880 1881/// \brief Matches if the expression's type either matches the specified 1882/// matcher, or is a pointer to a type that matches the InnerMatcher. 1883AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType, 1884 internal::Matcher<QualType>, InnerMatcher, 0) { 1885 return onImplicitObjectArgument( 1886 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))) 1887 .matches(Node, Finder, Builder); 1888} 1889 1890/// \brief Overloaded to match the type's declaration. 1891AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType, 1892 internal::Matcher<Decl>, InnerMatcher, 1) { 1893 return onImplicitObjectArgument( 1894 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))) 1895 .matches(Node, Finder, Builder); 1896} 1897 1898/// \brief Matches a DeclRefExpr that refers to a declaration that matches the 1899/// specified matcher. 1900/// 1901/// Example matches x in if(x) 1902/// (matcher = declRefExpr(to(varDecl(hasName("x"))))) 1903/// \code 1904/// bool x; 1905/// if (x) {} 1906/// \endcode 1907AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>, 1908 InnerMatcher) { 1909 const Decl *DeclNode = Node.getDecl(); 1910 return (DeclNode != NULL && 1911 InnerMatcher.matches(*DeclNode, Finder, Builder)); 1912} 1913 1914/// \brief Matches a \c DeclRefExpr that refers to a declaration through a 1915/// specific using shadow declaration. 1916/// 1917/// FIXME: This currently only works for functions. Fix. 1918/// 1919/// Given 1920/// \code 1921/// namespace a { void f() {} } 1922/// using a::f; 1923/// void g() { 1924/// f(); // Matches this .. 1925/// a::f(); // .. but not this. 1926/// } 1927/// \endcode 1928/// declRefExpr(throughUsingDeclaration(anything())) 1929/// matches \c f() 1930AST_MATCHER_P(DeclRefExpr, throughUsingDecl, 1931 internal::Matcher<UsingShadowDecl>, InnerMatcher) { 1932 const NamedDecl *FoundDecl = Node.getFoundDecl(); 1933 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl)) 1934 return InnerMatcher.matches(*UsingDecl, Finder, Builder); 1935 return false; 1936} 1937 1938/// \brief Matches the Decl of a DeclStmt which has a single declaration. 1939/// 1940/// Given 1941/// \code 1942/// int a, b; 1943/// int c; 1944/// \endcode 1945/// declStmt(hasSingleDecl(anything())) 1946/// matches 'int c;' but not 'int a, b;'. 1947AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) { 1948 if (Node.isSingleDecl()) { 1949 const Decl *FoundDecl = Node.getSingleDecl(); 1950 return InnerMatcher.matches(*FoundDecl, Finder, Builder); 1951 } 1952 return false; 1953} 1954 1955/// \brief Matches a variable declaration that has an initializer expression 1956/// that matches the given matcher. 1957/// 1958/// Example matches x (matcher = varDecl(hasInitializer(callExpr()))) 1959/// \code 1960/// bool y() { return true; } 1961/// bool x = y(); 1962/// \endcode 1963AST_MATCHER_P( 1964 VarDecl, hasInitializer, internal::Matcher<Expr>, 1965 InnerMatcher) { 1966 const Expr *Initializer = Node.getAnyInitializer(); 1967 return (Initializer != NULL && 1968 InnerMatcher.matches(*Initializer, Finder, Builder)); 1969} 1970 1971/// \brief Checks that a call expression or a constructor call expression has 1972/// a specific number of arguments (including absent default arguments). 1973/// 1974/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2))) 1975/// \code 1976/// void f(int x, int y); 1977/// f(0, 0); 1978/// \endcode 1979AST_POLYMORPHIC_MATCHER_P(argumentCountIs, AST_POLYMORPHIC_SUPPORTED_TYPES_2( 1980 CallExpr, CXXConstructExpr), 1981 unsigned, N) { 1982 return Node.getNumArgs() == N; 1983} 1984 1985/// \brief Matches the n'th argument of a call expression or a constructor 1986/// call expression. 1987/// 1988/// Example matches y in x(y) 1989/// (matcher = callExpr(hasArgument(0, declRefExpr()))) 1990/// \code 1991/// void x(int) { int y; x(y); } 1992/// \endcode 1993AST_POLYMORPHIC_MATCHER_P2( 1994 hasArgument, 1995 AST_POLYMORPHIC_SUPPORTED_TYPES_2(CallExpr, CXXConstructExpr), 1996 unsigned, N, internal::Matcher<Expr>, InnerMatcher) { 1997 return (N < Node.getNumArgs() && 1998 InnerMatcher.matches( 1999 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder)); 2000} 2001 2002/// \brief Matches declaration statements that contain a specific number of 2003/// declarations. 2004/// 2005/// Example: Given 2006/// \code 2007/// int a, b; 2008/// int c; 2009/// int d = 2, e; 2010/// \endcode 2011/// declCountIs(2) 2012/// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'. 2013AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) { 2014 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N; 2015} 2016 2017/// \brief Matches the n'th declaration of a declaration statement. 2018/// 2019/// Note that this does not work for global declarations because the AST 2020/// breaks up multiple-declaration DeclStmt's into multiple single-declaration 2021/// DeclStmt's. 2022/// Example: Given non-global declarations 2023/// \code 2024/// int a, b = 0; 2025/// int c; 2026/// int d = 2, e; 2027/// \endcode 2028/// declStmt(containsDeclaration( 2029/// 0, varDecl(hasInitializer(anything())))) 2030/// matches only 'int d = 2, e;', and 2031/// declStmt(containsDeclaration(1, varDecl())) 2032/// \code 2033/// matches 'int a, b = 0' as well as 'int d = 2, e;' 2034/// but 'int c;' is not matched. 2035/// \endcode 2036AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N, 2037 internal::Matcher<Decl>, InnerMatcher) { 2038 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end()); 2039 if (N >= NumDecls) 2040 return false; 2041 DeclStmt::const_decl_iterator Iterator = Node.decl_begin(); 2042 std::advance(Iterator, N); 2043 return InnerMatcher.matches(**Iterator, Finder, Builder); 2044} 2045 2046/// \brief Matches a constructor initializer. 2047/// 2048/// Given 2049/// \code 2050/// struct Foo { 2051/// Foo() : foo_(1) { } 2052/// int foo_; 2053/// }; 2054/// \endcode 2055/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything())))) 2056/// record matches Foo, hasAnyConstructorInitializer matches foo_(1) 2057AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer, 2058 internal::Matcher<CXXCtorInitializer>, InnerMatcher) { 2059 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(), 2060 Node.init_end(), Finder, Builder); 2061} 2062 2063/// \brief Matches the field declaration of a constructor initializer. 2064/// 2065/// Given 2066/// \code 2067/// struct Foo { 2068/// Foo() : foo_(1) { } 2069/// int foo_; 2070/// }; 2071/// \endcode 2072/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer( 2073/// forField(hasName("foo_")))))) 2074/// matches Foo 2075/// with forField matching foo_ 2076AST_MATCHER_P(CXXCtorInitializer, forField, 2077 internal::Matcher<FieldDecl>, InnerMatcher) { 2078 const FieldDecl *NodeAsDecl = Node.getMember(); 2079 return (NodeAsDecl != NULL && 2080 InnerMatcher.matches(*NodeAsDecl, Finder, Builder)); 2081} 2082 2083/// \brief Matches the initializer expression of a constructor initializer. 2084/// 2085/// Given 2086/// \code 2087/// struct Foo { 2088/// Foo() : foo_(1) { } 2089/// int foo_; 2090/// }; 2091/// \endcode 2092/// recordDecl(has(constructorDecl(hasAnyConstructorInitializer( 2093/// withInitializer(integerLiteral(equals(1))))))) 2094/// matches Foo 2095/// with withInitializer matching (1) 2096AST_MATCHER_P(CXXCtorInitializer, withInitializer, 2097 internal::Matcher<Expr>, InnerMatcher) { 2098 const Expr* NodeAsExpr = Node.getInit(); 2099 return (NodeAsExpr != NULL && 2100 InnerMatcher.matches(*NodeAsExpr, Finder, Builder)); 2101} 2102 2103/// \brief Matches a contructor initializer if it is explicitly written in 2104/// code (as opposed to implicitly added by the compiler). 2105/// 2106/// Given 2107/// \code 2108/// struct Foo { 2109/// Foo() { } 2110/// Foo(int) : foo_("A") { } 2111/// string foo_; 2112/// }; 2113/// \endcode 2114/// constructorDecl(hasAnyConstructorInitializer(isWritten())) 2115/// will match Foo(int), but not Foo() 2116AST_MATCHER(CXXCtorInitializer, isWritten) { 2117 return Node.isWritten(); 2118} 2119 2120/// \brief Matches a constructor declaration that has been implicitly added 2121/// by the compiler (eg. implicit default/copy constructors). 2122AST_MATCHER(CXXConstructorDecl, isImplicit) { 2123 return Node.isImplicit(); 2124} 2125 2126/// \brief Matches any argument of a call expression or a constructor call 2127/// expression. 2128/// 2129/// Given 2130/// \code 2131/// void x(int, int, int) { int y; x(1, y, 42); } 2132/// \endcode 2133/// callExpr(hasAnyArgument(declRefExpr())) 2134/// matches x(1, y, 42) 2135/// with hasAnyArgument(...) 2136/// matching y 2137/// 2138/// FIXME: Currently this will ignore parentheses and implicit casts on 2139/// the argument before applying the inner matcher. We'll want to remove 2140/// this to allow for greater control by the user once \c ignoreImplicit() 2141/// has been implemented. 2142AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, AST_POLYMORPHIC_SUPPORTED_TYPES_2( 2143 CallExpr, CXXConstructExpr), 2144 internal::Matcher<Expr>, InnerMatcher) { 2145 for (unsigned I = 0; I < Node.getNumArgs(); ++I) { 2146 BoundNodesTreeBuilder Result(*Builder); 2147 if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(), Finder, 2148 &Result)) { 2149 *Builder = Result; 2150 return true; 2151 } 2152 } 2153 return false; 2154} 2155 2156/// \brief Matches the n'th parameter of a function declaration. 2157/// 2158/// Given 2159/// \code 2160/// class X { void f(int x) {} }; 2161/// \endcode 2162/// methodDecl(hasParameter(0, hasType(varDecl()))) 2163/// matches f(int x) {} 2164/// with hasParameter(...) 2165/// matching int x 2166AST_MATCHER_P2(FunctionDecl, hasParameter, 2167 unsigned, N, internal::Matcher<ParmVarDecl>, 2168 InnerMatcher) { 2169 return (N < Node.getNumParams() && 2170 InnerMatcher.matches( 2171 *Node.getParamDecl(N), Finder, Builder)); 2172} 2173 2174/// \brief Matches any parameter of a function declaration. 2175/// 2176/// Does not match the 'this' parameter of a method. 2177/// 2178/// Given 2179/// \code 2180/// class X { void f(int x, int y, int z) {} }; 2181/// \endcode 2182/// methodDecl(hasAnyParameter(hasName("y"))) 2183/// matches f(int x, int y, int z) {} 2184/// with hasAnyParameter(...) 2185/// matching int y 2186AST_MATCHER_P(FunctionDecl, hasAnyParameter, 2187 internal::Matcher<ParmVarDecl>, InnerMatcher) { 2188 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(), 2189 Node.param_end(), Finder, Builder); 2190} 2191 2192/// \brief Matches \c FunctionDecls that have a specific parameter count. 2193/// 2194/// Given 2195/// \code 2196/// void f(int i) {} 2197/// void g(int i, int j) {} 2198/// \endcode 2199/// functionDecl(parameterCountIs(2)) 2200/// matches g(int i, int j) {} 2201AST_MATCHER_P(FunctionDecl, parameterCountIs, unsigned, N) { 2202 return Node.getNumParams() == N; 2203} 2204 2205/// \brief Matches the return type of a function declaration. 2206/// 2207/// Given: 2208/// \code 2209/// class X { int f() { return 1; } }; 2210/// \endcode 2211/// methodDecl(returns(asString("int"))) 2212/// matches int f() { return 1; } 2213AST_MATCHER_P(FunctionDecl, returns, 2214 internal::Matcher<QualType>, InnerMatcher) { 2215 return InnerMatcher.matches(Node.getResultType(), Finder, Builder); 2216} 2217 2218/// \brief Matches extern "C" function declarations. 2219/// 2220/// Given: 2221/// \code 2222/// extern "C" void f() {} 2223/// extern "C" { void g() {} } 2224/// void h() {} 2225/// \endcode 2226/// functionDecl(isExternC()) 2227/// matches the declaration of f and g, but not the declaration h 2228AST_MATCHER(FunctionDecl, isExternC) { 2229 return Node.isExternC(); 2230} 2231 2232/// \brief Matches the condition expression of an if statement, for loop, 2233/// or conditional operator. 2234/// 2235/// Example matches true (matcher = hasCondition(boolLiteral(equals(true)))) 2236/// \code 2237/// if (true) {} 2238/// \endcode 2239AST_POLYMORPHIC_MATCHER_P( 2240 hasCondition, AST_POLYMORPHIC_SUPPORTED_TYPES_5( 2241 IfStmt, ForStmt, WhileStmt, DoStmt, ConditionalOperator), 2242 internal::Matcher<Expr>, InnerMatcher) { 2243 const Expr *const Condition = Node.getCond(); 2244 return (Condition != NULL && 2245 InnerMatcher.matches(*Condition, Finder, Builder)); 2246} 2247 2248namespace internal { 2249struct NotEqualsBoundNodePredicate { 2250 bool operator()(const internal::BoundNodesMap &Nodes) const { 2251 return Nodes.getNode(ID) != Node; 2252 } 2253 std::string ID; 2254 ast_type_traits::DynTypedNode Node; 2255}; 2256} // namespace internal 2257 2258/// \brief Matches if a node equals a previously bound node. 2259/// 2260/// Matches a node if it equals the node previously bound to \p ID. 2261/// 2262/// Given 2263/// \code 2264/// class X { int a; int b; }; 2265/// \endcode 2266/// recordDecl( 2267/// has(fieldDecl(hasName("a"), hasType(type().bind("t")))), 2268/// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t")))))) 2269/// matches the class \c X, as \c a and \c b have the same type. 2270/// 2271/// Note that when multiple matches are involved via \c forEach* matchers, 2272/// \c equalsBoundNodes acts as a filter. 2273/// For example: 2274/// compoundStmt( 2275/// forEachDescendant(varDecl().bind("d")), 2276/// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))) 2277/// will trigger a match for each combination of variable declaration 2278/// and reference to that variable declaration within a compound statement. 2279AST_POLYMORPHIC_MATCHER_P(equalsBoundNode, AST_POLYMORPHIC_SUPPORTED_TYPES_4( 2280 Stmt, Decl, Type, QualType), 2281 std::string, ID) { 2282 // FIXME: Figure out whether it makes sense to allow this 2283 // on any other node types. 2284 // For *Loc it probably does not make sense, as those seem 2285 // unique. For NestedNameSepcifier it might make sense, as 2286 // those also have pointer identity, but I'm not sure whether 2287 // they're ever reused. 2288 internal::NotEqualsBoundNodePredicate Predicate; 2289 Predicate.ID = ID; 2290 Predicate.Node = ast_type_traits::DynTypedNode::create(Node); 2291 return Builder->removeBindings(Predicate); 2292} 2293 2294/// \brief Matches the condition variable statement in an if statement. 2295/// 2296/// Given 2297/// \code 2298/// if (A* a = GetAPointer()) {} 2299/// \endcode 2300/// hasConditionVariableStatment(...) 2301/// matches 'A* a = GetAPointer()'. 2302AST_MATCHER_P(IfStmt, hasConditionVariableStatement, 2303 internal::Matcher<DeclStmt>, InnerMatcher) { 2304 const DeclStmt* const DeclarationStatement = 2305 Node.getConditionVariableDeclStmt(); 2306 return DeclarationStatement != NULL && 2307 InnerMatcher.matches(*DeclarationStatement, Finder, Builder); 2308} 2309 2310/// \brief Matches the index expression of an array subscript expression. 2311/// 2312/// Given 2313/// \code 2314/// int i[5]; 2315/// void f() { i[1] = 42; } 2316/// \endcode 2317/// arraySubscriptExpression(hasIndex(integerLiteral())) 2318/// matches \c i[1] with the \c integerLiteral() matching \c 1 2319AST_MATCHER_P(ArraySubscriptExpr, hasIndex, 2320 internal::Matcher<Expr>, InnerMatcher) { 2321 if (const Expr* Expression = Node.getIdx()) 2322 return InnerMatcher.matches(*Expression, Finder, Builder); 2323 return false; 2324} 2325 2326/// \brief Matches the base expression of an array subscript expression. 2327/// 2328/// Given 2329/// \code 2330/// int i[5]; 2331/// void f() { i[1] = 42; } 2332/// \endcode 2333/// arraySubscriptExpression(hasBase(implicitCastExpr( 2334/// hasSourceExpression(declRefExpr())))) 2335/// matches \c i[1] with the \c declRefExpr() matching \c i 2336AST_MATCHER_P(ArraySubscriptExpr, hasBase, 2337 internal::Matcher<Expr>, InnerMatcher) { 2338 if (const Expr* Expression = Node.getBase()) 2339 return InnerMatcher.matches(*Expression, Finder, Builder); 2340 return false; 2341} 2342 2343/// \brief Matches a 'for', 'while', or 'do while' statement that has 2344/// a given body. 2345/// 2346/// Given 2347/// \code 2348/// for (;;) {} 2349/// \endcode 2350/// hasBody(compoundStmt()) 2351/// matches 'for (;;) {}' 2352/// with compoundStmt() 2353/// matching '{}' 2354AST_POLYMORPHIC_MATCHER_P( 2355 hasBody, AST_POLYMORPHIC_SUPPORTED_TYPES_3(DoStmt, ForStmt, WhileStmt), 2356 internal::Matcher<Stmt>, InnerMatcher) { 2357 const Stmt *const Statement = Node.getBody(); 2358 return (Statement != NULL && 2359 InnerMatcher.matches(*Statement, Finder, Builder)); 2360} 2361 2362/// \brief Matches compound statements where at least one substatement matches 2363/// a given matcher. 2364/// 2365/// Given 2366/// \code 2367/// { {}; 1+2; } 2368/// \endcode 2369/// hasAnySubstatement(compoundStmt()) 2370/// matches '{ {}; 1+2; }' 2371/// with compoundStmt() 2372/// matching '{}' 2373AST_MATCHER_P(CompoundStmt, hasAnySubstatement, 2374 internal::Matcher<Stmt>, InnerMatcher) { 2375 return matchesFirstInPointerRange(InnerMatcher, Node.body_begin(), 2376 Node.body_end(), Finder, Builder); 2377} 2378 2379/// \brief Checks that a compound statement contains a specific number of 2380/// child statements. 2381/// 2382/// Example: Given 2383/// \code 2384/// { for (;;) {} } 2385/// \endcode 2386/// compoundStmt(statementCountIs(0))) 2387/// matches '{}' 2388/// but does not match the outer compound statement. 2389AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) { 2390 return Node.size() == N; 2391} 2392 2393/// \brief Matches literals that are equal to the given value. 2394/// 2395/// Example matches true (matcher = boolLiteral(equals(true))) 2396/// \code 2397/// true 2398/// \endcode 2399/// 2400/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>, 2401/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral> 2402template <typename ValueT> 2403internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT> 2404equals(const ValueT &Value) { 2405 return internal::PolymorphicMatcherWithParam1< 2406 internal::ValueEqualsMatcher, 2407 ValueT>(Value); 2408} 2409 2410/// \brief Matches the operator Name of operator expressions (binary or 2411/// unary). 2412/// 2413/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||"))) 2414/// \code 2415/// !(a || b) 2416/// \endcode 2417AST_POLYMORPHIC_MATCHER_P(hasOperatorName, AST_POLYMORPHIC_SUPPORTED_TYPES_2( 2418 BinaryOperator, UnaryOperator), 2419 std::string, Name) { 2420 return Name == Node.getOpcodeStr(Node.getOpcode()); 2421} 2422 2423/// \brief Matches the left hand side of binary operator expressions. 2424/// 2425/// Example matches a (matcher = binaryOperator(hasLHS())) 2426/// \code 2427/// a || b 2428/// \endcode 2429AST_MATCHER_P(BinaryOperator, hasLHS, 2430 internal::Matcher<Expr>, InnerMatcher) { 2431 Expr *LeftHandSide = Node.getLHS(); 2432 return (LeftHandSide != NULL && 2433 InnerMatcher.matches(*LeftHandSide, Finder, Builder)); 2434} 2435 2436/// \brief Matches the right hand side of binary operator expressions. 2437/// 2438/// Example matches b (matcher = binaryOperator(hasRHS())) 2439/// \code 2440/// a || b 2441/// \endcode 2442AST_MATCHER_P(BinaryOperator, hasRHS, 2443 internal::Matcher<Expr>, InnerMatcher) { 2444 Expr *RightHandSide = Node.getRHS(); 2445 return (RightHandSide != NULL && 2446 InnerMatcher.matches(*RightHandSide, Finder, Builder)); 2447} 2448 2449/// \brief Matches if either the left hand side or the right hand side of a 2450/// binary operator matches. 2451inline internal::Matcher<BinaryOperator> hasEitherOperand( 2452 const internal::Matcher<Expr> &InnerMatcher) { 2453 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)); 2454} 2455 2456/// \brief Matches if the operand of a unary operator matches. 2457/// 2458/// Example matches true (matcher = hasUnaryOperand(boolLiteral(equals(true)))) 2459/// \code 2460/// !true 2461/// \endcode 2462AST_MATCHER_P(UnaryOperator, hasUnaryOperand, 2463 internal::Matcher<Expr>, InnerMatcher) { 2464 const Expr * const Operand = Node.getSubExpr(); 2465 return (Operand != NULL && 2466 InnerMatcher.matches(*Operand, Finder, Builder)); 2467} 2468 2469/// \brief Matches if the cast's source expression matches the given matcher. 2470/// 2471/// Example: matches "a string" (matcher = 2472/// hasSourceExpression(constructExpr())) 2473/// \code 2474/// class URL { URL(string); }; 2475/// URL url = "a string"; 2476AST_MATCHER_P(CastExpr, hasSourceExpression, 2477 internal::Matcher<Expr>, InnerMatcher) { 2478 const Expr* const SubExpression = Node.getSubExpr(); 2479 return (SubExpression != NULL && 2480 InnerMatcher.matches(*SubExpression, Finder, Builder)); 2481} 2482 2483/// \brief Matches casts whose destination type matches a given matcher. 2484/// 2485/// (Note: Clang's AST refers to other conversions as "casts" too, and calls 2486/// actual casts "explicit" casts.) 2487AST_MATCHER_P(ExplicitCastExpr, hasDestinationType, 2488 internal::Matcher<QualType>, InnerMatcher) { 2489 const QualType NodeType = Node.getTypeAsWritten(); 2490 return InnerMatcher.matches(NodeType, Finder, Builder); 2491} 2492 2493/// \brief Matches implicit casts whose destination type matches a given 2494/// matcher. 2495/// 2496/// FIXME: Unit test this matcher 2497AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType, 2498 internal::Matcher<QualType>, InnerMatcher) { 2499 return InnerMatcher.matches(Node.getType(), Finder, Builder); 2500} 2501 2502/// \brief Matches the true branch expression of a conditional operator. 2503/// 2504/// Example matches a 2505/// \code 2506/// condition ? a : b 2507/// \endcode 2508AST_MATCHER_P(ConditionalOperator, hasTrueExpression, 2509 internal::Matcher<Expr>, InnerMatcher) { 2510 Expr *Expression = Node.getTrueExpr(); 2511 return (Expression != NULL && 2512 InnerMatcher.matches(*Expression, Finder, Builder)); 2513} 2514 2515/// \brief Matches the false branch expression of a conditional operator. 2516/// 2517/// Example matches b 2518/// \code 2519/// condition ? a : b 2520/// \endcode 2521AST_MATCHER_P(ConditionalOperator, hasFalseExpression, 2522 internal::Matcher<Expr>, InnerMatcher) { 2523 Expr *Expression = Node.getFalseExpr(); 2524 return (Expression != NULL && 2525 InnerMatcher.matches(*Expression, Finder, Builder)); 2526} 2527 2528/// \brief Matches if a declaration has a body attached. 2529/// 2530/// Example matches A, va, fa 2531/// \code 2532/// class A {}; 2533/// class B; // Doesn't match, as it has no body. 2534/// int va; 2535/// extern int vb; // Doesn't match, as it doesn't define the variable. 2536/// void fa() {} 2537/// void fb(); // Doesn't match, as it has no body. 2538/// \endcode 2539/// 2540/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl> 2541AST_POLYMORPHIC_MATCHER(isDefinition, AST_POLYMORPHIC_SUPPORTED_TYPES_3( 2542 TagDecl, VarDecl, FunctionDecl)) { 2543 return Node.isThisDeclarationADefinition(); 2544} 2545 2546/// \brief Matches the class declaration that the given method declaration 2547/// belongs to. 2548/// 2549/// FIXME: Generalize this for other kinds of declarations. 2550/// FIXME: What other kind of declarations would we need to generalize 2551/// this to? 2552/// 2553/// Example matches A() in the last line 2554/// (matcher = constructExpr(hasDeclaration(methodDecl( 2555/// ofClass(hasName("A")))))) 2556/// \code 2557/// class A { 2558/// public: 2559/// A(); 2560/// }; 2561/// A a = A(); 2562/// \endcode 2563AST_MATCHER_P(CXXMethodDecl, ofClass, 2564 internal::Matcher<CXXRecordDecl>, InnerMatcher) { 2565 const CXXRecordDecl *Parent = Node.getParent(); 2566 return (Parent != NULL && 2567 InnerMatcher.matches(*Parent, Finder, Builder)); 2568} 2569 2570/// \brief Matches if the given method declaration is virtual. 2571/// 2572/// Given 2573/// \code 2574/// class A { 2575/// public: 2576/// virtual void x(); 2577/// }; 2578/// \endcode 2579/// matches A::x 2580AST_MATCHER(CXXMethodDecl, isVirtual) { 2581 return Node.isVirtual(); 2582} 2583 2584/// \brief Matches if the given method declaration is const. 2585/// 2586/// Given 2587/// \code 2588/// struct A { 2589/// void foo() const; 2590/// void bar(); 2591/// }; 2592/// \endcode 2593/// 2594/// methodDecl(isConst()) matches A::foo() but not A::bar() 2595AST_MATCHER(CXXMethodDecl, isConst) { 2596 return Node.isConst(); 2597} 2598 2599/// \brief Matches if the given method declaration overrides another method. 2600/// 2601/// Given 2602/// \code 2603/// class A { 2604/// public: 2605/// virtual void x(); 2606/// }; 2607/// class B : public A { 2608/// public: 2609/// virtual void x(); 2610/// }; 2611/// \endcode 2612/// matches B::x 2613AST_MATCHER(CXXMethodDecl, isOverride) { 2614 return Node.size_overridden_methods() > 0; 2615} 2616 2617/// \brief Matches member expressions that are called with '->' as opposed 2618/// to '.'. 2619/// 2620/// Member calls on the implicit this pointer match as called with '->'. 2621/// 2622/// Given 2623/// \code 2624/// class Y { 2625/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 2626/// int a; 2627/// static int b; 2628/// }; 2629/// \endcode 2630/// memberExpr(isArrow()) 2631/// matches this->x, x, y.x, a, this->b 2632AST_MATCHER(MemberExpr, isArrow) { 2633 return Node.isArrow(); 2634} 2635 2636/// \brief Matches QualType nodes that are of integer type. 2637/// 2638/// Given 2639/// \code 2640/// void a(int); 2641/// void b(long); 2642/// void c(double); 2643/// \endcode 2644/// functionDecl(hasAnyParameter(hasType(isInteger()))) 2645/// matches "a(int)", "b(long)", but not "c(double)". 2646AST_MATCHER(QualType, isInteger) { 2647 return Node->isIntegerType(); 2648} 2649 2650/// \brief Matches QualType nodes that are const-qualified, i.e., that 2651/// include "top-level" const. 2652/// 2653/// Given 2654/// \code 2655/// void a(int); 2656/// void b(int const); 2657/// void c(const int); 2658/// void d(const int*); 2659/// void e(int const) {}; 2660/// \endcode 2661/// functionDecl(hasAnyParameter(hasType(isConstQualified()))) 2662/// matches "void b(int const)", "void c(const int)" and 2663/// "void e(int const) {}". It does not match d as there 2664/// is no top-level const on the parameter type "const int *". 2665AST_MATCHER(QualType, isConstQualified) { 2666 return Node.isConstQualified(); 2667} 2668 2669/// \brief Matches QualType nodes that have local CV-qualifiers attached to 2670/// the node, not hidden within a typedef. 2671/// 2672/// Given 2673/// \code 2674/// typedef const int const_int; 2675/// const_int i; 2676/// int *const j; 2677/// int *volatile k; 2678/// int m; 2679/// \endcode 2680/// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k. 2681/// \c i is const-qualified but the qualifier is not local. 2682AST_MATCHER(QualType, hasLocalQualifiers) { 2683 return Node.hasLocalQualifiers(); 2684} 2685 2686/// \brief Matches a member expression where the member is matched by a 2687/// given matcher. 2688/// 2689/// Given 2690/// \code 2691/// struct { int first, second; } first, second; 2692/// int i(second.first); 2693/// int j(first.second); 2694/// \endcode 2695/// memberExpr(member(hasName("first"))) 2696/// matches second.first 2697/// but not first.second (because the member name there is "second"). 2698AST_MATCHER_P(MemberExpr, member, 2699 internal::Matcher<ValueDecl>, InnerMatcher) { 2700 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder); 2701} 2702 2703/// \brief Matches a member expression where the object expression is 2704/// matched by a given matcher. 2705/// 2706/// Given 2707/// \code 2708/// struct X { int m; }; 2709/// void f(X x) { x.m; m; } 2710/// \endcode 2711/// memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X"))))))) 2712/// matches "x.m" and "m" 2713/// with hasObjectExpression(...) 2714/// matching "x" and the implicit object expression of "m" which has type X*. 2715AST_MATCHER_P(MemberExpr, hasObjectExpression, 2716 internal::Matcher<Expr>, InnerMatcher) { 2717 return InnerMatcher.matches(*Node.getBase(), Finder, Builder); 2718} 2719 2720/// \brief Matches any using shadow declaration. 2721/// 2722/// Given 2723/// \code 2724/// namespace X { void b(); } 2725/// using X::b; 2726/// \endcode 2727/// usingDecl(hasAnyUsingShadowDecl(hasName("b")))) 2728/// matches \code using X::b \endcode 2729AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl, 2730 internal::Matcher<UsingShadowDecl>, InnerMatcher) { 2731 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(), 2732 Node.shadow_end(), Finder, Builder); 2733} 2734 2735/// \brief Matches a using shadow declaration where the target declaration is 2736/// matched by the given matcher. 2737/// 2738/// Given 2739/// \code 2740/// namespace X { int a; void b(); } 2741/// using X::a; 2742/// using X::b; 2743/// \endcode 2744/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl()))) 2745/// matches \code using X::b \endcode 2746/// but not \code using X::a \endcode 2747AST_MATCHER_P(UsingShadowDecl, hasTargetDecl, 2748 internal::Matcher<NamedDecl>, InnerMatcher) { 2749 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder); 2750} 2751 2752/// \brief Matches template instantiations of function, class, or static 2753/// member variable template instantiations. 2754/// 2755/// Given 2756/// \code 2757/// template <typename T> class X {}; class A {}; X<A> x; 2758/// \endcode 2759/// or 2760/// \code 2761/// template <typename T> class X {}; class A {}; template class X<A>; 2762/// \endcode 2763/// recordDecl(hasName("::X"), isTemplateInstantiation()) 2764/// matches the template instantiation of X<A>. 2765/// 2766/// But given 2767/// \code 2768/// template <typename T> class X {}; class A {}; 2769/// template <> class X<A> {}; X<A> x; 2770/// \endcode 2771/// recordDecl(hasName("::X"), isTemplateInstantiation()) 2772/// does not match, as X<A> is an explicit template specialization. 2773/// 2774/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> 2775AST_POLYMORPHIC_MATCHER( 2776 isTemplateInstantiation, 2777 AST_POLYMORPHIC_SUPPORTED_TYPES_3(FunctionDecl, VarDecl, CXXRecordDecl)) { 2778 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation || 2779 Node.getTemplateSpecializationKind() == 2780 TSK_ExplicitInstantiationDefinition); 2781} 2782 2783/// \brief Matches explicit template specializations of function, class, or 2784/// static member variable template instantiations. 2785/// 2786/// Given 2787/// \code 2788/// template<typename T> void A(T t) { } 2789/// template<> void A(int N) { } 2790/// \endcode 2791/// functionDecl(isExplicitTemplateSpecialization()) 2792/// matches the specialization A<int>(). 2793/// 2794/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> 2795AST_POLYMORPHIC_MATCHER( 2796 isExplicitTemplateSpecialization, 2797 AST_POLYMORPHIC_SUPPORTED_TYPES_3(FunctionDecl, VarDecl, CXXRecordDecl)) { 2798 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization); 2799} 2800 2801/// \brief Matches \c TypeLocs for which the given inner 2802/// QualType-matcher matches. 2803inline internal::BindableMatcher<TypeLoc> loc( 2804 const internal::Matcher<QualType> &InnerMatcher) { 2805 return internal::BindableMatcher<TypeLoc>( 2806 new internal::TypeLocTypeMatcher(InnerMatcher)); 2807} 2808 2809/// \brief Matches builtin Types. 2810/// 2811/// Given 2812/// \code 2813/// struct A {}; 2814/// A a; 2815/// int b; 2816/// float c; 2817/// bool d; 2818/// \endcode 2819/// builtinType() 2820/// matches "int b", "float c" and "bool d" 2821AST_TYPE_MATCHER(BuiltinType, builtinType); 2822 2823/// \brief Matches all kinds of arrays. 2824/// 2825/// Given 2826/// \code 2827/// int a[] = { 2, 3 }; 2828/// int b[4]; 2829/// void f() { int c[a[0]]; } 2830/// \endcode 2831/// arrayType() 2832/// matches "int a[]", "int b[4]" and "int c[a[0]]"; 2833AST_TYPE_MATCHER(ArrayType, arrayType); 2834 2835/// \brief Matches C99 complex types. 2836/// 2837/// Given 2838/// \code 2839/// _Complex float f; 2840/// \endcode 2841/// complexType() 2842/// matches "_Complex float f" 2843AST_TYPE_MATCHER(ComplexType, complexType); 2844 2845/// \brief Matches arrays and C99 complex types that have a specific element 2846/// type. 2847/// 2848/// Given 2849/// \code 2850/// struct A {}; 2851/// A a[7]; 2852/// int b[7]; 2853/// \endcode 2854/// arrayType(hasElementType(builtinType())) 2855/// matches "int b[7]" 2856/// 2857/// Usable as: Matcher<ArrayType>, Matcher<ComplexType> 2858AST_TYPELOC_TRAVERSE_MATCHER( 2859 hasElementType, getElement, 2860 AST_POLYMORPHIC_SUPPORTED_TYPES_2(ArrayType, ComplexType)); 2861 2862/// \brief Matches C arrays with a specified constant size. 2863/// 2864/// Given 2865/// \code 2866/// void() { 2867/// int a[2]; 2868/// int b[] = { 2, 3 }; 2869/// int c[b[0]]; 2870/// } 2871/// \endcode 2872/// constantArrayType() 2873/// matches "int a[2]" 2874AST_TYPE_MATCHER(ConstantArrayType, constantArrayType); 2875 2876/// \brief Matches \c ConstantArrayType nodes that have the specified size. 2877/// 2878/// Given 2879/// \code 2880/// int a[42]; 2881/// int b[2 * 21]; 2882/// int c[41], d[43]; 2883/// \endcode 2884/// constantArrayType(hasSize(42)) 2885/// matches "int a[42]" and "int b[2 * 21]" 2886AST_MATCHER_P(ConstantArrayType, hasSize, unsigned, N) { 2887 return Node.getSize() == N; 2888} 2889 2890/// \brief Matches C++ arrays whose size is a value-dependent expression. 2891/// 2892/// Given 2893/// \code 2894/// template<typename T, int Size> 2895/// class array { 2896/// T data[Size]; 2897/// }; 2898/// \endcode 2899/// dependentSizedArrayType 2900/// matches "T data[Size]" 2901AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType); 2902 2903/// \brief Matches C arrays with unspecified size. 2904/// 2905/// Given 2906/// \code 2907/// int a[] = { 2, 3 }; 2908/// int b[42]; 2909/// void f(int c[]) { int d[a[0]]; }; 2910/// \endcode 2911/// incompleteArrayType() 2912/// matches "int a[]" and "int c[]" 2913AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType); 2914 2915/// \brief Matches C arrays with a specified size that is not an 2916/// integer-constant-expression. 2917/// 2918/// Given 2919/// \code 2920/// void f() { 2921/// int a[] = { 2, 3 } 2922/// int b[42]; 2923/// int c[a[0]]; 2924/// \endcode 2925/// variableArrayType() 2926/// matches "int c[a[0]]" 2927AST_TYPE_MATCHER(VariableArrayType, variableArrayType); 2928 2929/// \brief Matches \c VariableArrayType nodes that have a specific size 2930/// expression. 2931/// 2932/// Given 2933/// \code 2934/// void f(int b) { 2935/// int a[b]; 2936/// } 2937/// \endcode 2938/// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to( 2939/// varDecl(hasName("b"))))))) 2940/// matches "int a[b]" 2941AST_MATCHER_P(VariableArrayType, hasSizeExpr, 2942 internal::Matcher<Expr>, InnerMatcher) { 2943 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder); 2944} 2945 2946/// \brief Matches atomic types. 2947/// 2948/// Given 2949/// \code 2950/// _Atomic(int) i; 2951/// \endcode 2952/// atomicType() 2953/// matches "_Atomic(int) i" 2954AST_TYPE_MATCHER(AtomicType, atomicType); 2955 2956/// \brief Matches atomic types with a specific value type. 2957/// 2958/// Given 2959/// \code 2960/// _Atomic(int) i; 2961/// _Atomic(float) f; 2962/// \endcode 2963/// atomicType(hasValueType(isInteger())) 2964/// matches "_Atomic(int) i" 2965/// 2966/// Usable as: Matcher<AtomicType> 2967AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue, 2968 AST_POLYMORPHIC_SUPPORTED_TYPES_1(AtomicType)); 2969 2970/// \brief Matches types nodes representing C++11 auto types. 2971/// 2972/// Given: 2973/// \code 2974/// auto n = 4; 2975/// int v[] = { 2, 3 } 2976/// for (auto i : v) { } 2977/// \endcode 2978/// autoType() 2979/// matches "auto n" and "auto i" 2980AST_TYPE_MATCHER(AutoType, autoType); 2981 2982/// \brief Matches \c AutoType nodes where the deduced type is a specific type. 2983/// 2984/// Note: There is no \c TypeLoc for the deduced type and thus no 2985/// \c getDeducedLoc() matcher. 2986/// 2987/// Given 2988/// \code 2989/// auto a = 1; 2990/// auto b = 2.0; 2991/// \endcode 2992/// autoType(hasDeducedType(isInteger())) 2993/// matches "auto a" 2994/// 2995/// Usable as: Matcher<AutoType> 2996AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType, 2997 AST_POLYMORPHIC_SUPPORTED_TYPES_1(AutoType)); 2998 2999/// \brief Matches \c FunctionType nodes. 3000/// 3001/// Given 3002/// \code 3003/// int (*f)(int); 3004/// void g(); 3005/// \endcode 3006/// functionType() 3007/// matches "int (*f)(int)" and the type of "g". 3008AST_TYPE_MATCHER(FunctionType, functionType); 3009 3010/// \brief Matches \c ParenType nodes. 3011/// 3012/// Given 3013/// \code 3014/// int (*ptr_to_array)[4]; 3015/// int *array_of_ptrs[4]; 3016/// \endcode 3017/// 3018/// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not 3019/// \c array_of_ptrs. 3020AST_TYPE_MATCHER(ParenType, parenType); 3021 3022/// \brief Matches \c ParenType nodes where the inner type is a specific type. 3023/// 3024/// Given 3025/// \code 3026/// int (*ptr_to_array)[4]; 3027/// int (*ptr_to_func)(int); 3028/// \endcode 3029/// 3030/// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches 3031/// \c ptr_to_func but not \c ptr_to_array. 3032/// 3033/// Usable as: Matcher<ParenType> 3034AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType, 3035 AST_POLYMORPHIC_SUPPORTED_TYPES_1(ParenType)); 3036 3037/// \brief Matches block pointer types, i.e. types syntactically represented as 3038/// "void (^)(int)". 3039/// 3040/// The \c pointee is always required to be a \c FunctionType. 3041AST_TYPE_MATCHER(BlockPointerType, blockPointerType); 3042 3043/// \brief Matches member pointer types. 3044/// Given 3045/// \code 3046/// struct A { int i; } 3047/// A::* ptr = A::i; 3048/// \endcode 3049/// memberPointerType() 3050/// matches "A::* ptr" 3051AST_TYPE_MATCHER(MemberPointerType, memberPointerType); 3052 3053/// \brief Matches pointer types. 3054/// 3055/// Given 3056/// \code 3057/// int *a; 3058/// int &b = *a; 3059/// int c = 5; 3060/// \endcode 3061/// pointerType() 3062/// matches "int *a" 3063AST_TYPE_MATCHER(PointerType, pointerType); 3064 3065/// \brief Matches both lvalue and rvalue reference types. 3066/// 3067/// Given 3068/// \code 3069/// int *a; 3070/// int &b = *a; 3071/// int &&c = 1; 3072/// auto &d = b; 3073/// auto &&e = c; 3074/// auto &&f = 2; 3075/// int g = 5; 3076/// \endcode 3077/// 3078/// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f. 3079AST_TYPE_MATCHER(ReferenceType, referenceType); 3080 3081/// \brief Matches lvalue reference types. 3082/// 3083/// Given: 3084/// \code 3085/// int *a; 3086/// int &b = *a; 3087/// int &&c = 1; 3088/// auto &d = b; 3089/// auto &&e = c; 3090/// auto &&f = 2; 3091/// int g = 5; 3092/// \endcode 3093/// 3094/// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is 3095/// matched since the type is deduced as int& by reference collapsing rules. 3096AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType); 3097 3098/// \brief Matches rvalue reference types. 3099/// 3100/// Given: 3101/// \code 3102/// int *a; 3103/// int &b = *a; 3104/// int &&c = 1; 3105/// auto &d = b; 3106/// auto &&e = c; 3107/// auto &&f = 2; 3108/// int g = 5; 3109/// \endcode 3110/// 3111/// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not 3112/// matched as it is deduced to int& by reference collapsing rules. 3113AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType); 3114 3115/// \brief Narrows PointerType (and similar) matchers to those where the 3116/// \c pointee matches a given matcher. 3117/// 3118/// Given 3119/// \code 3120/// int *a; 3121/// int const *b; 3122/// float const *f; 3123/// \endcode 3124/// pointerType(pointee(isConstQualified(), isInteger())) 3125/// matches "int const *b" 3126/// 3127/// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>, 3128/// Matcher<PointerType>, Matcher<ReferenceType> 3129AST_TYPELOC_TRAVERSE_MATCHER( 3130 pointee, getPointee, 3131 AST_POLYMORPHIC_SUPPORTED_TYPES_4(BlockPointerType, MemberPointerType, 3132 PointerType, ReferenceType)); 3133 3134/// \brief Matches typedef types. 3135/// 3136/// Given 3137/// \code 3138/// typedef int X; 3139/// \endcode 3140/// typedefType() 3141/// matches "typedef int X" 3142AST_TYPE_MATCHER(TypedefType, typedefType); 3143 3144/// \brief Matches template specialization types. 3145/// 3146/// Given 3147/// \code 3148/// template <typename T> 3149/// class C { }; 3150/// 3151/// template class C<int>; // A 3152/// C<char> var; // B 3153/// \code 3154/// 3155/// \c templateSpecializationType() matches the type of the explicit 3156/// instantiation in \c A and the type of the variable declaration in \c B. 3157AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType); 3158 3159/// \brief Matches types nodes representing unary type transformations. 3160/// 3161/// Given: 3162/// \code 3163/// typedef __underlying_type(T) type; 3164/// \endcode 3165/// unaryTransformType() 3166/// matches "__underlying_type(T)" 3167AST_TYPE_MATCHER(UnaryTransformType, unaryTransformType); 3168 3169/// \brief Matches record types (e.g. structs, classes). 3170/// 3171/// Given 3172/// \code 3173/// class C {}; 3174/// struct S {}; 3175/// 3176/// C c; 3177/// S s; 3178/// \code 3179/// 3180/// \c recordType() matches the type of the variable declarations of both \c c 3181/// and \c s. 3182AST_TYPE_MATCHER(RecordType, recordType); 3183 3184/// \brief Matches types specified with an elaborated type keyword or with a 3185/// qualified name. 3186/// 3187/// Given 3188/// \code 3189/// namespace N { 3190/// namespace M { 3191/// class D {}; 3192/// } 3193/// } 3194/// class C {}; 3195/// 3196/// class C c; 3197/// N::M::D d; 3198/// \code 3199/// 3200/// \c elaboratedType() matches the type of the variable declarations of both 3201/// \c c and \c d. 3202AST_TYPE_MATCHER(ElaboratedType, elaboratedType); 3203 3204/// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier, 3205/// matches \c InnerMatcher if the qualifier exists. 3206/// 3207/// Given 3208/// \code 3209/// namespace N { 3210/// namespace M { 3211/// class D {}; 3212/// } 3213/// } 3214/// N::M::D d; 3215/// \code 3216/// 3217/// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))) 3218/// matches the type of the variable declaration of \c d. 3219AST_MATCHER_P(ElaboratedType, hasQualifier, 3220 internal::Matcher<NestedNameSpecifier>, InnerMatcher) { 3221 if (const NestedNameSpecifier *Qualifier = Node.getQualifier()) 3222 return InnerMatcher.matches(*Qualifier, Finder, Builder); 3223 3224 return false; 3225} 3226 3227/// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher. 3228/// 3229/// Given 3230/// \code 3231/// namespace N { 3232/// namespace M { 3233/// class D {}; 3234/// } 3235/// } 3236/// N::M::D d; 3237/// \code 3238/// 3239/// \c elaboratedType(namesType(recordType( 3240/// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable 3241/// declaration of \c d. 3242AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>, 3243 InnerMatcher) { 3244 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder); 3245} 3246 3247/// \brief Matches declarations whose declaration context, interpreted as a 3248/// Decl, matches \c InnerMatcher. 3249/// 3250/// Given 3251/// \code 3252/// namespace N { 3253/// namespace M { 3254/// class D {}; 3255/// } 3256/// } 3257/// \code 3258/// 3259/// \c recordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the 3260/// declaration of \c class \c D. 3261AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) { 3262 return InnerMatcher.matches(*Decl::castFromDeclContext(Node.getDeclContext()), 3263 Finder, Builder); 3264} 3265 3266/// \brief Matches nested name specifiers. 3267/// 3268/// Given 3269/// \code 3270/// namespace ns { 3271/// struct A { static void f(); }; 3272/// void A::f() {} 3273/// void g() { A::f(); } 3274/// } 3275/// ns::A a; 3276/// \endcode 3277/// nestedNameSpecifier() 3278/// matches "ns::" and both "A::" 3279const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier; 3280 3281/// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc. 3282const internal::VariadicAllOfMatcher< 3283 NestedNameSpecifierLoc> nestedNameSpecifierLoc; 3284 3285/// \brief Matches \c NestedNameSpecifierLocs for which the given inner 3286/// NestedNameSpecifier-matcher matches. 3287inline internal::BindableMatcher<NestedNameSpecifierLoc> loc( 3288 const internal::Matcher<NestedNameSpecifier> &InnerMatcher) { 3289 return internal::BindableMatcher<NestedNameSpecifierLoc>( 3290 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>( 3291 InnerMatcher)); 3292} 3293 3294/// \brief Matches nested name specifiers that specify a type matching the 3295/// given \c QualType matcher without qualifiers. 3296/// 3297/// Given 3298/// \code 3299/// struct A { struct B { struct C {}; }; }; 3300/// A::B::C c; 3301/// \endcode 3302/// nestedNameSpecifier(specifiesType(hasDeclaration(recordDecl(hasName("A"))))) 3303/// matches "A::" 3304AST_MATCHER_P(NestedNameSpecifier, specifiesType, 3305 internal::Matcher<QualType>, InnerMatcher) { 3306 if (Node.getAsType() == NULL) 3307 return false; 3308 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder); 3309} 3310 3311/// \brief Matches nested name specifier locs that specify a type matching the 3312/// given \c TypeLoc. 3313/// 3314/// Given 3315/// \code 3316/// struct A { struct B { struct C {}; }; }; 3317/// A::B::C c; 3318/// \endcode 3319/// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type( 3320/// hasDeclaration(recordDecl(hasName("A"))))))) 3321/// matches "A::" 3322AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc, 3323 internal::Matcher<TypeLoc>, InnerMatcher) { 3324 return InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder); 3325} 3326 3327/// \brief Matches on the prefix of a \c NestedNameSpecifier. 3328/// 3329/// Given 3330/// \code 3331/// struct A { struct B { struct C {}; }; }; 3332/// A::B::C c; 3333/// \endcode 3334/// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and 3335/// matches "A::" 3336AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix, 3337 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 3338 0) { 3339 NestedNameSpecifier *NextNode = Node.getPrefix(); 3340 if (NextNode == NULL) 3341 return false; 3342 return InnerMatcher.matches(*NextNode, Finder, Builder); 3343} 3344 3345/// \brief Matches on the prefix of a \c NestedNameSpecifierLoc. 3346/// 3347/// Given 3348/// \code 3349/// struct A { struct B { struct C {}; }; }; 3350/// A::B::C c; 3351/// \endcode 3352/// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A"))))) 3353/// matches "A::" 3354AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix, 3355 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher, 3356 1) { 3357 NestedNameSpecifierLoc NextNode = Node.getPrefix(); 3358 if (!NextNode) 3359 return false; 3360 return InnerMatcher.matches(NextNode, Finder, Builder); 3361} 3362 3363/// \brief Matches nested name specifiers that specify a namespace matching the 3364/// given namespace matcher. 3365/// 3366/// Given 3367/// \code 3368/// namespace ns { struct A {}; } 3369/// ns::A a; 3370/// \endcode 3371/// nestedNameSpecifier(specifiesNamespace(hasName("ns"))) 3372/// matches "ns::" 3373AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace, 3374 internal::Matcher<NamespaceDecl>, InnerMatcher) { 3375 if (Node.getAsNamespace() == NULL) 3376 return false; 3377 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder); 3378} 3379 3380/// \brief Overloads for the \c equalsNode matcher. 3381/// FIXME: Implement for other node types. 3382/// @{ 3383 3384/// \brief Matches if a node equals another node. 3385/// 3386/// \c Decl has pointer identity in the AST. 3387AST_MATCHER_P_OVERLOAD(Decl, equalsNode, Decl*, Other, 0) { 3388 return &Node == Other; 3389} 3390/// \brief Matches if a node equals another node. 3391/// 3392/// \c Stmt has pointer identity in the AST. 3393/// 3394AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, Stmt*, Other, 1) { 3395 return &Node == Other; 3396} 3397 3398/// @} 3399 3400/// \brief Matches each case or default statement belonging to the given switch 3401/// statement. This matcher may produce multiple matches. 3402/// 3403/// Given 3404/// \code 3405/// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } } 3406/// \endcode 3407/// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s") 3408/// matches four times, with "c" binding each of "case 1:", "case 2:", 3409/// "case 3:" and "case 4:", and "s" respectively binding "switch (1)", 3410/// "switch (1)", "switch (2)" and "switch (2)". 3411AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>, 3412 InnerMatcher) { 3413 BoundNodesTreeBuilder Result; 3414 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable 3415 // iteration order. We should use the more general iterating matchers once 3416 // they are capable of expressing this matcher (for example, it should ignore 3417 // case statements belonging to nested switch statements). 3418 bool Matched = false; 3419 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC; 3420 SC = SC->getNextSwitchCase()) { 3421 BoundNodesTreeBuilder CaseBuilder(*Builder); 3422 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder); 3423 if (CaseMatched) { 3424 Matched = true; 3425 Result.addMatch(CaseBuilder); 3426 } 3427 } 3428 *Builder = Result; 3429 return Matched; 3430} 3431 3432/// \brief Matches each constructor initializer in a constructor definition. 3433/// 3434/// Given 3435/// \code 3436/// class A { A() : i(42), j(42) {} int i; int j; }; 3437/// \endcode 3438/// constructorDecl(forEachConstructorInitializer(forField(decl().bind("x")))) 3439/// will trigger two matches, binding for 'i' and 'j' respectively. 3440AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer, 3441 internal::Matcher<CXXCtorInitializer>, InnerMatcher) { 3442 BoundNodesTreeBuilder Result; 3443 bool Matched = false; 3444 for (CXXConstructorDecl::init_const_iterator I = Node.init_begin(), 3445 E = Node.init_end(); 3446 I != E; ++I) { 3447 BoundNodesTreeBuilder InitBuilder(*Builder); 3448 if (InnerMatcher.matches(**I, Finder, &InitBuilder)) { 3449 Matched = true; 3450 Result.addMatch(InitBuilder); 3451 } 3452 } 3453 *Builder = Result; 3454 return Matched; 3455} 3456 3457/// \brief If the given case statement does not use the GNU case range 3458/// extension, matches the constant given in the statement. 3459/// 3460/// Given 3461/// \code 3462/// switch (1) { case 1: case 1+1: case 3 ... 4: ; } 3463/// \endcode 3464/// caseStmt(hasCaseConstant(integerLiteral())) 3465/// matches "case 1:" 3466AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>, 3467 InnerMatcher) { 3468 if (Node.getRHS()) 3469 return false; 3470 3471 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder); 3472} 3473 3474} // end namespace ast_matchers 3475} // end namespace clang 3476 3477#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H 3478