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