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// cxxRecordDecl(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// cxxRecordDecl(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 RecordDecl 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_ASTMATCHERS_ASTMATCHERS_H 46#define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H 47 48#include "clang/AST/ASTContext.h" 49#include "clang/AST/DeclFriend.h" 50#include "clang/AST/DeclObjC.h" 51#include "clang/AST/DeclTemplate.h" 52#include "clang/ASTMatchers/ASTMatchersInternal.h" 53#include "clang/ASTMatchers/ASTMatchersMacros.h" 54#include "llvm/Support/Regex.h" 55#include <iterator> 56 57namespace clang { 58namespace ast_matchers { 59 60/// \brief Maps string IDs to AST nodes matched by parts of a matcher. 61/// 62/// The bound nodes are generated by calling \c bind("id") on the node matchers 63/// of the nodes we want to access later. 64/// 65/// The instances of BoundNodes are created by \c MatchFinder when the user's 66/// callbacks are executed every time a match is found. 67class BoundNodes { 68public: 69 /// \brief Returns the AST node bound to \c ID. 70 /// 71 /// Returns NULL if there was no node bound to \c ID or if there is a node but 72 /// it cannot be converted to the specified type. 73 template <typename T> 74 const T *getNodeAs(StringRef ID) const { 75 return MyBoundNodes.getNodeAs<T>(ID); 76 } 77 78 /// \brief Type of mapping from binding identifiers to bound nodes. This type 79 /// is an associative container with a key type of \c std::string and a value 80 /// type of \c clang::ast_type_traits::DynTypedNode 81 typedef internal::BoundNodesMap::IDToNodeMap IDToNodeMap; 82 83 /// \brief Retrieve mapping from binding identifiers to bound nodes. 84 const IDToNodeMap &getMap() const { 85 return MyBoundNodes.getMap(); 86 } 87 88private: 89 /// \brief Create BoundNodes from a pre-filled map of bindings. 90 BoundNodes(internal::BoundNodesMap &MyBoundNodes) 91 : MyBoundNodes(MyBoundNodes) {} 92 93 internal::BoundNodesMap MyBoundNodes; 94 95 friend class internal::BoundNodesTreeBuilder; 96}; 97 98/// \brief If the provided matcher matches a node, binds the node to \c ID. 99/// 100/// FIXME: Do we want to support this now that we have bind()? 101template <typename T> 102internal::Matcher<T> id(StringRef ID, 103 const internal::BindableMatcher<T> &InnerMatcher) { 104 return InnerMatcher.bind(ID); 105} 106 107/// \brief Types of matchers for the top-level classes in the AST class 108/// hierarchy. 109/// @{ 110typedef internal::Matcher<Decl> DeclarationMatcher; 111typedef internal::Matcher<Stmt> StatementMatcher; 112typedef internal::Matcher<QualType> TypeMatcher; 113typedef internal::Matcher<TypeLoc> TypeLocMatcher; 114typedef internal::Matcher<NestedNameSpecifier> NestedNameSpecifierMatcher; 115typedef internal::Matcher<NestedNameSpecifierLoc> NestedNameSpecifierLocMatcher; 116typedef internal::Matcher<CXXCtorInitializer> CXXCtorInitializerMatcher; 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::TrueMatcher anything() { return internal::TrueMatcher(); } 134 135/// \brief Matches the top declaration context. 136/// 137/// Given 138/// \code 139/// int X; 140/// namespace NS { 141/// int Y; 142/// } // namespace NS 143/// \endcode 144/// decl(hasDeclContext(translationUnitDecl())) 145/// matches "int X", but not "int Y". 146const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl> 147 translationUnitDecl; 148 149/// \brief Matches typedef declarations. 150/// 151/// Given 152/// \code 153/// typedef int X; 154/// using Y = int; 155/// \endcode 156/// typedefDecl() 157/// matches "typedef int X", but not "using Y = int" 158const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl> typedefDecl; 159 160/// \brief Matches typedef name declarations. 161/// 162/// Given 163/// \code 164/// typedef int X; 165/// using Y = int; 166/// \endcode 167/// typedefNameDecl() 168/// matches "typedef int X" and "using Y = int" 169const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl> 170 typedefNameDecl; 171 172/// \brief Matches type alias declarations. 173/// 174/// Given 175/// \code 176/// typedef int X; 177/// using Y = int; 178/// \endcode 179/// typeAliasDecl() 180/// matches "using Y = int", but not "typedef int X" 181const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl> typeAliasDecl; 182 183/// \brief Matches type alias template declarations. 184/// 185/// typeAliasTemplateDecl() matches 186/// \code 187/// template <typename T> 188/// using Y = X<T>; 189/// \endcode 190const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl> 191 typeAliasTemplateDecl; 192 193/// \brief Matches AST nodes that were expanded within the main-file. 194/// 195/// Example matches X but not Y 196/// (matcher = cxxRecordDecl(isExpansionInMainFile()) 197/// \code 198/// #include <Y.h> 199/// class X {}; 200/// \endcode 201/// Y.h: 202/// \code 203/// class Y {}; 204/// \endcode 205/// 206/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc> 207AST_POLYMORPHIC_MATCHER(isExpansionInMainFile, 208 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) { 209 auto &SourceManager = Finder->getASTContext().getSourceManager(); 210 return SourceManager.isInMainFile( 211 SourceManager.getExpansionLoc(Node.getLocStart())); 212} 213 214/// \brief Matches AST nodes that were expanded within system-header-files. 215/// 216/// Example matches Y but not X 217/// (matcher = cxxRecordDecl(isExpansionInSystemHeader()) 218/// \code 219/// #include <SystemHeader.h> 220/// class X {}; 221/// \endcode 222/// SystemHeader.h: 223/// \code 224/// class Y {}; 225/// \endcode 226/// 227/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc> 228AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader, 229 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) { 230 auto &SourceManager = Finder->getASTContext().getSourceManager(); 231 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart()); 232 if (ExpansionLoc.isInvalid()) { 233 return false; 234 } 235 return SourceManager.isInSystemHeader(ExpansionLoc); 236} 237 238/// \brief Matches AST nodes that were expanded within files whose name is 239/// partially matching a given regex. 240/// 241/// Example matches Y but not X 242/// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*")) 243/// \code 244/// #include "ASTMatcher.h" 245/// class X {}; 246/// \endcode 247/// ASTMatcher.h: 248/// \code 249/// class Y {}; 250/// \endcode 251/// 252/// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc> 253AST_POLYMORPHIC_MATCHER_P(isExpansionInFileMatching, 254 AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc), 255 std::string, RegExp) { 256 auto &SourceManager = Finder->getASTContext().getSourceManager(); 257 auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getLocStart()); 258 if (ExpansionLoc.isInvalid()) { 259 return false; 260 } 261 auto FileEntry = 262 SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc)); 263 if (!FileEntry) { 264 return false; 265 } 266 267 auto Filename = FileEntry->getName(); 268 llvm::Regex RE(RegExp); 269 return RE.match(Filename); 270} 271 272/// \brief Matches declarations. 273/// 274/// Examples matches \c X, \c C, and the friend declaration inside \c C; 275/// \code 276/// void X(); 277/// class C { 278/// friend X; 279/// }; 280/// \endcode 281const internal::VariadicAllOfMatcher<Decl> decl; 282 283/// \brief Matches a declaration of a linkage specification. 284/// 285/// Given 286/// \code 287/// extern "C" {} 288/// \endcode 289/// linkageSpecDecl() 290/// matches "extern "C" {}" 291const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl> 292 linkageSpecDecl; 293 294/// \brief Matches a declaration of anything that could have a name. 295/// 296/// Example matches \c X, \c S, the anonymous union type, \c i, and \c U; 297/// \code 298/// typedef int X; 299/// struct S { 300/// union { 301/// int i; 302/// } U; 303/// }; 304/// \endcode 305const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl; 306 307/// \brief Matches a declaration of label. 308/// 309/// Given 310/// \code 311/// goto FOO; 312/// FOO: bar(); 313/// \endcode 314/// labelDecl() 315/// matches 'FOO:' 316const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl; 317 318/// \brief Matches a declaration of a namespace. 319/// 320/// Given 321/// \code 322/// namespace {} 323/// namespace test {} 324/// \endcode 325/// namespaceDecl() 326/// matches "namespace {}" and "namespace test {}" 327const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl; 328 329/// \brief Matches a declaration of a namespace alias. 330/// 331/// Given 332/// \code 333/// namespace test {} 334/// namespace alias = ::test; 335/// \endcode 336/// namespaceAliasDecl() 337/// matches "namespace alias" but not "namespace test" 338const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl> 339 namespaceAliasDecl; 340 341/// \brief Matches class, struct, and union declarations. 342/// 343/// Example matches \c X, \c Z, \c U, and \c S 344/// \code 345/// class X; 346/// template<class T> class Z {}; 347/// struct S {}; 348/// union U {}; 349/// \endcode 350const internal::VariadicDynCastAllOfMatcher< 351 Decl, 352 RecordDecl> recordDecl; 353 354/// \brief Matches C++ class declarations. 355/// 356/// Example matches \c X, \c Z 357/// \code 358/// class X; 359/// template<class T> class Z {}; 360/// \endcode 361const internal::VariadicDynCastAllOfMatcher< 362 Decl, 363 CXXRecordDecl> cxxRecordDecl; 364 365/// \brief Matches C++ class template declarations. 366/// 367/// Example matches \c Z 368/// \code 369/// template<class T> class Z {}; 370/// \endcode 371const internal::VariadicDynCastAllOfMatcher< 372 Decl, 373 ClassTemplateDecl> classTemplateDecl; 374 375/// \brief Matches C++ class template specializations. 376/// 377/// Given 378/// \code 379/// template<typename T> class A {}; 380/// template<> class A<double> {}; 381/// A<int> a; 382/// \endcode 383/// classTemplateSpecializationDecl() 384/// matches the specializations \c A<int> and \c A<double> 385const internal::VariadicDynCastAllOfMatcher< 386 Decl, 387 ClassTemplateSpecializationDecl> classTemplateSpecializationDecl; 388 389/// \brief Matches declarator declarations (field, variable, function 390/// and non-type template parameter declarations). 391/// 392/// Given 393/// \code 394/// class X { int y; }; 395/// \endcode 396/// declaratorDecl() 397/// matches \c int y. 398const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl> 399 declaratorDecl; 400 401/// \brief Matches parameter variable declarations. 402/// 403/// Given 404/// \code 405/// void f(int x); 406/// \endcode 407/// parmVarDecl() 408/// matches \c int x. 409const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl> parmVarDecl; 410 411/// \brief Matches C++ access specifier declarations. 412/// 413/// Given 414/// \code 415/// class C { 416/// public: 417/// int a; 418/// }; 419/// \endcode 420/// accessSpecDecl() 421/// matches 'public:' 422const internal::VariadicDynCastAllOfMatcher< 423 Decl, 424 AccessSpecDecl> accessSpecDecl; 425 426/// \brief Matches constructor initializers. 427/// 428/// Examples matches \c i(42). 429/// \code 430/// class C { 431/// C() : i(42) {} 432/// int i; 433/// }; 434/// \endcode 435const internal::VariadicAllOfMatcher<CXXCtorInitializer> cxxCtorInitializer; 436 437/// \brief Matches template arguments. 438/// 439/// Given 440/// \code 441/// template <typename T> struct C {}; 442/// C<int> c; 443/// \endcode 444/// templateArgument() 445/// matches 'int' in C<int>. 446const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument; 447 448/// \brief Matches template name. 449/// 450/// Given 451/// \code 452/// template <typename T> class X { }; 453/// X<int> xi; 454/// \endcode 455/// templateName() 456/// matches 'X' in X<int>. 457const internal::VariadicAllOfMatcher<TemplateName> templateName; 458 459/// \brief Matches non-type template parameter declarations. 460/// 461/// Given 462/// \code 463/// template <typename T, int N> struct C {}; 464/// \endcode 465/// nonTypeTemplateParmDecl() 466/// matches 'N', but not 'T'. 467const internal::VariadicDynCastAllOfMatcher< 468 Decl, 469 NonTypeTemplateParmDecl> nonTypeTemplateParmDecl; 470 471/// \brief Matches template type parameter declarations. 472/// 473/// Given 474/// \code 475/// template <typename T, int N> struct C {}; 476/// \endcode 477/// templateTypeParmDecl() 478/// matches 'T', but not 'N'. 479const internal::VariadicDynCastAllOfMatcher< 480 Decl, 481 TemplateTypeParmDecl> templateTypeParmDecl; 482 483/// \brief Matches public C++ declarations. 484/// 485/// Given 486/// \code 487/// class C { 488/// public: int a; 489/// protected: int b; 490/// private: int c; 491/// }; 492/// \endcode 493/// fieldDecl(isPublic()) 494/// matches 'int a;' 495AST_MATCHER(Decl, isPublic) { 496 return Node.getAccess() == AS_public; 497} 498 499/// \brief Matches protected C++ declarations. 500/// 501/// Given 502/// \code 503/// class C { 504/// public: int a; 505/// protected: int b; 506/// private: int c; 507/// }; 508/// \endcode 509/// fieldDecl(isProtected()) 510/// matches 'int b;' 511AST_MATCHER(Decl, isProtected) { 512 return Node.getAccess() == AS_protected; 513} 514 515/// \brief Matches private C++ declarations. 516/// 517/// Given 518/// \code 519/// class C { 520/// public: int a; 521/// protected: int b; 522/// private: int c; 523/// }; 524/// \endcode 525/// fieldDecl(isPrivate()) 526/// matches 'int c;' 527AST_MATCHER(Decl, isPrivate) { 528 return Node.getAccess() == AS_private; 529} 530 531/// \brief Matches non-static data members that are bit-fields. 532/// 533/// Given 534/// \code 535/// class C { 536/// int a : 2; 537/// int b; 538/// }; 539/// \endcode 540/// fieldDecl(isBitField()) 541/// matches 'int a;' but not 'int b;'. 542AST_MATCHER(FieldDecl, isBitField) { 543 return Node.isBitField(); 544} 545 546/// \brief Matches non-static data members that are bit-fields of the specified 547/// bit width. 548/// 549/// Given 550/// \code 551/// class C { 552/// int a : 2; 553/// int b : 4; 554/// int c : 2; 555/// }; 556/// \endcode 557/// fieldDecl(hasBitWidth(2)) 558/// matches 'int a;' and 'int c;' but not 'int b;'. 559AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) { 560 return Node.isBitField() && 561 Node.getBitWidthValue(Finder->getASTContext()) == Width; 562} 563 564/// \brief Matches non-static data members that have an in-class initializer. 565/// 566/// Given 567/// \code 568/// class C { 569/// int a = 2; 570/// int b = 3; 571/// int c; 572/// }; 573/// \endcode 574/// fieldDecl(hasInClassInitializer(integerLiteral(equals(2)))) 575/// matches 'int a;' but not 'int b;'. 576/// fieldDecl(hasInClassInitializer(anything())) 577/// matches 'int a;' and 'int b;' but not 'int c;'. 578AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>, 579 InnerMatcher) { 580 const Expr *Initializer = Node.getInClassInitializer(); 581 return (Initializer != nullptr && 582 InnerMatcher.matches(*Initializer, Finder, Builder)); 583} 584 585/// \brief Matches a declaration that has been implicitly added 586/// by the compiler (eg. implicit default/copy constructors). 587AST_MATCHER(Decl, isImplicit) { 588 return Node.isImplicit(); 589} 590 591/// \brief Matches classTemplateSpecializations, templateSpecializationType and 592/// functionDecl that have at least one TemplateArgument matching the given 593/// InnerMatcher. 594/// 595/// Given 596/// \code 597/// template<typename T> class A {}; 598/// template<> class A<double> {}; 599/// A<int> a; 600/// 601/// template<typename T> f() {}; 602/// void func() { f<int>(); }; 603/// \endcode 604/// 605/// \endcode 606/// classTemplateSpecializationDecl(hasAnyTemplateArgument( 607/// refersToType(asString("int")))) 608/// matches the specialization \c A<int> 609/// 610/// functionDecl(hasAnyTemplateArgument(refersToType(asString("int")))) 611/// matches the specialization \c f<int> 612AST_POLYMORPHIC_MATCHER_P( 613 hasAnyTemplateArgument, 614 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl, 615 TemplateSpecializationType, 616 FunctionDecl), 617 internal::Matcher<TemplateArgument>, InnerMatcher) { 618 ArrayRef<TemplateArgument> List = 619 internal::getTemplateSpecializationArgs(Node); 620 return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder, 621 Builder); 622} 623 624/// \brief Matches expressions that match InnerMatcher after any implicit AST 625/// nodes are stripped off. 626/// 627/// Parentheses and explicit casts are not discarded. 628/// Given 629/// \code 630/// class C {}; 631/// C a = C(); 632/// C b; 633/// C c = b; 634/// \endcode 635/// The matchers 636/// \code 637/// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr()))) 638/// \endcode 639/// would match the declarations for a, b, and c. 640/// While 641/// \code 642/// varDecl(hasInitializer(cxxConstructExpr())) 643/// \endcode 644/// only match the declarations for b and c. 645AST_MATCHER_P(Expr, ignoringImplicit, ast_matchers::internal::Matcher<Expr>, 646 InnerMatcher) { 647 return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder); 648} 649 650/// \brief Matches expressions that match InnerMatcher after any implicit casts 651/// are stripped off. 652/// 653/// Parentheses and explicit casts are not discarded. 654/// Given 655/// \code 656/// int arr[5]; 657/// int a = 0; 658/// char b = 0; 659/// const int c = a; 660/// int *d = arr; 661/// long e = (long) 0l; 662/// \endcode 663/// The matchers 664/// \code 665/// varDecl(hasInitializer(ignoringImpCasts(integerLiteral()))) 666/// varDecl(hasInitializer(ignoringImpCasts(declRefExpr()))) 667/// \endcode 668/// would match the declarations for a, b, c, and d, but not e. 669/// While 670/// \code 671/// varDecl(hasInitializer(integerLiteral())) 672/// varDecl(hasInitializer(declRefExpr())) 673/// \endcode 674/// only match the declarations for b, c, and d. 675AST_MATCHER_P(Expr, ignoringImpCasts, 676 internal::Matcher<Expr>, InnerMatcher) { 677 return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder); 678} 679 680/// \brief Matches expressions that match InnerMatcher after parentheses and 681/// casts are stripped off. 682/// 683/// Implicit and non-C Style casts are also discarded. 684/// Given 685/// \code 686/// int a = 0; 687/// char b = (0); 688/// void* c = reinterpret_cast<char*>(0); 689/// char d = char(0); 690/// \endcode 691/// The matcher 692/// varDecl(hasInitializer(ignoringParenCasts(integerLiteral()))) 693/// would match the declarations for a, b, c, and d. 694/// while 695/// varDecl(hasInitializer(integerLiteral())) 696/// only match the declaration for a. 697AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) { 698 return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder); 699} 700 701/// \brief Matches expressions that match InnerMatcher after implicit casts and 702/// parentheses are stripped off. 703/// 704/// Explicit casts are not discarded. 705/// Given 706/// \code 707/// int arr[5]; 708/// int a = 0; 709/// char b = (0); 710/// const int c = a; 711/// int *d = (arr); 712/// long e = ((long) 0l); 713/// \endcode 714/// The matchers 715/// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral()))) 716/// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr()))) 717/// would match the declarations for a, b, c, and d, but not e. 718/// while 719/// varDecl(hasInitializer(integerLiteral())) 720/// varDecl(hasInitializer(declRefExpr())) 721/// would only match the declaration for a. 722AST_MATCHER_P(Expr, ignoringParenImpCasts, 723 internal::Matcher<Expr>, InnerMatcher) { 724 return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder); 725} 726 727/// \brief Matches types that match InnerMatcher after any parens are stripped. 728/// 729/// Given 730/// \code 731/// void (*fp)(void); 732/// \endcode 733/// The matcher 734/// \code 735/// varDecl(hasType(pointerType(pointee(ignoringParens(functionType()))))) 736/// \endcode 737/// would match the declaration for fp. 738AST_MATCHER_P(QualType, ignoringParens, 739 internal::Matcher<QualType>, InnerMatcher) { 740 return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder); 741} 742 743/// \brief Matches classTemplateSpecializations, templateSpecializationType and 744/// functionDecl where the n'th TemplateArgument matches the given InnerMatcher. 745/// 746/// Given 747/// \code 748/// template<typename T, typename U> class A {}; 749/// A<bool, int> b; 750/// A<int, bool> c; 751/// 752/// template<typename T> f() {}; 753/// void func() { f<int>(); }; 754/// \endcode 755/// classTemplateSpecializationDecl(hasTemplateArgument( 756/// 1, refersToType(asString("int")))) 757/// matches the specialization \c A<bool, int> 758/// 759/// functionDecl(hasTemplateArgument(0, refersToType(asString("int")))) 760/// matches the specialization \c f<int> 761AST_POLYMORPHIC_MATCHER_P2( 762 hasTemplateArgument, 763 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl, 764 TemplateSpecializationType, 765 FunctionDecl), 766 unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) { 767 ArrayRef<TemplateArgument> List = 768 internal::getTemplateSpecializationArgs(Node); 769 if (List.size() <= N) 770 return false; 771 return InnerMatcher.matches(List[N], Finder, Builder); 772} 773 774/// \brief Matches if the number of template arguments equals \p N. 775/// 776/// Given 777/// \code 778/// template<typename T> struct C {}; 779/// C<int> c; 780/// \endcode 781/// classTemplateSpecializationDecl(templateArgumentCountIs(1)) 782/// matches C<int>. 783AST_POLYMORPHIC_MATCHER_P( 784 templateArgumentCountIs, 785 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl, 786 TemplateSpecializationType), 787 unsigned, N) { 788 return internal::getTemplateSpecializationArgs(Node).size() == N; 789} 790 791/// \brief Matches a TemplateArgument that refers to a certain type. 792/// 793/// Given 794/// \code 795/// struct X {}; 796/// template<typename T> struct A {}; 797/// A<X> a; 798/// \endcode 799/// classTemplateSpecializationDecl(hasAnyTemplateArgument( 800/// refersToType(class(hasName("X"))))) 801/// matches the specialization \c A<X> 802AST_MATCHER_P(TemplateArgument, refersToType, 803 internal::Matcher<QualType>, InnerMatcher) { 804 if (Node.getKind() != TemplateArgument::Type) 805 return false; 806 return InnerMatcher.matches(Node.getAsType(), Finder, Builder); 807} 808 809/// \brief Matches a TemplateArgument that refers to a certain template. 810/// 811/// Given 812/// \code 813/// template<template <typename> class S> class X {}; 814/// template<typename T> class Y {};" 815/// X<Y> xi; 816/// \endcode 817/// classTemplateSpecializationDecl(hasAnyTemplateArgument( 818/// refersToTemplate(templateName()))) 819/// matches the specialization \c X<Y> 820AST_MATCHER_P(TemplateArgument, refersToTemplate, 821 internal::Matcher<TemplateName>, InnerMatcher) { 822 if (Node.getKind() != TemplateArgument::Template) 823 return false; 824 return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder); 825} 826 827/// \brief Matches a canonical TemplateArgument that refers to a certain 828/// declaration. 829/// 830/// Given 831/// \code 832/// template<typename T> struct A {}; 833/// struct B { B* next; }; 834/// A<&B::next> a; 835/// \endcode 836/// classTemplateSpecializationDecl(hasAnyTemplateArgument( 837/// refersToDeclaration(fieldDecl(hasName("next")))) 838/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching 839/// \c B::next 840AST_MATCHER_P(TemplateArgument, refersToDeclaration, 841 internal::Matcher<Decl>, InnerMatcher) { 842 if (Node.getKind() == TemplateArgument::Declaration) 843 return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder); 844 return false; 845} 846 847/// \brief Matches a sugar TemplateArgument that refers to a certain expression. 848/// 849/// Given 850/// \code 851/// template<typename T> struct A {}; 852/// struct B { B* next; }; 853/// A<&B::next> a; 854/// \endcode 855/// templateSpecializationType(hasAnyTemplateArgument( 856/// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next")))))))) 857/// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching 858/// \c B::next 859AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) { 860 if (Node.getKind() == TemplateArgument::Expression) 861 return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder); 862 return false; 863} 864 865/// \brief Matches a TemplateArgument that is an integral value. 866/// 867/// Given 868/// \code 869/// template<int T> struct A {}; 870/// C<42> c; 871/// \endcode 872/// classTemplateSpecializationDecl( 873/// hasAnyTemplateArgument(isIntegral())) 874/// matches the implicit instantiation of C in C<42> 875/// with isIntegral() matching 42. 876AST_MATCHER(TemplateArgument, isIntegral) { 877 return Node.getKind() == TemplateArgument::Integral; 878} 879 880/// \brief Matches a TemplateArgument that referes to an integral type. 881/// 882/// Given 883/// \code 884/// template<int T> struct A {}; 885/// C<42> c; 886/// \endcode 887/// classTemplateSpecializationDecl( 888/// hasAnyTemplateArgument(refersToIntegralType(asString("int")))) 889/// matches the implicit instantiation of C in C<42>. 890AST_MATCHER_P(TemplateArgument, refersToIntegralType, 891 internal::Matcher<QualType>, InnerMatcher) { 892 if (Node.getKind() != TemplateArgument::Integral) 893 return false; 894 return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder); 895} 896 897/// \brief Matches a TemplateArgument of integral type with a given value. 898/// 899/// Note that 'Value' is a string as the template argument's value is 900/// an arbitrary precision integer. 'Value' must be euqal to the canonical 901/// representation of that integral value in base 10. 902/// 903/// Given 904/// \code 905/// template<int T> struct A {}; 906/// C<42> c; 907/// \endcode 908/// classTemplateSpecializationDecl( 909/// hasAnyTemplateArgument(equalsIntegralValue("42"))) 910/// matches the implicit instantiation of C in C<42>. 911AST_MATCHER_P(TemplateArgument, equalsIntegralValue, 912 std::string, Value) { 913 if (Node.getKind() != TemplateArgument::Integral) 914 return false; 915 return Node.getAsIntegral().toString(10) == Value; 916} 917 918/// \brief Matches any value declaration. 919/// 920/// Example matches A, B, C and F 921/// \code 922/// enum X { A, B, C }; 923/// void F(); 924/// \endcode 925const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl; 926 927/// \brief Matches C++ constructor declarations. 928/// 929/// Example matches Foo::Foo() and Foo::Foo(int) 930/// \code 931/// class Foo { 932/// public: 933/// Foo(); 934/// Foo(int); 935/// int DoSomething(); 936/// }; 937/// \endcode 938const internal::VariadicDynCastAllOfMatcher< 939 Decl, 940 CXXConstructorDecl> cxxConstructorDecl; 941 942/// \brief Matches explicit C++ destructor declarations. 943/// 944/// Example matches Foo::~Foo() 945/// \code 946/// class Foo { 947/// public: 948/// virtual ~Foo(); 949/// }; 950/// \endcode 951const internal::VariadicDynCastAllOfMatcher< 952 Decl, 953 CXXDestructorDecl> cxxDestructorDecl; 954 955/// \brief Matches enum declarations. 956/// 957/// Example matches X 958/// \code 959/// enum X { 960/// A, B, C 961/// }; 962/// \endcode 963const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl; 964 965/// \brief Matches enum constants. 966/// 967/// Example matches A, B, C 968/// \code 969/// enum X { 970/// A, B, C 971/// }; 972/// \endcode 973const internal::VariadicDynCastAllOfMatcher< 974 Decl, 975 EnumConstantDecl> enumConstantDecl; 976 977/// \brief Matches method declarations. 978/// 979/// Example matches y 980/// \code 981/// class X { void y(); }; 982/// \endcode 983const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> cxxMethodDecl; 984 985/// \brief Matches conversion operator declarations. 986/// 987/// Example matches the operator. 988/// \code 989/// class X { operator int() const; }; 990/// \endcode 991const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl> 992 cxxConversionDecl; 993 994/// \brief Matches variable declarations. 995/// 996/// Note: this does not match declarations of member variables, which are 997/// "field" declarations in Clang parlance. 998/// 999/// Example matches a 1000/// \code 1001/// int a; 1002/// \endcode 1003const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl; 1004 1005/// \brief Matches field declarations. 1006/// 1007/// Given 1008/// \code 1009/// class X { int m; }; 1010/// \endcode 1011/// fieldDecl() 1012/// matches 'm'. 1013const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl; 1014 1015/// \brief Matches function declarations. 1016/// 1017/// Example matches f 1018/// \code 1019/// void f(); 1020/// \endcode 1021const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl; 1022 1023/// \brief Matches C++ function template declarations. 1024/// 1025/// Example matches f 1026/// \code 1027/// template<class T> void f(T t) {} 1028/// \endcode 1029const internal::VariadicDynCastAllOfMatcher< 1030 Decl, 1031 FunctionTemplateDecl> functionTemplateDecl; 1032 1033/// \brief Matches friend declarations. 1034/// 1035/// Given 1036/// \code 1037/// class X { friend void foo(); }; 1038/// \endcode 1039/// friendDecl() 1040/// matches 'friend void foo()'. 1041const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl; 1042 1043/// \brief Matches statements. 1044/// 1045/// Given 1046/// \code 1047/// { ++a; } 1048/// \endcode 1049/// stmt() 1050/// matches both the compound statement '{ ++a; }' and '++a'. 1051const internal::VariadicAllOfMatcher<Stmt> stmt; 1052 1053/// \brief Matches declaration statements. 1054/// 1055/// Given 1056/// \code 1057/// int a; 1058/// \endcode 1059/// declStmt() 1060/// matches 'int a'. 1061const internal::VariadicDynCastAllOfMatcher< 1062 Stmt, 1063 DeclStmt> declStmt; 1064 1065/// \brief Matches member expressions. 1066/// 1067/// Given 1068/// \code 1069/// class Y { 1070/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 1071/// int a; static int b; 1072/// }; 1073/// \endcode 1074/// memberExpr() 1075/// matches this->x, x, y.x, a, this->b 1076const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr; 1077 1078/// \brief Matches call expressions. 1079/// 1080/// Example matches x.y() and y() 1081/// \code 1082/// X x; 1083/// x.y(); 1084/// y(); 1085/// \endcode 1086const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr; 1087 1088/// \brief Matches lambda expressions. 1089/// 1090/// Example matches [&](){return 5;} 1091/// \code 1092/// [&](){return 5;} 1093/// \endcode 1094const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr; 1095 1096/// \brief Matches member call expressions. 1097/// 1098/// Example matches x.y() 1099/// \code 1100/// X x; 1101/// x.y(); 1102/// \endcode 1103const internal::VariadicDynCastAllOfMatcher< 1104 Stmt, 1105 CXXMemberCallExpr> cxxMemberCallExpr; 1106 1107/// \brief Matches ObjectiveC Message invocation expressions. 1108/// 1109/// The innermost message send invokes the "alloc" class method on the 1110/// NSString class, while the outermost message send invokes the 1111/// "initWithString" instance method on the object returned from 1112/// NSString's "alloc". This matcher should match both message sends. 1113/// \code 1114/// [[NSString alloc] initWithString:@"Hello"] 1115/// \endcode 1116const internal::VariadicDynCastAllOfMatcher< 1117 Stmt, 1118 ObjCMessageExpr> objcMessageExpr; 1119 1120/// \brief Matches Objective-C interface declarations. 1121/// 1122/// Example matches Foo 1123/// \code 1124/// @interface Foo 1125/// @end 1126/// \endcode 1127const internal::VariadicDynCastAllOfMatcher< 1128 Decl, 1129 ObjCInterfaceDecl> objcInterfaceDecl; 1130 1131/// \brief Matches Objective-C protocol declarations. 1132/// 1133/// Example matches FooDelegate 1134/// \code 1135/// @protocol FooDelegate 1136/// @end 1137/// \endcode 1138const internal::VariadicDynCastAllOfMatcher< 1139 Decl, 1140 ObjCProtocolDecl> objcProtocolDecl; 1141 1142/// \brief Matches Objective-C category declarations. 1143/// 1144/// Example matches Foo (Additions) 1145/// \code 1146/// @interface Foo (Additions) 1147/// @end 1148/// \endcode 1149const internal::VariadicDynCastAllOfMatcher< 1150 Decl, 1151 ObjCCategoryDecl> objcCategoryDecl; 1152 1153/// \brief Matches Objective-C method declarations. 1154/// 1155/// Example matches both declaration and definition of -[Foo method] 1156/// \code 1157/// @interface Foo 1158/// - (void)method; 1159/// @end 1160/// 1161/// @implementation Foo 1162/// - (void)method {} 1163/// @end 1164/// \endcode 1165const internal::VariadicDynCastAllOfMatcher< 1166 Decl, 1167 ObjCMethodDecl> objcMethodDecl; 1168 1169/// \brief Matches Objective-C instance variable declarations. 1170/// 1171/// Example matches _enabled 1172/// \code 1173/// @implementation Foo { 1174/// BOOL _enabled; 1175/// } 1176/// @end 1177/// \endcode 1178const internal::VariadicDynCastAllOfMatcher< 1179 Decl, 1180 ObjCIvarDecl> objcIvarDecl; 1181 1182/// \brief Matches Objective-C property declarations. 1183/// 1184/// Example matches enabled 1185/// \code 1186/// @interface Foo 1187/// @property BOOL enabled; 1188/// @end 1189/// \endcode 1190const internal::VariadicDynCastAllOfMatcher< 1191 Decl, 1192 ObjCPropertyDecl> objcPropertyDecl; 1193 1194/// \brief Matches expressions that introduce cleanups to be run at the end 1195/// of the sub-expression's evaluation. 1196/// 1197/// Example matches std::string() 1198/// \code 1199/// const std::string str = std::string(); 1200/// \endcode 1201const internal::VariadicDynCastAllOfMatcher< 1202 Stmt, 1203 ExprWithCleanups> exprWithCleanups; 1204 1205/// \brief Matches init list expressions. 1206/// 1207/// Given 1208/// \code 1209/// int a[] = { 1, 2 }; 1210/// struct B { int x, y; }; 1211/// B b = { 5, 6 }; 1212/// \endcode 1213/// initListExpr() 1214/// matches "{ 1, 2 }" and "{ 5, 6 }" 1215const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr; 1216 1217/// \brief Matches the syntactic form of init list expressions 1218/// (if expression have it). 1219AST_MATCHER_P(InitListExpr, hasSyntacticForm, 1220 internal::Matcher<Expr>, InnerMatcher) { 1221 const Expr *SyntForm = Node.getSyntacticForm(); 1222 return (SyntForm != nullptr && 1223 InnerMatcher.matches(*SyntForm, Finder, Builder)); 1224} 1225 1226/// \brief Matches implicit initializers of init list expressions. 1227/// 1228/// Given 1229/// \code 1230/// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; 1231/// \endcode 1232/// implicitValueInitExpr() 1233/// matches "[0].y" (implicitly) 1234const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr> 1235implicitValueInitExpr; 1236 1237/// \brief Matches paren list expressions. 1238/// ParenListExprs don't have a predefined type and are used for late parsing. 1239/// In the final AST, they can be met in template declarations. 1240/// 1241/// Given 1242/// \code 1243/// template<typename T> class X { 1244/// void f() { 1245/// X x(*this); 1246/// int a = 0, b = 1; int i = (a, b); 1247/// } 1248/// }; 1249/// \endcode 1250/// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b) 1251/// has a predefined type and is a ParenExpr, not a ParenListExpr. 1252const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr> parenListExpr; 1253 1254/// \brief Matches substitutions of non-type template parameters. 1255/// 1256/// Given 1257/// \code 1258/// template <int N> 1259/// struct A { static const int n = N; }; 1260/// struct B : public A<42> {}; 1261/// \endcode 1262/// substNonTypeTemplateParmExpr() 1263/// matches "N" in the right-hand side of "static const int n = N;" 1264const internal::VariadicDynCastAllOfMatcher< 1265 Stmt, 1266 SubstNonTypeTemplateParmExpr> substNonTypeTemplateParmExpr; 1267 1268/// \brief Matches using declarations. 1269/// 1270/// Given 1271/// \code 1272/// namespace X { int x; } 1273/// using X::x; 1274/// \endcode 1275/// usingDecl() 1276/// matches \code using X::x \endcode 1277const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl; 1278 1279/// \brief Matches using namespace declarations. 1280/// 1281/// Given 1282/// \code 1283/// namespace X { int x; } 1284/// using namespace X; 1285/// \endcode 1286/// usingDirectiveDecl() 1287/// matches \code using namespace X \endcode 1288const internal::VariadicDynCastAllOfMatcher< 1289 Decl, 1290 UsingDirectiveDecl> usingDirectiveDecl; 1291 1292/// \brief Matches reference to a name that can be looked up during parsing 1293/// but could not be resolved to a specific declaration. 1294/// 1295/// Given 1296/// \code 1297/// template<typename T> 1298/// T foo() { T a; return a; } 1299/// template<typename T> 1300/// void bar() { 1301/// foo<T>(); 1302/// } 1303/// \endcode 1304/// unresolvedLookupExpr() 1305/// matches \code foo<T>() \endcode 1306const internal::VariadicDynCastAllOfMatcher< 1307 Stmt, 1308 UnresolvedLookupExpr> unresolvedLookupExpr; 1309 1310/// \brief Matches unresolved using value declarations. 1311/// 1312/// Given 1313/// \code 1314/// template<typename X> 1315/// class C : private X { 1316/// using X::x; 1317/// }; 1318/// \endcode 1319/// unresolvedUsingValueDecl() 1320/// matches \code using X::x \endcode 1321const internal::VariadicDynCastAllOfMatcher< 1322 Decl, 1323 UnresolvedUsingValueDecl> unresolvedUsingValueDecl; 1324 1325/// \brief Matches unresolved using value declarations that involve the 1326/// typename. 1327/// 1328/// Given 1329/// \code 1330/// template <typename T> 1331/// struct Base { typedef T Foo; }; 1332/// 1333/// template<typename T> 1334/// struct S : private Base<T> { 1335/// using typename Base<T>::Foo; 1336/// }; 1337/// \endcode 1338/// unresolvedUsingTypenameDecl() 1339/// matches \code using Base<T>::Foo \endcode 1340const internal::VariadicDynCastAllOfMatcher< 1341 Decl, 1342 UnresolvedUsingTypenameDecl> unresolvedUsingTypenameDecl; 1343 1344/// \brief Matches parentheses used in expressions. 1345/// 1346/// Example matches (foo() + 1) 1347/// \code 1348/// int foo() { return 1; } 1349/// int a = (foo() + 1); 1350/// \endcode 1351const internal::VariadicDynCastAllOfMatcher< 1352 Stmt, 1353 ParenExpr> parenExpr; 1354 1355/// \brief Matches constructor call expressions (including implicit ones). 1356/// 1357/// Example matches string(ptr, n) and ptr within arguments of f 1358/// (matcher = cxxConstructExpr()) 1359/// \code 1360/// void f(const string &a, const string &b); 1361/// char *ptr; 1362/// int n; 1363/// f(string(ptr, n), ptr); 1364/// \endcode 1365const internal::VariadicDynCastAllOfMatcher< 1366 Stmt, 1367 CXXConstructExpr> cxxConstructExpr; 1368 1369/// \brief Matches unresolved constructor call expressions. 1370/// 1371/// Example matches T(t) in return statement of f 1372/// (matcher = cxxUnresolvedConstructExpr()) 1373/// \code 1374/// template <typename T> 1375/// void f(const T& t) { return T(t); } 1376/// \endcode 1377const internal::VariadicDynCastAllOfMatcher< 1378 Stmt, 1379 CXXUnresolvedConstructExpr> cxxUnresolvedConstructExpr; 1380 1381/// \brief Matches implicit and explicit this expressions. 1382/// 1383/// Example matches the implicit this expression in "return i". 1384/// (matcher = cxxThisExpr()) 1385/// \code 1386/// struct foo { 1387/// int i; 1388/// int f() { return i; } 1389/// }; 1390/// \endcode 1391const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> cxxThisExpr; 1392 1393/// \brief Matches nodes where temporaries are created. 1394/// 1395/// Example matches FunctionTakesString(GetStringByValue()) 1396/// (matcher = cxxBindTemporaryExpr()) 1397/// \code 1398/// FunctionTakesString(GetStringByValue()); 1399/// FunctionTakesStringByPointer(GetStringPointer()); 1400/// \endcode 1401const internal::VariadicDynCastAllOfMatcher< 1402 Stmt, 1403 CXXBindTemporaryExpr> cxxBindTemporaryExpr; 1404 1405/// \brief Matches nodes where temporaries are materialized. 1406/// 1407/// Example: Given 1408/// \code 1409/// struct T {void func()}; 1410/// T f(); 1411/// void g(T); 1412/// \endcode 1413/// materializeTemporaryExpr() matches 'f()' in these statements 1414/// \code 1415/// T u(f()); 1416/// g(f()); 1417/// \endcode 1418/// but does not match 1419/// \code 1420/// f(); 1421/// f().func(); 1422/// \endcode 1423const internal::VariadicDynCastAllOfMatcher< 1424 Stmt, 1425 MaterializeTemporaryExpr> materializeTemporaryExpr; 1426 1427/// \brief Matches new expressions. 1428/// 1429/// Given 1430/// \code 1431/// new X; 1432/// \endcode 1433/// cxxNewExpr() 1434/// matches 'new X'. 1435const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr; 1436 1437/// \brief Matches delete expressions. 1438/// 1439/// Given 1440/// \code 1441/// delete X; 1442/// \endcode 1443/// cxxDeleteExpr() 1444/// matches 'delete X'. 1445const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> cxxDeleteExpr; 1446 1447/// \brief Matches array subscript expressions. 1448/// 1449/// Given 1450/// \code 1451/// int i = a[1]; 1452/// \endcode 1453/// arraySubscriptExpr() 1454/// matches "a[1]" 1455const internal::VariadicDynCastAllOfMatcher< 1456 Stmt, 1457 ArraySubscriptExpr> arraySubscriptExpr; 1458 1459/// \brief Matches the value of a default argument at the call site. 1460/// 1461/// Example matches the CXXDefaultArgExpr placeholder inserted for the 1462/// default value of the second parameter in the call expression f(42) 1463/// (matcher = cxxDefaultArgExpr()) 1464/// \code 1465/// void f(int x, int y = 0); 1466/// f(42); 1467/// \endcode 1468const internal::VariadicDynCastAllOfMatcher< 1469 Stmt, 1470 CXXDefaultArgExpr> cxxDefaultArgExpr; 1471 1472/// \brief Matches overloaded operator calls. 1473/// 1474/// Note that if an operator isn't overloaded, it won't match. Instead, use 1475/// binaryOperator matcher. 1476/// Currently it does not match operators such as new delete. 1477/// FIXME: figure out why these do not match? 1478/// 1479/// Example matches both operator<<((o << b), c) and operator<<(o, b) 1480/// (matcher = cxxOperatorCallExpr()) 1481/// \code 1482/// ostream &operator<< (ostream &out, int i) { }; 1483/// ostream &o; int b = 1, c = 1; 1484/// o << b << c; 1485/// \endcode 1486const internal::VariadicDynCastAllOfMatcher< 1487 Stmt, 1488 CXXOperatorCallExpr> cxxOperatorCallExpr; 1489 1490/// \brief Matches expressions. 1491/// 1492/// Example matches x() 1493/// \code 1494/// void f() { x(); } 1495/// \endcode 1496const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr; 1497 1498/// \brief Matches expressions that refer to declarations. 1499/// 1500/// Example matches x in if (x) 1501/// \code 1502/// bool x; 1503/// if (x) {} 1504/// \endcode 1505const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr; 1506 1507/// \brief Matches if statements. 1508/// 1509/// Example matches 'if (x) {}' 1510/// \code 1511/// if (x) {} 1512/// \endcode 1513const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt; 1514 1515/// \brief Matches for statements. 1516/// 1517/// Example matches 'for (;;) {}' 1518/// \code 1519/// for (;;) {} 1520/// int i[] = {1, 2, 3}; for (auto a : i); 1521/// \endcode 1522const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt; 1523 1524/// \brief Matches the increment statement of a for loop. 1525/// 1526/// Example: 1527/// forStmt(hasIncrement(unaryOperator(hasOperatorName("++")))) 1528/// matches '++x' in 1529/// \code 1530/// for (x; x < N; ++x) { } 1531/// \endcode 1532AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>, 1533 InnerMatcher) { 1534 const Stmt *const Increment = Node.getInc(); 1535 return (Increment != nullptr && 1536 InnerMatcher.matches(*Increment, Finder, Builder)); 1537} 1538 1539/// \brief Matches the initialization statement of a for loop. 1540/// 1541/// Example: 1542/// forStmt(hasLoopInit(declStmt())) 1543/// matches 'int x = 0' in 1544/// \code 1545/// for (int x = 0; x < N; ++x) { } 1546/// \endcode 1547AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>, 1548 InnerMatcher) { 1549 const Stmt *const Init = Node.getInit(); 1550 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder)); 1551} 1552 1553/// \brief Matches range-based for statements. 1554/// 1555/// cxxForRangeStmt() matches 'for (auto a : i)' 1556/// \code 1557/// int i[] = {1, 2, 3}; for (auto a : i); 1558/// for(int j = 0; j < 5; ++j); 1559/// \endcode 1560const internal::VariadicDynCastAllOfMatcher< 1561 Stmt, 1562 CXXForRangeStmt> cxxForRangeStmt; 1563 1564/// \brief Matches the initialization statement of a for loop. 1565/// 1566/// Example: 1567/// forStmt(hasLoopVariable(anything())) 1568/// matches 'int x' in 1569/// \code 1570/// for (int x : a) { } 1571/// \endcode 1572AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>, 1573 InnerMatcher) { 1574 const VarDecl *const Var = Node.getLoopVariable(); 1575 return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder)); 1576} 1577 1578/// \brief Matches the range initialization statement of a for loop. 1579/// 1580/// Example: 1581/// forStmt(hasRangeInit(anything())) 1582/// matches 'a' in 1583/// \code 1584/// for (int x : a) { } 1585/// \endcode 1586AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>, 1587 InnerMatcher) { 1588 const Expr *const Init = Node.getRangeInit(); 1589 return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder)); 1590} 1591 1592/// \brief Matches while statements. 1593/// 1594/// Given 1595/// \code 1596/// while (true) {} 1597/// \endcode 1598/// whileStmt() 1599/// matches 'while (true) {}'. 1600const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt; 1601 1602/// \brief Matches do statements. 1603/// 1604/// Given 1605/// \code 1606/// do {} while (true); 1607/// \endcode 1608/// doStmt() 1609/// matches 'do {} while(true)' 1610const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt; 1611 1612/// \brief Matches break statements. 1613/// 1614/// Given 1615/// \code 1616/// while (true) { break; } 1617/// \endcode 1618/// breakStmt() 1619/// matches 'break' 1620const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt; 1621 1622/// \brief Matches continue statements. 1623/// 1624/// Given 1625/// \code 1626/// while (true) { continue; } 1627/// \endcode 1628/// continueStmt() 1629/// matches 'continue' 1630const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt; 1631 1632/// \brief Matches return statements. 1633/// 1634/// Given 1635/// \code 1636/// return 1; 1637/// \endcode 1638/// returnStmt() 1639/// matches 'return 1' 1640const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt; 1641 1642/// \brief Matches goto statements. 1643/// 1644/// Given 1645/// \code 1646/// goto FOO; 1647/// FOO: bar(); 1648/// \endcode 1649/// gotoStmt() 1650/// matches 'goto FOO' 1651const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt; 1652 1653/// \brief Matches label statements. 1654/// 1655/// Given 1656/// \code 1657/// goto FOO; 1658/// FOO: bar(); 1659/// \endcode 1660/// labelStmt() 1661/// matches 'FOO:' 1662const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt; 1663 1664/// \brief Matches address of label statements (GNU extension). 1665/// 1666/// Given 1667/// \code 1668/// FOO: bar(); 1669/// void *ptr = &&FOO; 1670/// goto *bar; 1671/// \endcode 1672/// addrLabelExpr() 1673/// matches '&&FOO' 1674const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr> addrLabelExpr; 1675 1676/// \brief Matches switch statements. 1677/// 1678/// Given 1679/// \code 1680/// switch(a) { case 42: break; default: break; } 1681/// \endcode 1682/// switchStmt() 1683/// matches 'switch(a)'. 1684const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt; 1685 1686/// \brief Matches case and default statements inside switch statements. 1687/// 1688/// Given 1689/// \code 1690/// switch(a) { case 42: break; default: break; } 1691/// \endcode 1692/// switchCase() 1693/// matches 'case 42: break;' and 'default: break;'. 1694const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase; 1695 1696/// \brief Matches case statements inside switch statements. 1697/// 1698/// Given 1699/// \code 1700/// switch(a) { case 42: break; default: break; } 1701/// \endcode 1702/// caseStmt() 1703/// matches 'case 42: break;'. 1704const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt; 1705 1706/// \brief Matches default statements inside switch statements. 1707/// 1708/// Given 1709/// \code 1710/// switch(a) { case 42: break; default: break; } 1711/// \endcode 1712/// defaultStmt() 1713/// matches 'default: break;'. 1714const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt> defaultStmt; 1715 1716/// \brief Matches compound statements. 1717/// 1718/// Example matches '{}' and '{{}}'in 'for (;;) {{}}' 1719/// \code 1720/// for (;;) {{}} 1721/// \endcode 1722const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt; 1723 1724/// \brief Matches catch statements. 1725/// 1726/// \code 1727/// try {} catch(int i) {} 1728/// \endcode 1729/// cxxCatchStmt() 1730/// matches 'catch(int i)' 1731const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> cxxCatchStmt; 1732 1733/// \brief Matches try statements. 1734/// 1735/// \code 1736/// try {} catch(int i) {} 1737/// \endcode 1738/// cxxTryStmt() 1739/// matches 'try {}' 1740const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt; 1741 1742/// \brief Matches throw expressions. 1743/// 1744/// \code 1745/// try { throw 5; } catch(int i) {} 1746/// \endcode 1747/// cxxThrowExpr() 1748/// matches 'throw 5' 1749const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> cxxThrowExpr; 1750 1751/// \brief Matches null statements. 1752/// 1753/// \code 1754/// foo();; 1755/// \endcode 1756/// nullStmt() 1757/// matches the second ';' 1758const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt; 1759 1760/// \brief Matches asm statements. 1761/// 1762/// \code 1763/// int i = 100; 1764/// __asm("mov al, 2"); 1765/// \endcode 1766/// asmStmt() 1767/// matches '__asm("mov al, 2")' 1768const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt; 1769 1770/// \brief Matches bool literals. 1771/// 1772/// Example matches true 1773/// \code 1774/// true 1775/// \endcode 1776const internal::VariadicDynCastAllOfMatcher< 1777 Stmt, 1778 CXXBoolLiteralExpr> cxxBoolLiteral; 1779 1780/// \brief Matches string literals (also matches wide string literals). 1781/// 1782/// Example matches "abcd", L"abcd" 1783/// \code 1784/// char *s = "abcd"; 1785/// wchar_t *ws = L"abcd"; 1786/// \endcode 1787const internal::VariadicDynCastAllOfMatcher< 1788 Stmt, 1789 StringLiteral> stringLiteral; 1790 1791/// \brief Matches character literals (also matches wchar_t). 1792/// 1793/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral), 1794/// though. 1795/// 1796/// Example matches 'a', L'a' 1797/// \code 1798/// char ch = 'a'; 1799/// wchar_t chw = L'a'; 1800/// \endcode 1801const internal::VariadicDynCastAllOfMatcher< 1802 Stmt, 1803 CharacterLiteral> characterLiteral; 1804 1805/// \brief Matches integer literals of all sizes / encodings, e.g. 1806/// 1, 1L, 0x1 and 1U. 1807/// 1808/// Does not match character-encoded integers such as L'a'. 1809const internal::VariadicDynCastAllOfMatcher< 1810 Stmt, 1811 IntegerLiteral> integerLiteral; 1812 1813/// \brief Matches float literals of all sizes / encodings, e.g. 1814/// 1.0, 1.0f, 1.0L and 1e10. 1815/// 1816/// Does not match implicit conversions such as 1817/// \code 1818/// float a = 10; 1819/// \endcode 1820const internal::VariadicDynCastAllOfMatcher< 1821 Stmt, 1822 FloatingLiteral> floatLiteral; 1823 1824/// \brief Matches user defined literal operator call. 1825/// 1826/// Example match: "foo"_suffix 1827const internal::VariadicDynCastAllOfMatcher< 1828 Stmt, 1829 UserDefinedLiteral> userDefinedLiteral; 1830 1831/// \brief Matches compound (i.e. non-scalar) literals 1832/// 1833/// Example match: {1}, (1, 2) 1834/// \code 1835/// int array[4] = {1}; 1836/// vector int myvec = (vector int)(1, 2); 1837/// \endcode 1838const internal::VariadicDynCastAllOfMatcher< 1839 Stmt, 1840 CompoundLiteralExpr> compoundLiteralExpr; 1841 1842/// \brief Matches nullptr literal. 1843const internal::VariadicDynCastAllOfMatcher< 1844 Stmt, 1845 CXXNullPtrLiteralExpr> cxxNullPtrLiteralExpr; 1846 1847/// \brief Matches GNU __null expression. 1848const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr> gnuNullExpr; 1849 1850/// \brief Matches atomic builtins. 1851/// Example matches __atomic_load_n(ptr, 1) 1852/// \code 1853/// void foo() { int *ptr; __atomic_load_n(ptr, 1); } 1854/// \endcode 1855const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr; 1856 1857/// \brief Matches statement expression (GNU extension). 1858/// 1859/// Example match: ({ int X = 4; X; }) 1860/// \code 1861/// int C = ({ int X = 4; X; }); 1862/// \endcode 1863const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr; 1864 1865/// \brief Matches binary operator expressions. 1866/// 1867/// Example matches a || b 1868/// \code 1869/// !(a || b) 1870/// \endcode 1871const internal::VariadicDynCastAllOfMatcher< 1872 Stmt, 1873 BinaryOperator> binaryOperator; 1874 1875/// \brief Matches unary operator expressions. 1876/// 1877/// Example matches !a 1878/// \code 1879/// !a || b 1880/// \endcode 1881const internal::VariadicDynCastAllOfMatcher< 1882 Stmt, 1883 UnaryOperator> unaryOperator; 1884 1885/// \brief Matches conditional operator expressions. 1886/// 1887/// Example matches a ? b : c 1888/// \code 1889/// (a ? b : c) + 42 1890/// \endcode 1891const internal::VariadicDynCastAllOfMatcher< 1892 Stmt, 1893 ConditionalOperator> conditionalOperator; 1894 1895/// \brief Matches binary conditional operator expressions (GNU extension). 1896/// 1897/// Example matches a ?: b 1898/// \code 1899/// (a ?: b) + 42; 1900/// \endcode 1901const internal::VariadicDynCastAllOfMatcher< 1902 Stmt, 1903 BinaryConditionalOperator> binaryConditionalOperator; 1904 1905/// \brief Matches opaque value expressions. They are used as helpers 1906/// to reference another expressions and can be met 1907/// in BinaryConditionalOperators, for example. 1908/// 1909/// Example matches 'a' 1910/// \code 1911/// (a ?: c) + 42; 1912/// \endcode 1913const internal::VariadicDynCastAllOfMatcher< 1914 Stmt, 1915 OpaqueValueExpr> opaqueValueExpr; 1916 1917/// \brief Matches a C++ static_assert declaration. 1918/// 1919/// Example: 1920/// staticAssertExpr() 1921/// matches 1922/// static_assert(sizeof(S) == sizeof(int)) 1923/// in 1924/// \code 1925/// struct S { 1926/// int x; 1927/// }; 1928/// static_assert(sizeof(S) == sizeof(int)); 1929/// \endcode 1930const internal::VariadicDynCastAllOfMatcher< 1931 Decl, 1932 StaticAssertDecl> staticAssertDecl; 1933 1934/// \brief Matches a reinterpret_cast expression. 1935/// 1936/// Either the source expression or the destination type can be matched 1937/// using has(), but hasDestinationType() is more specific and can be 1938/// more readable. 1939/// 1940/// Example matches reinterpret_cast<char*>(&p) in 1941/// \code 1942/// void* p = reinterpret_cast<char*>(&p); 1943/// \endcode 1944const internal::VariadicDynCastAllOfMatcher< 1945 Stmt, 1946 CXXReinterpretCastExpr> cxxReinterpretCastExpr; 1947 1948/// \brief Matches a C++ static_cast expression. 1949/// 1950/// \see hasDestinationType 1951/// \see reinterpretCast 1952/// 1953/// Example: 1954/// cxxStaticCastExpr() 1955/// matches 1956/// static_cast<long>(8) 1957/// in 1958/// \code 1959/// long eight(static_cast<long>(8)); 1960/// \endcode 1961const internal::VariadicDynCastAllOfMatcher< 1962 Stmt, 1963 CXXStaticCastExpr> cxxStaticCastExpr; 1964 1965/// \brief Matches a dynamic_cast expression. 1966/// 1967/// Example: 1968/// cxxDynamicCastExpr() 1969/// matches 1970/// dynamic_cast<D*>(&b); 1971/// in 1972/// \code 1973/// struct B { virtual ~B() {} }; struct D : B {}; 1974/// B b; 1975/// D* p = dynamic_cast<D*>(&b); 1976/// \endcode 1977const internal::VariadicDynCastAllOfMatcher< 1978 Stmt, 1979 CXXDynamicCastExpr> cxxDynamicCastExpr; 1980 1981/// \brief Matches a const_cast expression. 1982/// 1983/// Example: Matches const_cast<int*>(&r) in 1984/// \code 1985/// int n = 42; 1986/// const int &r(n); 1987/// int* p = const_cast<int*>(&r); 1988/// \endcode 1989const internal::VariadicDynCastAllOfMatcher< 1990 Stmt, 1991 CXXConstCastExpr> cxxConstCastExpr; 1992 1993/// \brief Matches a C-style cast expression. 1994/// 1995/// Example: Matches (int) 2.2f in 1996/// \code 1997/// int i = (int) 2.2f; 1998/// \endcode 1999const internal::VariadicDynCastAllOfMatcher< 2000 Stmt, 2001 CStyleCastExpr> cStyleCastExpr; 2002 2003/// \brief Matches explicit cast expressions. 2004/// 2005/// Matches any cast expression written in user code, whether it be a 2006/// C-style cast, a functional-style cast, or a keyword cast. 2007/// 2008/// Does not match implicit conversions. 2009/// 2010/// Note: the name "explicitCast" is chosen to match Clang's terminology, as 2011/// Clang uses the term "cast" to apply to implicit conversions as well as to 2012/// actual cast expressions. 2013/// 2014/// \see hasDestinationType. 2015/// 2016/// Example: matches all five of the casts in 2017/// \code 2018/// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42))))) 2019/// \endcode 2020/// but does not match the implicit conversion in 2021/// \code 2022/// long ell = 42; 2023/// \endcode 2024const internal::VariadicDynCastAllOfMatcher< 2025 Stmt, 2026 ExplicitCastExpr> explicitCastExpr; 2027 2028/// \brief Matches the implicit cast nodes of Clang's AST. 2029/// 2030/// This matches many different places, including function call return value 2031/// eliding, as well as any type conversions. 2032const internal::VariadicDynCastAllOfMatcher< 2033 Stmt, 2034 ImplicitCastExpr> implicitCastExpr; 2035 2036/// \brief Matches any cast nodes of Clang's AST. 2037/// 2038/// Example: castExpr() matches each of the following: 2039/// \code 2040/// (int) 3; 2041/// const_cast<Expr *>(SubExpr); 2042/// char c = 0; 2043/// \endcode 2044/// but does not match 2045/// \code 2046/// int i = (0); 2047/// int k = 0; 2048/// \endcode 2049const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr; 2050 2051/// \brief Matches functional cast expressions 2052/// 2053/// Example: Matches Foo(bar); 2054/// \code 2055/// Foo f = bar; 2056/// Foo g = (Foo) bar; 2057/// Foo h = Foo(bar); 2058/// \endcode 2059const internal::VariadicDynCastAllOfMatcher< 2060 Stmt, 2061 CXXFunctionalCastExpr> cxxFunctionalCastExpr; 2062 2063/// \brief Matches functional cast expressions having N != 1 arguments 2064/// 2065/// Example: Matches Foo(bar, bar) 2066/// \code 2067/// Foo h = Foo(bar, bar); 2068/// \endcode 2069const internal::VariadicDynCastAllOfMatcher< 2070 Stmt, 2071 CXXTemporaryObjectExpr> cxxTemporaryObjectExpr; 2072 2073/// \brief Matches predefined identifier expressions [C99 6.4.2.2]. 2074/// 2075/// Example: Matches __func__ 2076/// \code 2077/// printf("%s", __func__); 2078/// \endcode 2079const internal::VariadicDynCastAllOfMatcher< 2080 Stmt, 2081 PredefinedExpr> predefinedExpr; 2082 2083/// \brief Matches C99 designated initializer expressions [C99 6.7.8]. 2084/// 2085/// Example: Matches { [2].y = 1.0, [0].x = 1.0 } 2086/// \code 2087/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 }; 2088/// \endcode 2089const internal::VariadicDynCastAllOfMatcher< 2090 Stmt, 2091 DesignatedInitExpr> designatedInitExpr; 2092 2093/// \brief Matches designated initializer expressions that contain 2094/// a specific number of designators. 2095/// 2096/// Example: Given 2097/// \code 2098/// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 }; 2099/// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }; 2100/// \endcode 2101/// designatorCountIs(2) 2102/// matches '{ [2].y = 1.0, [0].x = 1.0 }', 2103/// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'. 2104AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) { 2105 return Node.size() == N; 2106} 2107 2108/// \brief Matches \c QualTypes in the clang AST. 2109const internal::VariadicAllOfMatcher<QualType> qualType; 2110 2111/// \brief Matches \c Types in the clang AST. 2112const internal::VariadicAllOfMatcher<Type> type; 2113 2114/// \brief Matches \c TypeLocs in the clang AST. 2115const internal::VariadicAllOfMatcher<TypeLoc> typeLoc; 2116 2117/// \brief Matches if any of the given matchers matches. 2118/// 2119/// Unlike \c anyOf, \c eachOf will generate a match result for each 2120/// matching submatcher. 2121/// 2122/// For example, in: 2123/// \code 2124/// class A { int a; int b; }; 2125/// \endcode 2126/// The matcher: 2127/// \code 2128/// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")), 2129/// has(fieldDecl(hasName("b")).bind("v")))) 2130/// \endcode 2131/// will generate two results binding "v", the first of which binds 2132/// the field declaration of \c a, the second the field declaration of 2133/// \c b. 2134/// 2135/// Usable as: Any Matcher 2136const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> eachOf = { 2137 internal::DynTypedMatcher::VO_EachOf 2138}; 2139 2140/// \brief Matches if any of the given matchers matches. 2141/// 2142/// Usable as: Any Matcher 2143const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> anyOf = { 2144 internal::DynTypedMatcher::VO_AnyOf 2145}; 2146 2147/// \brief Matches if all given matchers match. 2148/// 2149/// Usable as: Any Matcher 2150const internal::VariadicOperatorMatcherFunc<2, UINT_MAX> allOf = { 2151 internal::DynTypedMatcher::VO_AllOf 2152}; 2153 2154/// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL) 2155/// 2156/// Given 2157/// \code 2158/// Foo x = bar; 2159/// int y = sizeof(x) + alignof(x); 2160/// \endcode 2161/// unaryExprOrTypeTraitExpr() 2162/// matches \c sizeof(x) and \c alignof(x) 2163const internal::VariadicDynCastAllOfMatcher< 2164 Stmt, 2165 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr; 2166 2167/// \brief Matches unary expressions that have a specific type of argument. 2168/// 2169/// Given 2170/// \code 2171/// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c); 2172/// \endcode 2173/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int")) 2174/// matches \c sizeof(a) and \c alignof(c) 2175AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType, 2176 internal::Matcher<QualType>, InnerMatcher) { 2177 const QualType ArgumentType = Node.getTypeOfArgument(); 2178 return InnerMatcher.matches(ArgumentType, Finder, Builder); 2179} 2180 2181/// \brief Matches unary expressions of a certain kind. 2182/// 2183/// Given 2184/// \code 2185/// int x; 2186/// int s = sizeof(x) + alignof(x) 2187/// \endcode 2188/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf)) 2189/// matches \c sizeof(x) 2190AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) { 2191 return Node.getKind() == Kind; 2192} 2193 2194/// \brief Same as unaryExprOrTypeTraitExpr, but only matching 2195/// alignof. 2196inline internal::Matcher<Stmt> alignOfExpr( 2197 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) { 2198 return stmt(unaryExprOrTypeTraitExpr(allOf( 2199 ofKind(UETT_AlignOf), InnerMatcher))); 2200} 2201 2202/// \brief Same as unaryExprOrTypeTraitExpr, but only matching 2203/// sizeof. 2204inline internal::Matcher<Stmt> sizeOfExpr( 2205 const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) { 2206 return stmt(unaryExprOrTypeTraitExpr( 2207 allOf(ofKind(UETT_SizeOf), InnerMatcher))); 2208} 2209 2210/// \brief Matches NamedDecl nodes that have the specified name. 2211/// 2212/// Supports specifying enclosing namespaces or classes by prefixing the name 2213/// with '<enclosing>::'. 2214/// Does not match typedefs of an underlying type with the given name. 2215/// 2216/// Example matches X (Name == "X") 2217/// \code 2218/// class X; 2219/// \endcode 2220/// 2221/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X") 2222/// \code 2223/// namespace a { namespace b { class X; } } 2224/// \endcode 2225inline internal::Matcher<NamedDecl> hasName(const std::string &Name) { 2226 std::vector<std::string> Names; 2227 Names.push_back(Name); 2228 return internal::Matcher<NamedDecl>(new internal::HasNameMatcher(Names)); 2229} 2230 2231/// \brief Matches NamedDecl nodes that have any of the specified names. 2232/// 2233/// This matcher is only provided as a performance optimization of hasName. 2234/// \code 2235/// hasAnyName(a, b, c) 2236/// \endcode 2237/// is equivalent to, but faster than 2238/// \code 2239/// anyOf(hasName(a), hasName(b), hasName(c)) 2240/// \endcode 2241const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef, 2242 internal::hasAnyNameFunc> 2243 hasAnyName = {}; 2244 2245/// \brief Matches NamedDecl nodes whose fully qualified names contain 2246/// a substring matched by the given RegExp. 2247/// 2248/// Supports specifying enclosing namespaces or classes by 2249/// prefixing the name with '<enclosing>::'. Does not match typedefs 2250/// of an underlying type with the given name. 2251/// 2252/// Example matches X (regexp == "::X") 2253/// \code 2254/// class X; 2255/// \endcode 2256/// 2257/// Example matches X (regexp is one of "::X", "^foo::.*X", among others) 2258/// \code 2259/// namespace foo { namespace bar { class X; } } 2260/// \endcode 2261AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) { 2262 assert(!RegExp.empty()); 2263 std::string FullNameString = "::" + Node.getQualifiedNameAsString(); 2264 llvm::Regex RE(RegExp); 2265 return RE.match(FullNameString); 2266} 2267 2268/// \brief Matches overloaded operator names. 2269/// 2270/// Matches overloaded operator names specified in strings without the 2271/// "operator" prefix: e.g. "<<". 2272/// 2273/// Given: 2274/// \code 2275/// class A { int operator*(); }; 2276/// const A &operator<<(const A &a, const A &b); 2277/// A a; 2278/// a << a; // <-- This matches 2279/// \endcode 2280/// 2281/// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the 2282/// specified line and 2283/// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*"))) 2284/// matches the declaration of \c A. 2285/// 2286/// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl> 2287inline internal::PolymorphicMatcherWithParam1< 2288 internal::HasOverloadedOperatorNameMatcher, StringRef, 2289 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)> 2290hasOverloadedOperatorName(StringRef Name) { 2291 return internal::PolymorphicMatcherWithParam1< 2292 internal::HasOverloadedOperatorNameMatcher, StringRef, 2293 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl)>(Name); 2294} 2295 2296/// \brief Matches C++ classes that are directly or indirectly derived from 2297/// a class matching \c Base. 2298/// 2299/// Note that a class is not considered to be derived from itself. 2300/// 2301/// Example matches Y, Z, C (Base == hasName("X")) 2302/// \code 2303/// class X; 2304/// class Y : public X {}; // directly derived 2305/// class Z : public Y {}; // indirectly derived 2306/// typedef X A; 2307/// typedef A B; 2308/// class C : public B {}; // derived from a typedef of X 2309/// \endcode 2310/// 2311/// In the following example, Bar matches isDerivedFrom(hasName("X")): 2312/// \code 2313/// class Foo; 2314/// typedef Foo X; 2315/// class Bar : public Foo {}; // derived from a type that X is a typedef of 2316/// \endcode 2317AST_MATCHER_P(CXXRecordDecl, isDerivedFrom, 2318 internal::Matcher<NamedDecl>, Base) { 2319 return Finder->classIsDerivedFrom(&Node, Base, Builder); 2320} 2321 2322/// \brief Overloaded method as shortcut for \c isDerivedFrom(hasName(...)). 2323AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isDerivedFrom, std::string, BaseName, 1) { 2324 assert(!BaseName.empty()); 2325 return isDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder); 2326} 2327 2328/// \brief Similar to \c isDerivedFrom(), but also matches classes that directly 2329/// match \c Base. 2330AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, 2331 internal::Matcher<NamedDecl>, Base, 0) { 2332 return Matcher<CXXRecordDecl>(anyOf(Base, isDerivedFrom(Base))) 2333 .matches(Node, Finder, Builder); 2334} 2335 2336/// \brief Overloaded method as shortcut for 2337/// \c isSameOrDerivedFrom(hasName(...)). 2338AST_MATCHER_P_OVERLOAD(CXXRecordDecl, isSameOrDerivedFrom, std::string, 2339 BaseName, 1) { 2340 assert(!BaseName.empty()); 2341 return isSameOrDerivedFrom(hasName(BaseName)).matches(Node, Finder, Builder); 2342} 2343 2344/// \brief Matches the first method of a class or struct that satisfies \c 2345/// InnerMatcher. 2346/// 2347/// Given: 2348/// \code 2349/// class A { void func(); }; 2350/// class B { void member(); }; 2351/// \endcode 2352/// 2353/// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of 2354/// \c A but not \c B. 2355AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>, 2356 InnerMatcher) { 2357 return matchesFirstInPointerRange(InnerMatcher, Node.method_begin(), 2358 Node.method_end(), Finder, Builder); 2359} 2360 2361/// \brief Matches the generated class of lambda expressions. 2362/// 2363/// Given: 2364/// \code 2365/// auto x = []{}; 2366/// \endcode 2367/// 2368/// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of 2369/// \c decltype(x) 2370AST_MATCHER(CXXRecordDecl, isLambda) { 2371 return Node.isLambda(); 2372} 2373 2374/// \brief Matches AST nodes that have child AST nodes that match the 2375/// provided matcher. 2376/// 2377/// Example matches X, Y 2378/// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X"))) 2379/// \code 2380/// class X {}; // Matches X, because X::X is a class of name X inside X. 2381/// class Y { class X {}; }; 2382/// class Z { class Y { class X {}; }; }; // Does not match Z. 2383/// \endcode 2384/// 2385/// ChildT must be an AST base type. 2386/// 2387/// Usable as: Any Matcher 2388/// Note that has is direct matcher, so it also matches things like implicit 2389/// casts and paren casts. If you are matching with expr then you should 2390/// probably consider using ignoringParenImpCasts like: 2391/// has(ignoringParenImpCasts(expr())). 2392const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> 2393LLVM_ATTRIBUTE_UNUSED has = {}; 2394 2395/// \brief Matches AST nodes that have descendant AST nodes that match the 2396/// provided matcher. 2397/// 2398/// Example matches X, Y, Z 2399/// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X"))))) 2400/// \code 2401/// class X {}; // Matches X, because X::X is a class of name X inside X. 2402/// class Y { class X {}; }; 2403/// class Z { class Y { class X {}; }; }; 2404/// \endcode 2405/// 2406/// DescendantT must be an AST base type. 2407/// 2408/// Usable as: Any Matcher 2409const internal::ArgumentAdaptingMatcherFunc<internal::HasDescendantMatcher> 2410LLVM_ATTRIBUTE_UNUSED hasDescendant = {}; 2411 2412/// \brief Matches AST nodes that have child AST nodes that match the 2413/// provided matcher. 2414/// 2415/// Example matches X, Y 2416/// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X"))) 2417/// \code 2418/// class X {}; // Matches X, because X::X is a class of name X inside X. 2419/// class Y { class X {}; }; 2420/// class Z { class Y { class X {}; }; }; // Does not match Z. 2421/// \endcode 2422/// 2423/// ChildT must be an AST base type. 2424/// 2425/// As opposed to 'has', 'forEach' will cause a match for each result that 2426/// matches instead of only on the first one. 2427/// 2428/// Usable as: Any Matcher 2429const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher> 2430LLVM_ATTRIBUTE_UNUSED forEach = {}; 2431 2432/// \brief Matches AST nodes that have descendant AST nodes that match the 2433/// provided matcher. 2434/// 2435/// Example matches X, A, B, C 2436/// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X"))))) 2437/// \code 2438/// class X {}; // Matches X, because X::X is a class of name X inside X. 2439/// class A { class X {}; }; 2440/// class B { class C { class X {}; }; }; 2441/// \endcode 2442/// 2443/// DescendantT must be an AST base type. 2444/// 2445/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for 2446/// each result that matches instead of only on the first one. 2447/// 2448/// Note: Recursively combined ForEachDescendant can cause many matches: 2449/// cxxRecordDecl(forEachDescendant(cxxRecordDecl( 2450/// forEachDescendant(cxxRecordDecl()) 2451/// ))) 2452/// will match 10 times (plus injected class name matches) on: 2453/// \code 2454/// class A { class B { class C { class D { class E {}; }; }; }; }; 2455/// \endcode 2456/// 2457/// Usable as: Any Matcher 2458const internal::ArgumentAdaptingMatcherFunc<internal::ForEachDescendantMatcher> 2459LLVM_ATTRIBUTE_UNUSED forEachDescendant = {}; 2460 2461/// \brief Matches if the node or any descendant matches. 2462/// 2463/// Generates results for each match. 2464/// 2465/// For example, in: 2466/// \code 2467/// class A { class B {}; class C {}; }; 2468/// \endcode 2469/// The matcher: 2470/// \code 2471/// cxxRecordDecl(hasName("::A"), 2472/// findAll(cxxRecordDecl(isDefinition()).bind("m"))) 2473/// \endcode 2474/// will generate results for \c A, \c B and \c C. 2475/// 2476/// Usable as: Any Matcher 2477template <typename T> 2478internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) { 2479 return eachOf(Matcher, forEachDescendant(Matcher)); 2480} 2481 2482/// \brief Matches AST nodes that have a parent that matches the provided 2483/// matcher. 2484/// 2485/// Given 2486/// \code 2487/// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } } 2488/// \endcode 2489/// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }". 2490/// 2491/// Usable as: Any Matcher 2492const internal::ArgumentAdaptingMatcherFunc< 2493 internal::HasParentMatcher, 2494 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>, 2495 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>> 2496 LLVM_ATTRIBUTE_UNUSED hasParent = {}; 2497 2498/// \brief Matches AST nodes that have an ancestor that matches the provided 2499/// matcher. 2500/// 2501/// Given 2502/// \code 2503/// void f() { if (true) { int x = 42; } } 2504/// void g() { for (;;) { int x = 43; } } 2505/// \endcode 2506/// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43. 2507/// 2508/// Usable as: Any Matcher 2509const internal::ArgumentAdaptingMatcherFunc< 2510 internal::HasAncestorMatcher, 2511 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>, 2512 internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>> 2513 LLVM_ATTRIBUTE_UNUSED hasAncestor = {}; 2514 2515/// \brief Matches if the provided matcher does not match. 2516/// 2517/// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X")))) 2518/// \code 2519/// class X {}; 2520/// class Y {}; 2521/// \endcode 2522/// 2523/// Usable as: Any Matcher 2524const internal::VariadicOperatorMatcherFunc<1, 1> unless = { 2525 internal::DynTypedMatcher::VO_UnaryNot 2526}; 2527 2528/// \brief Matches a node if the declaration associated with that node 2529/// matches the given matcher. 2530/// 2531/// The associated declaration is: 2532/// - for type nodes, the declaration of the underlying type 2533/// - for CallExpr, the declaration of the callee 2534/// - for MemberExpr, the declaration of the referenced member 2535/// - for CXXConstructExpr, the declaration of the constructor 2536/// - for CXXNewExpr, the declaration of the operator new 2537/// 2538/// Also usable as Matcher<T> for any T supporting the getDecl() member 2539/// function. e.g. various subtypes of clang::Type and various expressions. 2540/// 2541/// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>, 2542/// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>, 2543/// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>, 2544/// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>, 2545/// Matcher<TagType>, Matcher<TemplateSpecializationType>, 2546/// Matcher<TemplateTypeParmType>, Matcher<TypedefType>, 2547/// Matcher<UnresolvedUsingType> 2548inline internal::PolymorphicMatcherWithParam1< 2549 internal::HasDeclarationMatcher, internal::Matcher<Decl>, 2550 void(internal::HasDeclarationSupportedTypes)> 2551hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) { 2552 return internal::PolymorphicMatcherWithParam1< 2553 internal::HasDeclarationMatcher, internal::Matcher<Decl>, 2554 void(internal::HasDeclarationSupportedTypes)>(InnerMatcher); 2555} 2556 2557/// \brief Matches a \c NamedDecl whose underlying declaration matches the given 2558/// matcher. 2559/// 2560/// Given 2561/// \code 2562/// namespace N { template<class T> void f(T t); } 2563/// template <class T> void g() { using N::f; f(T()); } 2564/// \endcode 2565/// \c unresolvedLookupExpr(hasAnyDeclaration( 2566/// namedDecl(hasUnderlyingDecl(hasName("::N::f"))))) 2567/// matches the use of \c f in \c g() . 2568AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>, 2569 InnerMatcher) { 2570 const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl(); 2571 2572 return UnderlyingDecl != nullptr && 2573 InnerMatcher.matches(*UnderlyingDecl, Finder, Builder); 2574} 2575 2576/// \brief Matches on the implicit object argument of a member call expression. 2577/// 2578/// Example matches y.x() 2579/// (matcher = cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y")))))) 2580/// \code 2581/// class Y { public: void x(); }; 2582/// void z() { Y y; y.x(); }", 2583/// \endcode 2584/// 2585/// FIXME: Overload to allow directly matching types? 2586AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>, 2587 InnerMatcher) { 2588 const Expr *ExprNode = Node.getImplicitObjectArgument() 2589 ->IgnoreParenImpCasts(); 2590 return (ExprNode != nullptr && 2591 InnerMatcher.matches(*ExprNode, Finder, Builder)); 2592} 2593 2594 2595/// \brief Matches on the receiver of an ObjectiveC Message expression. 2596/// 2597/// Example 2598/// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *"))); 2599/// matches the [webView ...] message invocation. 2600/// \code 2601/// NSString *webViewJavaScript = ... 2602/// UIWebView *webView = ... 2603/// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript]; 2604/// \endcode 2605AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>, 2606 InnerMatcher) { 2607 const QualType TypeDecl = Node.getReceiverType(); 2608 return InnerMatcher.matches(TypeDecl, Finder, Builder); 2609} 2610 2611/// \brief Matches when BaseName == Selector.getAsString() 2612/// 2613/// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:")); 2614/// matches the outer message expr in the code below, but NOT the message 2615/// invocation for self.bodyView. 2616/// \code 2617/// [self.bodyView loadHTMLString:html baseURL:NULL]; 2618/// \endcode 2619AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) { 2620 Selector Sel = Node.getSelector(); 2621 return BaseName.compare(Sel.getAsString()) == 0; 2622} 2623 2624 2625/// \brief Matches ObjC selectors whose name contains 2626/// a substring matched by the given RegExp. 2627/// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?")); 2628/// matches the outer message expr in the code below, but NOT the message 2629/// invocation for self.bodyView. 2630/// \code 2631/// [self.bodyView loadHTMLString:html baseURL:NULL]; 2632/// \endcode 2633AST_MATCHER_P(ObjCMessageExpr, matchesSelector, std::string, RegExp) { 2634 assert(!RegExp.empty()); 2635 std::string SelectorString = Node.getSelector().getAsString(); 2636 llvm::Regex RE(RegExp); 2637 return RE.match(SelectorString); 2638} 2639 2640/// \brief Matches when the selector is the empty selector 2641/// 2642/// Matches only when the selector of the objCMessageExpr is NULL. This may 2643/// represent an error condition in the tree! 2644AST_MATCHER(ObjCMessageExpr, hasNullSelector) { 2645 return Node.getSelector().isNull(); 2646} 2647 2648/// \brief Matches when the selector is a Unary Selector 2649/// 2650/// matcher = objCMessageExpr(matchesSelector(hasUnarySelector()); 2651/// matches self.bodyView in the code below, but NOT the outer message 2652/// invocation of "loadHTMLString:baseURL:". 2653/// \code 2654/// [self.bodyView loadHTMLString:html baseURL:NULL]; 2655/// \endcode 2656AST_MATCHER(ObjCMessageExpr, hasUnarySelector) { 2657 return Node.getSelector().isUnarySelector(); 2658} 2659 2660/// \brief Matches when the selector is a keyword selector 2661/// 2662/// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame 2663/// message expression in 2664/// 2665/// \code 2666/// UIWebView *webView = ...; 2667/// CGRect bodyFrame = webView.frame; 2668/// bodyFrame.size.height = self.bodyContentHeight; 2669/// webView.frame = bodyFrame; 2670/// // ^---- matches here 2671/// \endcode 2672AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) { 2673 return Node.getSelector().isKeywordSelector(); 2674} 2675 2676/// \brief Matches when the selector has the specified number of arguments 2677/// 2678/// matcher = objCMessageExpr(numSelectorArgs(0)); 2679/// matches self.bodyView in the code below 2680/// 2681/// matcher = objCMessageExpr(numSelectorArgs(2)); 2682/// matches the invocation of "loadHTMLString:baseURL:" but not that 2683/// of self.bodyView 2684/// \code 2685/// [self.bodyView loadHTMLString:html baseURL:NULL]; 2686/// \endcode 2687AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) { 2688 return Node.getSelector().getNumArgs() == N; 2689} 2690 2691/// \brief Matches if the call expression's callee expression matches. 2692/// 2693/// Given 2694/// \code 2695/// class Y { void x() { this->x(); x(); Y y; y.x(); } }; 2696/// void f() { f(); } 2697/// \endcode 2698/// callExpr(callee(expr())) 2699/// matches this->x(), x(), y.x(), f() 2700/// with callee(...) 2701/// matching this->x, x, y.x, f respectively 2702/// 2703/// Note: Callee cannot take the more general internal::Matcher<Expr> 2704/// because this introduces ambiguous overloads with calls to Callee taking a 2705/// internal::Matcher<Decl>, as the matcher hierarchy is purely 2706/// implemented in terms of implicit casts. 2707AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>, 2708 InnerMatcher) { 2709 const Expr *ExprNode = Node.getCallee(); 2710 return (ExprNode != nullptr && 2711 InnerMatcher.matches(*ExprNode, Finder, Builder)); 2712} 2713 2714/// \brief Matches if the call expression's callee's declaration matches the 2715/// given matcher. 2716/// 2717/// Example matches y.x() (matcher = callExpr(callee( 2718/// cxxMethodDecl(hasName("x"))))) 2719/// \code 2720/// class Y { public: void x(); }; 2721/// void z() { Y y; y.x(); } 2722/// \endcode 2723AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher, 2724 1) { 2725 return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder); 2726} 2727 2728/// \brief Matches if the expression's or declaration's type matches a type 2729/// matcher. 2730/// 2731/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X"))))) 2732/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X"))))) 2733/// and U (matcher = typedefDecl(hasType(asString("int"))) 2734/// \code 2735/// class X {}; 2736/// void y(X &x) { x; X z; } 2737/// typedef int U; 2738/// \endcode 2739AST_POLYMORPHIC_MATCHER_P_OVERLOAD( 2740 hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, TypedefNameDecl, ValueDecl), 2741 internal::Matcher<QualType>, InnerMatcher, 0) { 2742 return InnerMatcher.matches(internal::getUnderlyingType(Node), 2743 Finder, Builder); 2744} 2745 2746/// \brief Overloaded to match the declaration of the expression's or value 2747/// declaration's type. 2748/// 2749/// In case of a value declaration (for example a variable declaration), 2750/// this resolves one layer of indirection. For example, in the value 2751/// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of 2752/// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the 2753/// declaration of x. 2754/// 2755/// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X"))))) 2756/// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X"))))) 2757/// \code 2758/// class X {}; 2759/// void y(X &x) { x; X z; } 2760/// \endcode 2761/// 2762/// Usable as: Matcher<Expr>, Matcher<ValueDecl> 2763AST_POLYMORPHIC_MATCHER_P_OVERLOAD(hasType, 2764 AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, 2765 ValueDecl), 2766 internal::Matcher<Decl>, InnerMatcher, 1) { 2767 return qualType(hasDeclaration(InnerMatcher)) 2768 .matches(Node.getType(), Finder, Builder); 2769} 2770 2771/// \brief Matches if the type location of the declarator decl's type matches 2772/// the inner matcher. 2773/// 2774/// Given 2775/// \code 2776/// int x; 2777/// \endcode 2778/// declaratorDecl(hasTypeLoc(loc(asString("int")))) 2779/// matches int x 2780AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) { 2781 if (!Node.getTypeSourceInfo()) 2782 // This happens for example for implicit destructors. 2783 return false; 2784 return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder); 2785} 2786 2787/// \brief Matches if the matched type is represented by the given string. 2788/// 2789/// Given 2790/// \code 2791/// class Y { public: void x(); }; 2792/// void z() { Y* y; y->x(); } 2793/// \endcode 2794/// cxxMemberCallExpr(on(hasType(asString("class Y *")))) 2795/// matches y->x() 2796AST_MATCHER_P(QualType, asString, std::string, Name) { 2797 return Name == Node.getAsString(); 2798} 2799 2800/// \brief Matches if the matched type is a pointer type and the pointee type 2801/// matches the specified matcher. 2802/// 2803/// Example matches y->x() 2804/// (matcher = cxxMemberCallExpr(on(hasType(pointsTo 2805/// cxxRecordDecl(hasName("Y"))))))) 2806/// \code 2807/// class Y { public: void x(); }; 2808/// void z() { Y *y; y->x(); } 2809/// \endcode 2810AST_MATCHER_P( 2811 QualType, pointsTo, internal::Matcher<QualType>, 2812 InnerMatcher) { 2813 return (!Node.isNull() && Node->isAnyPointerType() && 2814 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 2815} 2816 2817/// \brief Overloaded to match the pointee type's declaration. 2818AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>, 2819 InnerMatcher, 1) { 2820 return pointsTo(qualType(hasDeclaration(InnerMatcher))) 2821 .matches(Node, Finder, Builder); 2822} 2823 2824/// \brief Matches if the matched type matches the unqualified desugared 2825/// type of the matched node. 2826/// 2827/// For example, in: 2828/// \code 2829/// class A {}; 2830/// using B = A; 2831/// \endcode 2832/// The matcher type(hasUniqualifeidDesugaredType(recordType())) matches 2833/// both B and A. 2834AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>, 2835 InnerMatcher) { 2836 return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder, 2837 Builder); 2838} 2839 2840/// \brief Matches if the matched type is a reference type and the referenced 2841/// type matches the specified matcher. 2842/// 2843/// Example matches X &x and const X &y 2844/// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X")))))) 2845/// \code 2846/// class X { 2847/// void a(X b) { 2848/// X &x = b; 2849/// const X &y = b; 2850/// } 2851/// }; 2852/// \endcode 2853AST_MATCHER_P(QualType, references, internal::Matcher<QualType>, 2854 InnerMatcher) { 2855 return (!Node.isNull() && Node->isReferenceType() && 2856 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 2857} 2858 2859/// \brief Matches QualTypes whose canonical type matches InnerMatcher. 2860/// 2861/// Given: 2862/// \code 2863/// typedef int &int_ref; 2864/// int a; 2865/// int_ref b = a; 2866/// \endcode 2867/// 2868/// \c varDecl(hasType(qualType(referenceType()))))) will not match the 2869/// declaration of b but \c 2870/// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does. 2871AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>, 2872 InnerMatcher) { 2873 if (Node.isNull()) 2874 return false; 2875 return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder); 2876} 2877 2878/// \brief Overloaded to match the referenced type's declaration. 2879AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>, 2880 InnerMatcher, 1) { 2881 return references(qualType(hasDeclaration(InnerMatcher))) 2882 .matches(Node, Finder, Builder); 2883} 2884 2885AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument, 2886 internal::Matcher<Expr>, InnerMatcher) { 2887 const Expr *ExprNode = Node.getImplicitObjectArgument(); 2888 return (ExprNode != nullptr && 2889 InnerMatcher.matches(*ExprNode, Finder, Builder)); 2890} 2891 2892/// \brief Matches if the expression's type either matches the specified 2893/// matcher, or is a pointer to a type that matches the InnerMatcher. 2894AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType, 2895 internal::Matcher<QualType>, InnerMatcher, 0) { 2896 return onImplicitObjectArgument( 2897 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))) 2898 .matches(Node, Finder, Builder); 2899} 2900 2901/// \brief Overloaded to match the type's declaration. 2902AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType, 2903 internal::Matcher<Decl>, InnerMatcher, 1) { 2904 return onImplicitObjectArgument( 2905 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))) 2906 .matches(Node, Finder, Builder); 2907} 2908 2909/// \brief Matches a DeclRefExpr that refers to a declaration that matches the 2910/// specified matcher. 2911/// 2912/// Example matches x in if(x) 2913/// (matcher = declRefExpr(to(varDecl(hasName("x"))))) 2914/// \code 2915/// bool x; 2916/// if (x) {} 2917/// \endcode 2918AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>, 2919 InnerMatcher) { 2920 const Decl *DeclNode = Node.getDecl(); 2921 return (DeclNode != nullptr && 2922 InnerMatcher.matches(*DeclNode, Finder, Builder)); 2923} 2924 2925/// \brief Matches a \c DeclRefExpr that refers to a declaration through a 2926/// specific using shadow declaration. 2927/// 2928/// Given 2929/// \code 2930/// namespace a { void f() {} } 2931/// using a::f; 2932/// void g() { 2933/// f(); // Matches this .. 2934/// a::f(); // .. but not this. 2935/// } 2936/// \endcode 2937/// declRefExpr(throughUsingDecl(anything())) 2938/// matches \c f() 2939AST_MATCHER_P(DeclRefExpr, throughUsingDecl, 2940 internal::Matcher<UsingShadowDecl>, InnerMatcher) { 2941 const NamedDecl *FoundDecl = Node.getFoundDecl(); 2942 if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl)) 2943 return InnerMatcher.matches(*UsingDecl, Finder, Builder); 2944 return false; 2945} 2946 2947/// \brief Matches an \c OverloadExpr if any of the declarations in the set of 2948/// overloads matches the given matcher. 2949/// 2950/// Given 2951/// \code 2952/// template <typename T> void foo(T); 2953/// template <typename T> void bar(T); 2954/// template <typename T> void baz(T t) { 2955/// foo(t); 2956/// bar(t); 2957/// } 2958/// \endcode 2959/// unresolvedLookupExpr(hasAnyDeclaration( 2960/// functionTemplateDecl(hasName("foo")))) 2961/// matches \c foo in \c foo(t); but not \c bar in \c bar(t); 2962AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>, 2963 InnerMatcher) { 2964 return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(), 2965 Node.decls_end(), Finder, Builder); 2966} 2967 2968/// \brief Matches the Decl of a DeclStmt which has a single declaration. 2969/// 2970/// Given 2971/// \code 2972/// int a, b; 2973/// int c; 2974/// \endcode 2975/// declStmt(hasSingleDecl(anything())) 2976/// matches 'int c;' but not 'int a, b;'. 2977AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) { 2978 if (Node.isSingleDecl()) { 2979 const Decl *FoundDecl = Node.getSingleDecl(); 2980 return InnerMatcher.matches(*FoundDecl, Finder, Builder); 2981 } 2982 return false; 2983} 2984 2985/// \brief Matches a variable declaration that has an initializer expression 2986/// that matches the given matcher. 2987/// 2988/// Example matches x (matcher = varDecl(hasInitializer(callExpr()))) 2989/// \code 2990/// bool y() { return true; } 2991/// bool x = y(); 2992/// \endcode 2993AST_MATCHER_P( 2994 VarDecl, hasInitializer, internal::Matcher<Expr>, 2995 InnerMatcher) { 2996 const Expr *Initializer = Node.getAnyInitializer(); 2997 return (Initializer != nullptr && 2998 InnerMatcher.matches(*Initializer, Finder, Builder)); 2999} 3000 3001/// \brief Matches a variable declaration that has function scope and is a 3002/// non-static local variable. 3003/// 3004/// Example matches x (matcher = varDecl(hasLocalStorage()) 3005/// \code 3006/// void f() { 3007/// int x; 3008/// static int y; 3009/// } 3010/// int z; 3011/// \endcode 3012AST_MATCHER(VarDecl, hasLocalStorage) { 3013 return Node.hasLocalStorage(); 3014} 3015 3016/// \brief Matches a variable declaration that does not have local storage. 3017/// 3018/// Example matches y and z (matcher = varDecl(hasGlobalStorage()) 3019/// \code 3020/// void f() { 3021/// int x; 3022/// static int y; 3023/// } 3024/// int z; 3025/// \endcode 3026AST_MATCHER(VarDecl, hasGlobalStorage) { 3027 return Node.hasGlobalStorage(); 3028} 3029 3030/// \brief Matches a variable declaration that has automatic storage duration. 3031/// 3032/// Example matches x, but not y, z, or a. 3033/// (matcher = varDecl(hasAutomaticStorageDuration()) 3034/// \code 3035/// void f() { 3036/// int x; 3037/// static int y; 3038/// thread_local int z; 3039/// } 3040/// int a; 3041/// \endcode 3042AST_MATCHER(VarDecl, hasAutomaticStorageDuration) { 3043 return Node.getStorageDuration() == SD_Automatic; 3044} 3045 3046/// \brief Matches a variable declaration that has static storage duration. 3047/// It includes the variable declared at namespace scope and those declared 3048/// with "static" and "extern" storage class specifiers. 3049/// 3050/// \code 3051/// void f() { 3052/// int x; 3053/// static int y; 3054/// thread_local int z; 3055/// } 3056/// int a; 3057/// static int b; 3058/// extern int c; 3059/// varDecl(hasStaticStorageDuration()) 3060/// matches the function declaration y, a, b and c. 3061/// \endcode 3062AST_MATCHER(VarDecl, hasStaticStorageDuration) { 3063 return Node.getStorageDuration() == SD_Static; 3064} 3065 3066/// \brief Matches a variable declaration that has thread storage duration. 3067/// 3068/// Example matches z, but not x, z, or a. 3069/// (matcher = varDecl(hasThreadStorageDuration()) 3070/// \code 3071/// void f() { 3072/// int x; 3073/// static int y; 3074/// thread_local int z; 3075/// } 3076/// int a; 3077/// \endcode 3078AST_MATCHER(VarDecl, hasThreadStorageDuration) { 3079 return Node.getStorageDuration() == SD_Thread; 3080} 3081 3082/// \brief Matches a variable declaration that is an exception variable from 3083/// a C++ catch block, or an Objective-C \@catch statement. 3084/// 3085/// Example matches x (matcher = varDecl(isExceptionVariable()) 3086/// \code 3087/// void f(int y) { 3088/// try { 3089/// } catch (int x) { 3090/// } 3091/// } 3092/// \endcode 3093AST_MATCHER(VarDecl, isExceptionVariable) { 3094 return Node.isExceptionVariable(); 3095} 3096 3097/// \brief Checks that a call expression or a constructor call expression has 3098/// a specific number of arguments (including absent default arguments). 3099/// 3100/// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2))) 3101/// \code 3102/// void f(int x, int y); 3103/// f(0, 0); 3104/// \endcode 3105AST_POLYMORPHIC_MATCHER_P(argumentCountIs, 3106 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr, 3107 CXXConstructExpr, 3108 ObjCMessageExpr), 3109 unsigned, N) { 3110 return Node.getNumArgs() == N; 3111} 3112 3113/// \brief Matches the n'th argument of a call expression or a constructor 3114/// call expression. 3115/// 3116/// Example matches y in x(y) 3117/// (matcher = callExpr(hasArgument(0, declRefExpr()))) 3118/// \code 3119/// void x(int) { int y; x(y); } 3120/// \endcode 3121AST_POLYMORPHIC_MATCHER_P2(hasArgument, 3122 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr, 3123 CXXConstructExpr, 3124 ObjCMessageExpr), 3125 unsigned, N, internal::Matcher<Expr>, InnerMatcher) { 3126 return (N < Node.getNumArgs() && 3127 InnerMatcher.matches( 3128 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder)); 3129} 3130 3131/// \brief Matches declaration statements that contain a specific number of 3132/// declarations. 3133/// 3134/// Example: Given 3135/// \code 3136/// int a, b; 3137/// int c; 3138/// int d = 2, e; 3139/// \endcode 3140/// declCountIs(2) 3141/// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'. 3142AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) { 3143 return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N; 3144} 3145 3146/// \brief Matches the n'th declaration of a declaration statement. 3147/// 3148/// Note that this does not work for global declarations because the AST 3149/// breaks up multiple-declaration DeclStmt's into multiple single-declaration 3150/// DeclStmt's. 3151/// Example: Given non-global declarations 3152/// \code 3153/// int a, b = 0; 3154/// int c; 3155/// int d = 2, e; 3156/// \endcode 3157/// declStmt(containsDeclaration( 3158/// 0, varDecl(hasInitializer(anything())))) 3159/// matches only 'int d = 2, e;', and 3160/// declStmt(containsDeclaration(1, varDecl())) 3161/// \code 3162/// matches 'int a, b = 0' as well as 'int d = 2, e;' 3163/// but 'int c;' is not matched. 3164/// \endcode 3165AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N, 3166 internal::Matcher<Decl>, InnerMatcher) { 3167 const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end()); 3168 if (N >= NumDecls) 3169 return false; 3170 DeclStmt::const_decl_iterator Iterator = Node.decl_begin(); 3171 std::advance(Iterator, N); 3172 return InnerMatcher.matches(**Iterator, Finder, Builder); 3173} 3174 3175/// \brief Matches a C++ catch statement that has a catch-all handler. 3176/// 3177/// Given 3178/// \code 3179/// try { 3180/// // ... 3181/// } catch (int) { 3182/// // ... 3183/// } catch (...) { 3184/// // ... 3185/// } 3186/// /endcode 3187/// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int). 3188AST_MATCHER(CXXCatchStmt, isCatchAll) { 3189 return Node.getExceptionDecl() == nullptr; 3190} 3191 3192/// \brief Matches a constructor initializer. 3193/// 3194/// Given 3195/// \code 3196/// struct Foo { 3197/// Foo() : foo_(1) { } 3198/// int foo_; 3199/// }; 3200/// \endcode 3201/// cxxRecordDecl(has(cxxConstructorDecl( 3202/// hasAnyConstructorInitializer(anything()) 3203/// ))) 3204/// record matches Foo, hasAnyConstructorInitializer matches foo_(1) 3205AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer, 3206 internal::Matcher<CXXCtorInitializer>, InnerMatcher) { 3207 return matchesFirstInPointerRange(InnerMatcher, Node.init_begin(), 3208 Node.init_end(), Finder, Builder); 3209} 3210 3211/// \brief Matches the field declaration of a constructor initializer. 3212/// 3213/// Given 3214/// \code 3215/// struct Foo { 3216/// Foo() : foo_(1) { } 3217/// int foo_; 3218/// }; 3219/// \endcode 3220/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer( 3221/// forField(hasName("foo_")))))) 3222/// matches Foo 3223/// with forField matching foo_ 3224AST_MATCHER_P(CXXCtorInitializer, forField, 3225 internal::Matcher<FieldDecl>, InnerMatcher) { 3226 const FieldDecl *NodeAsDecl = Node.getMember(); 3227 return (NodeAsDecl != nullptr && 3228 InnerMatcher.matches(*NodeAsDecl, Finder, Builder)); 3229} 3230 3231/// \brief Matches the initializer expression of a constructor initializer. 3232/// 3233/// Given 3234/// \code 3235/// struct Foo { 3236/// Foo() : foo_(1) { } 3237/// int foo_; 3238/// }; 3239/// \endcode 3240/// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer( 3241/// withInitializer(integerLiteral(equals(1))))))) 3242/// matches Foo 3243/// with withInitializer matching (1) 3244AST_MATCHER_P(CXXCtorInitializer, withInitializer, 3245 internal::Matcher<Expr>, InnerMatcher) { 3246 const Expr* NodeAsExpr = Node.getInit(); 3247 return (NodeAsExpr != nullptr && 3248 InnerMatcher.matches(*NodeAsExpr, Finder, Builder)); 3249} 3250 3251/// \brief Matches a constructor initializer if it is explicitly written in 3252/// code (as opposed to implicitly added by the compiler). 3253/// 3254/// Given 3255/// \code 3256/// struct Foo { 3257/// Foo() { } 3258/// Foo(int) : foo_("A") { } 3259/// string foo_; 3260/// }; 3261/// \endcode 3262/// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten())) 3263/// will match Foo(int), but not Foo() 3264AST_MATCHER(CXXCtorInitializer, isWritten) { 3265 return Node.isWritten(); 3266} 3267 3268/// \brief Matches a constructor initializer if it is initializing a base, as 3269/// opposed to a member. 3270/// 3271/// Given 3272/// \code 3273/// struct B {}; 3274/// struct D : B { 3275/// int I; 3276/// D(int i) : I(i) {} 3277/// }; 3278/// struct E : B { 3279/// E() : B() {} 3280/// }; 3281/// \endcode 3282/// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer())) 3283/// will match E(), but not match D(int). 3284AST_MATCHER(CXXCtorInitializer, isBaseInitializer) { 3285 return Node.isBaseInitializer(); 3286} 3287 3288/// \brief Matches a constructor initializer if it is initializing a member, as 3289/// opposed to a base. 3290/// 3291/// Given 3292/// \code 3293/// struct B {}; 3294/// struct D : B { 3295/// int I; 3296/// D(int i) : I(i) {} 3297/// }; 3298/// struct E : B { 3299/// E() : B() {} 3300/// }; 3301/// \endcode 3302/// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer())) 3303/// will match D(int), but not match E(). 3304AST_MATCHER(CXXCtorInitializer, isMemberInitializer) { 3305 return Node.isMemberInitializer(); 3306} 3307 3308/// \brief Matches any argument of a call expression or a constructor call 3309/// expression. 3310/// 3311/// Given 3312/// \code 3313/// void x(int, int, int) { int y; x(1, y, 42); } 3314/// \endcode 3315/// callExpr(hasAnyArgument(declRefExpr())) 3316/// matches x(1, y, 42) 3317/// with hasAnyArgument(...) 3318/// matching y 3319AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, 3320 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr, 3321 CXXConstructExpr), 3322 internal::Matcher<Expr>, InnerMatcher) { 3323 for (const Expr *Arg : Node.arguments()) { 3324 BoundNodesTreeBuilder Result(*Builder); 3325 if (InnerMatcher.matches(*Arg, Finder, &Result)) { 3326 *Builder = std::move(Result); 3327 return true; 3328 } 3329 } 3330 return false; 3331} 3332 3333/// \brief Matches a constructor call expression which uses list initialization. 3334AST_MATCHER(CXXConstructExpr, isListInitialization) { 3335 return Node.isListInitialization(); 3336} 3337 3338/// \brief Matches a constructor call expression which requires 3339/// zero initialization. 3340/// 3341/// Given 3342/// \code 3343/// void foo() { 3344/// struct point { double x; double y; }; 3345/// point pt[2] = { { 1.0, 2.0 } }; 3346/// } 3347/// \endcode 3348/// initListExpr(has(cxxConstructExpr(requiresZeroInitialization())) 3349/// will match the implicit array filler for pt[1]. 3350AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) { 3351 return Node.requiresZeroInitialization(); 3352} 3353 3354/// \brief Matches the n'th parameter of a function declaration. 3355/// 3356/// Given 3357/// \code 3358/// class X { void f(int x) {} }; 3359/// \endcode 3360/// cxxMethodDecl(hasParameter(0, hasType(varDecl()))) 3361/// matches f(int x) {} 3362/// with hasParameter(...) 3363/// matching int x 3364AST_MATCHER_P2(FunctionDecl, hasParameter, 3365 unsigned, N, internal::Matcher<ParmVarDecl>, 3366 InnerMatcher) { 3367 return (N < Node.getNumParams() && 3368 InnerMatcher.matches( 3369 *Node.getParamDecl(N), Finder, Builder)); 3370} 3371 3372/// \brief Matches all arguments and their respective ParmVarDecl. 3373/// 3374/// Given 3375/// \code 3376/// void f(int i); 3377/// int y; 3378/// f(y); 3379/// \endcode 3380/// callExpr( 3381/// forEachArgumentWithParam( 3382/// declRefExpr(to(varDecl(hasName("y")))), 3383/// parmVarDecl(hasType(isInteger())) 3384/// )) 3385/// matches f(y); 3386/// with declRefExpr(...) 3387/// matching int y 3388/// and parmVarDecl(...) 3389/// matching int i 3390AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam, 3391 AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr, 3392 CXXConstructExpr), 3393 internal::Matcher<Expr>, ArgMatcher, 3394 internal::Matcher<ParmVarDecl>, ParamMatcher) { 3395 BoundNodesTreeBuilder Result; 3396 // The first argument of an overloaded member operator is the implicit object 3397 // argument of the method which should not be matched against a parameter, so 3398 // we skip over it here. 3399 BoundNodesTreeBuilder Matches; 3400 unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl())) 3401 .matches(Node, Finder, &Matches) 3402 ? 1 3403 : 0; 3404 int ParamIndex = 0; 3405 bool Matched = false; 3406 for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) { 3407 BoundNodesTreeBuilder ArgMatches(*Builder); 3408 if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), 3409 Finder, &ArgMatches)) { 3410 BoundNodesTreeBuilder ParamMatches(ArgMatches); 3411 if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl( 3412 hasParameter(ParamIndex, ParamMatcher)))), 3413 callExpr(callee(functionDecl( 3414 hasParameter(ParamIndex, ParamMatcher)))))) 3415 .matches(Node, Finder, &ParamMatches)) { 3416 Result.addMatch(ParamMatches); 3417 Matched = true; 3418 } 3419 } 3420 ++ParamIndex; 3421 } 3422 *Builder = std::move(Result); 3423 return Matched; 3424} 3425 3426/// \brief Matches any parameter of a function declaration. 3427/// 3428/// Does not match the 'this' parameter of a method. 3429/// 3430/// Given 3431/// \code 3432/// class X { void f(int x, int y, int z) {} }; 3433/// \endcode 3434/// cxxMethodDecl(hasAnyParameter(hasName("y"))) 3435/// matches f(int x, int y, int z) {} 3436/// with hasAnyParameter(...) 3437/// matching int y 3438AST_MATCHER_P(FunctionDecl, hasAnyParameter, 3439 internal::Matcher<ParmVarDecl>, InnerMatcher) { 3440 return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(), 3441 Node.param_end(), Finder, Builder); 3442} 3443 3444/// \brief Matches \c FunctionDecls and \c FunctionProtoTypes that have a 3445/// specific parameter count. 3446/// 3447/// Given 3448/// \code 3449/// void f(int i) {} 3450/// void g(int i, int j) {} 3451/// void h(int i, int j); 3452/// void j(int i); 3453/// void k(int x, int y, int z, ...); 3454/// \endcode 3455/// functionDecl(parameterCountIs(2)) 3456/// matches void g(int i, int j) {} 3457/// functionProtoType(parameterCountIs(2)) 3458/// matches void h(int i, int j) 3459/// functionProtoType(parameterCountIs(3)) 3460/// matches void k(int x, int y, int z, ...); 3461AST_POLYMORPHIC_MATCHER_P(parameterCountIs, 3462 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, 3463 FunctionProtoType), 3464 unsigned, N) { 3465 return Node.getNumParams() == N; 3466} 3467 3468/// \brief Matches the return type of a function declaration. 3469/// 3470/// Given: 3471/// \code 3472/// class X { int f() { return 1; } }; 3473/// \endcode 3474/// cxxMethodDecl(returns(asString("int"))) 3475/// matches int f() { return 1; } 3476AST_MATCHER_P(FunctionDecl, returns, 3477 internal::Matcher<QualType>, InnerMatcher) { 3478 return InnerMatcher.matches(Node.getReturnType(), Finder, Builder); 3479} 3480 3481/// \brief Matches extern "C" function declarations. 3482/// 3483/// Given: 3484/// \code 3485/// extern "C" void f() {} 3486/// extern "C" { void g() {} } 3487/// void h() {} 3488/// \endcode 3489/// functionDecl(isExternC()) 3490/// matches the declaration of f and g, but not the declaration h 3491AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, 3492 VarDecl)) { 3493 return Node.isExternC(); 3494} 3495 3496/// \brief Matches variable/function declarations that have "static" storage 3497/// class specifier ("static" keyword) written in the source. 3498/// 3499/// Given: 3500/// \code 3501/// static void f() {} 3502/// static int i = 0; 3503/// extern int j; 3504/// int k; 3505/// \endcode 3506/// functionDecl(isStaticStorageClass()) 3507/// matches the function declaration f. 3508/// varDecl(isStaticStorageClass()) 3509/// matches the variable declaration i. 3510AST_POLYMORPHIC_MATCHER(isStaticStorageClass, 3511 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, 3512 VarDecl)) { 3513 return Node.getStorageClass() == SC_Static; 3514} 3515 3516/// \brief Matches deleted function declarations. 3517/// 3518/// Given: 3519/// \code 3520/// void Func(); 3521/// void DeletedFunc() = delete; 3522/// \endcode 3523/// functionDecl(isDeleted()) 3524/// matches the declaration of DeletedFunc, but not Func. 3525AST_MATCHER(FunctionDecl, isDeleted) { 3526 return Node.isDeleted(); 3527} 3528 3529/// \brief Matches defaulted function declarations. 3530/// 3531/// Given: 3532/// \code 3533/// class A { ~A(); }; 3534/// class B { ~B() = default; }; 3535/// \endcode 3536/// functionDecl(isDefaulted()) 3537/// matches the declaration of ~B, but not ~A. 3538AST_MATCHER(FunctionDecl, isDefaulted) { 3539 return Node.isDefaulted(); 3540} 3541 3542/// \brief Matches functions that have a dynamic exception specification. 3543/// 3544/// Given: 3545/// \code 3546/// void f(); 3547/// void g() noexcept; 3548/// void h() noexcept(true); 3549/// void i() noexcept(false); 3550/// void j() throw(); 3551/// void k() throw(int); 3552/// void l() throw(...); 3553/// \endcode 3554/// functionDecl(hasDynamicExceptionSpec()) and 3555/// functionProtoType(hasDynamicExceptionSpec()) 3556/// match the declarations of j, k, and l, but not f, g, h, or i. 3557AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec, 3558 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, 3559 FunctionProtoType)) { 3560 if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node)) 3561 return FnTy->hasDynamicExceptionSpec(); 3562 return false; 3563} 3564 3565/// \brief Matches functions that have a non-throwing exception specification. 3566/// 3567/// Given: 3568/// \code 3569/// void f(); 3570/// void g() noexcept; 3571/// void h() throw(); 3572/// void i() throw(int); 3573/// void j() noexcept(false); 3574/// \endcode 3575/// functionDecl(isNoThrow()) and functionProtoType(isNoThrow()) 3576/// match the declarations of g, and h, but not f, i or j. 3577AST_POLYMORPHIC_MATCHER(isNoThrow, 3578 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, 3579 FunctionProtoType)) { 3580 const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node); 3581 3582 // If the function does not have a prototype, then it is assumed to be a 3583 // throwing function (as it would if the function did not have any exception 3584 // specification). 3585 if (!FnTy) 3586 return false; 3587 3588 // Assume the best for any unresolved exception specification. 3589 if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType())) 3590 return true; 3591 3592 return FnTy->isNothrow(Finder->getASTContext()); 3593} 3594 3595/// \brief Matches constexpr variable and function declarations. 3596/// 3597/// Given: 3598/// \code 3599/// constexpr int foo = 42; 3600/// constexpr int bar(); 3601/// \endcode 3602/// varDecl(isConstexpr()) 3603/// matches the declaration of foo. 3604/// functionDecl(isConstexpr()) 3605/// matches the declaration of bar. 3606AST_POLYMORPHIC_MATCHER(isConstexpr, 3607 AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl, 3608 FunctionDecl)) { 3609 return Node.isConstexpr(); 3610} 3611 3612/// \brief Matches the condition expression of an if statement, for loop, 3613/// switch statement or conditional operator. 3614/// 3615/// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true)))) 3616/// \code 3617/// if (true) {} 3618/// \endcode 3619AST_POLYMORPHIC_MATCHER_P( 3620 hasCondition, 3621 AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt, 3622 SwitchStmt, AbstractConditionalOperator), 3623 internal::Matcher<Expr>, InnerMatcher) { 3624 const Expr *const Condition = Node.getCond(); 3625 return (Condition != nullptr && 3626 InnerMatcher.matches(*Condition, Finder, Builder)); 3627} 3628 3629/// \brief Matches the then-statement of an if statement. 3630/// 3631/// Examples matches the if statement 3632/// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true))))) 3633/// \code 3634/// if (false) true; else false; 3635/// \endcode 3636AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) { 3637 const Stmt *const Then = Node.getThen(); 3638 return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder)); 3639} 3640 3641/// \brief Matches the else-statement of an if statement. 3642/// 3643/// Examples matches the if statement 3644/// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true))))) 3645/// \code 3646/// if (false) false; else true; 3647/// \endcode 3648AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) { 3649 const Stmt *const Else = Node.getElse(); 3650 return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder)); 3651} 3652 3653/// \brief Matches if a node equals a previously bound node. 3654/// 3655/// Matches a node if it equals the node previously bound to \p ID. 3656/// 3657/// Given 3658/// \code 3659/// class X { int a; int b; }; 3660/// \endcode 3661/// cxxRecordDecl( 3662/// has(fieldDecl(hasName("a"), hasType(type().bind("t")))), 3663/// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t")))))) 3664/// matches the class \c X, as \c a and \c b have the same type. 3665/// 3666/// Note that when multiple matches are involved via \c forEach* matchers, 3667/// \c equalsBoundNodes acts as a filter. 3668/// For example: 3669/// compoundStmt( 3670/// forEachDescendant(varDecl().bind("d")), 3671/// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))) 3672/// will trigger a match for each combination of variable declaration 3673/// and reference to that variable declaration within a compound statement. 3674AST_POLYMORPHIC_MATCHER_P(equalsBoundNode, 3675 AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type, 3676 QualType), 3677 std::string, ID) { 3678 // FIXME: Figure out whether it makes sense to allow this 3679 // on any other node types. 3680 // For *Loc it probably does not make sense, as those seem 3681 // unique. For NestedNameSepcifier it might make sense, as 3682 // those also have pointer identity, but I'm not sure whether 3683 // they're ever reused. 3684 internal::NotEqualsBoundNodePredicate Predicate; 3685 Predicate.ID = ID; 3686 Predicate.Node = ast_type_traits::DynTypedNode::create(Node); 3687 return Builder->removeBindings(Predicate); 3688} 3689 3690/// \brief Matches the condition variable statement in an if statement. 3691/// 3692/// Given 3693/// \code 3694/// if (A* a = GetAPointer()) {} 3695/// \endcode 3696/// hasConditionVariableStatement(...) 3697/// matches 'A* a = GetAPointer()'. 3698AST_MATCHER_P(IfStmt, hasConditionVariableStatement, 3699 internal::Matcher<DeclStmt>, InnerMatcher) { 3700 const DeclStmt* const DeclarationStatement = 3701 Node.getConditionVariableDeclStmt(); 3702 return DeclarationStatement != nullptr && 3703 InnerMatcher.matches(*DeclarationStatement, Finder, Builder); 3704} 3705 3706/// \brief Matches the index expression of an array subscript expression. 3707/// 3708/// Given 3709/// \code 3710/// int i[5]; 3711/// void f() { i[1] = 42; } 3712/// \endcode 3713/// arraySubscriptExpression(hasIndex(integerLiteral())) 3714/// matches \c i[1] with the \c integerLiteral() matching \c 1 3715AST_MATCHER_P(ArraySubscriptExpr, hasIndex, 3716 internal::Matcher<Expr>, InnerMatcher) { 3717 if (const Expr* Expression = Node.getIdx()) 3718 return InnerMatcher.matches(*Expression, Finder, Builder); 3719 return false; 3720} 3721 3722/// \brief Matches the base expression of an array subscript expression. 3723/// 3724/// Given 3725/// \code 3726/// int i[5]; 3727/// void f() { i[1] = 42; } 3728/// \endcode 3729/// arraySubscriptExpression(hasBase(implicitCastExpr( 3730/// hasSourceExpression(declRefExpr())))) 3731/// matches \c i[1] with the \c declRefExpr() matching \c i 3732AST_MATCHER_P(ArraySubscriptExpr, hasBase, 3733 internal::Matcher<Expr>, InnerMatcher) { 3734 if (const Expr* Expression = Node.getBase()) 3735 return InnerMatcher.matches(*Expression, Finder, Builder); 3736 return false; 3737} 3738 3739/// \brief Matches a 'for', 'while', 'do while' statement or a function 3740/// definition that has a given body. 3741/// 3742/// Given 3743/// \code 3744/// for (;;) {} 3745/// \endcode 3746/// hasBody(compoundStmt()) 3747/// matches 'for (;;) {}' 3748/// with compoundStmt() 3749/// matching '{}' 3750AST_POLYMORPHIC_MATCHER_P(hasBody, 3751 AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt, 3752 WhileStmt, 3753 CXXForRangeStmt, 3754 FunctionDecl), 3755 internal::Matcher<Stmt>, InnerMatcher) { 3756 const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node); 3757 return (Statement != nullptr && 3758 InnerMatcher.matches(*Statement, Finder, Builder)); 3759} 3760 3761/// \brief Matches compound statements where at least one substatement matches 3762/// a given matcher. Also matches StmtExprs that have CompoundStmt as children. 3763/// 3764/// Given 3765/// \code 3766/// { {}; 1+2; } 3767/// \endcode 3768/// hasAnySubstatement(compoundStmt()) 3769/// matches '{ {}; 1+2; }' 3770/// with compoundStmt() 3771/// matching '{}' 3772AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement, 3773 AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt, 3774 StmtExpr), 3775 internal::Matcher<Stmt>, InnerMatcher) { 3776 const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node); 3777 return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(), 3778 CS->body_end(), Finder, Builder); 3779} 3780 3781/// \brief Checks that a compound statement contains a specific number of 3782/// child statements. 3783/// 3784/// Example: Given 3785/// \code 3786/// { for (;;) {} } 3787/// \endcode 3788/// compoundStmt(statementCountIs(0))) 3789/// matches '{}' 3790/// but does not match the outer compound statement. 3791AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) { 3792 return Node.size() == N; 3793} 3794 3795/// \brief Matches literals that are equal to the given value. 3796/// 3797/// Example matches true (matcher = cxxBoolLiteral(equals(true))) 3798/// \code 3799/// true 3800/// \endcode 3801/// 3802/// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteral>, 3803/// Matcher<FloatingLiteral>, Matcher<IntegerLiteral> 3804template <typename ValueT> 3805internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT> 3806equals(const ValueT &Value) { 3807 return internal::PolymorphicMatcherWithParam1< 3808 internal::ValueEqualsMatcher, 3809 ValueT>(Value); 3810} 3811 3812/// \brief Matches the operator Name of operator expressions (binary or 3813/// unary). 3814/// 3815/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||"))) 3816/// \code 3817/// !(a || b) 3818/// \endcode 3819AST_POLYMORPHIC_MATCHER_P(hasOperatorName, 3820 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, 3821 UnaryOperator), 3822 std::string, Name) { 3823 return Name == Node.getOpcodeStr(Node.getOpcode()); 3824} 3825 3826/// \brief Matches the left hand side of binary operator expressions. 3827/// 3828/// Example matches a (matcher = binaryOperator(hasLHS())) 3829/// \code 3830/// a || b 3831/// \endcode 3832AST_POLYMORPHIC_MATCHER_P(hasLHS, 3833 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, 3834 ArraySubscriptExpr), 3835 internal::Matcher<Expr>, InnerMatcher) { 3836 const Expr *LeftHandSide = Node.getLHS(); 3837 return (LeftHandSide != nullptr && 3838 InnerMatcher.matches(*LeftHandSide, Finder, Builder)); 3839} 3840 3841/// \brief Matches the right hand side of binary operator expressions. 3842/// 3843/// Example matches b (matcher = binaryOperator(hasRHS())) 3844/// \code 3845/// a || b 3846/// \endcode 3847AST_POLYMORPHIC_MATCHER_P(hasRHS, 3848 AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, 3849 ArraySubscriptExpr), 3850 internal::Matcher<Expr>, InnerMatcher) { 3851 const Expr *RightHandSide = Node.getRHS(); 3852 return (RightHandSide != nullptr && 3853 InnerMatcher.matches(*RightHandSide, Finder, Builder)); 3854} 3855 3856/// \brief Matches if either the left hand side or the right hand side of a 3857/// binary operator matches. 3858inline internal::Matcher<BinaryOperator> hasEitherOperand( 3859 const internal::Matcher<Expr> &InnerMatcher) { 3860 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)); 3861} 3862 3863/// \brief Matches if the operand of a unary operator matches. 3864/// 3865/// Example matches true (matcher = hasUnaryOperand( 3866/// cxxBoolLiteral(equals(true)))) 3867/// \code 3868/// !true 3869/// \endcode 3870AST_MATCHER_P(UnaryOperator, hasUnaryOperand, 3871 internal::Matcher<Expr>, InnerMatcher) { 3872 const Expr * const Operand = Node.getSubExpr(); 3873 return (Operand != nullptr && 3874 InnerMatcher.matches(*Operand, Finder, Builder)); 3875} 3876 3877/// \brief Matches if the cast's source expression 3878/// or opaque value's source expression matches the given matcher. 3879/// 3880/// Example 1: matches "a string" 3881/// (matcher = castExpr(hasSourceExpression(cxxConstructExpr()))) 3882/// \code 3883/// class URL { URL(string); }; 3884/// URL url = "a string"; 3885/// \endcode 3886/// 3887/// Example 2: matches 'b' (matcher = 3888/// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr()))) 3889/// \code 3890/// int a = b ?: 1; 3891/// \endcode 3892 3893AST_POLYMORPHIC_MATCHER_P(hasSourceExpression, 3894 AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr, 3895 OpaqueValueExpr), 3896 internal::Matcher<Expr>, InnerMatcher) { 3897 const Expr *const SubExpression = 3898 internal::GetSourceExpressionMatcher<NodeType>::get(Node); 3899 return (SubExpression != nullptr && 3900 InnerMatcher.matches(*SubExpression, Finder, Builder)); 3901} 3902 3903/// \brief Matches casts that has a given cast kind. 3904/// 3905/// Example: matches the implicit cast around \c 0 3906/// (matcher = castExpr(hasCastKind(CK_NullToPointer))) 3907/// \code 3908/// int *p = 0; 3909/// \endcode 3910AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) { 3911 return Node.getCastKind() == Kind; 3912} 3913 3914/// \brief Matches casts whose destination type matches a given matcher. 3915/// 3916/// (Note: Clang's AST refers to other conversions as "casts" too, and calls 3917/// actual casts "explicit" casts.) 3918AST_MATCHER_P(ExplicitCastExpr, hasDestinationType, 3919 internal::Matcher<QualType>, InnerMatcher) { 3920 const QualType NodeType = Node.getTypeAsWritten(); 3921 return InnerMatcher.matches(NodeType, Finder, Builder); 3922} 3923 3924/// \brief Matches implicit casts whose destination type matches a given 3925/// matcher. 3926/// 3927/// FIXME: Unit test this matcher 3928AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType, 3929 internal::Matcher<QualType>, InnerMatcher) { 3930 return InnerMatcher.matches(Node.getType(), Finder, Builder); 3931} 3932 3933/// \brief Matches RecordDecl object that are spelled with "struct." 3934/// 3935/// Example matches S, but not C or U. 3936/// \code 3937/// struct S {}; 3938/// class C {}; 3939/// union U {}; 3940/// \endcode 3941AST_MATCHER(RecordDecl, isStruct) { 3942 return Node.isStruct(); 3943} 3944 3945/// \brief Matches RecordDecl object that are spelled with "union." 3946/// 3947/// Example matches U, but not C or S. 3948/// \code 3949/// struct S {}; 3950/// class C {}; 3951/// union U {}; 3952/// \endcode 3953AST_MATCHER(RecordDecl, isUnion) { 3954 return Node.isUnion(); 3955} 3956 3957/// \brief Matches RecordDecl object that are spelled with "class." 3958/// 3959/// Example matches C, but not S or U. 3960/// \code 3961/// struct S {}; 3962/// class C {}; 3963/// union U {}; 3964/// \endcode 3965AST_MATCHER(RecordDecl, isClass) { 3966 return Node.isClass(); 3967} 3968 3969/// \brief Matches the true branch expression of a conditional operator. 3970/// 3971/// Example 1 (conditional ternary operator): matches a 3972/// \code 3973/// condition ? a : b 3974/// \endcode 3975/// 3976/// Example 2 (conditional binary operator): matches opaqueValueExpr(condition) 3977/// \code 3978/// condition ?: b 3979/// \endcode 3980AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression, 3981 internal::Matcher<Expr>, InnerMatcher) { 3982 const Expr *Expression = Node.getTrueExpr(); 3983 return (Expression != nullptr && 3984 InnerMatcher.matches(*Expression, Finder, Builder)); 3985} 3986 3987/// \brief Matches the false branch expression of a conditional operator 3988/// (binary or ternary). 3989/// 3990/// Example matches b 3991/// \code 3992/// condition ? a : b 3993/// condition ?: b 3994/// \endcode 3995AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression, 3996 internal::Matcher<Expr>, InnerMatcher) { 3997 const Expr *Expression = Node.getFalseExpr(); 3998 return (Expression != nullptr && 3999 InnerMatcher.matches(*Expression, Finder, Builder)); 4000} 4001 4002/// \brief Matches if a declaration has a body attached. 4003/// 4004/// Example matches A, va, fa 4005/// \code 4006/// class A {}; 4007/// class B; // Doesn't match, as it has no body. 4008/// int va; 4009/// extern int vb; // Doesn't match, as it doesn't define the variable. 4010/// void fa() {} 4011/// void fb(); // Doesn't match, as it has no body. 4012/// \endcode 4013/// 4014/// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl> 4015AST_POLYMORPHIC_MATCHER(isDefinition, 4016 AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl, 4017 FunctionDecl)) { 4018 return Node.isThisDeclarationADefinition(); 4019} 4020 4021/// \brief Matches if a function declaration is variadic. 4022/// 4023/// Example matches f, but not g or h. The function i will not match, even when 4024/// compiled in C mode. 4025/// \code 4026/// void f(...); 4027/// void g(int); 4028/// template <typename... Ts> void h(Ts...); 4029/// void i(); 4030/// \endcode 4031AST_MATCHER(FunctionDecl, isVariadic) { 4032 return Node.isVariadic(); 4033} 4034 4035/// \brief Matches the class declaration that the given method declaration 4036/// belongs to. 4037/// 4038/// FIXME: Generalize this for other kinds of declarations. 4039/// FIXME: What other kind of declarations would we need to generalize 4040/// this to? 4041/// 4042/// Example matches A() in the last line 4043/// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl( 4044/// ofClass(hasName("A")))))) 4045/// \code 4046/// class A { 4047/// public: 4048/// A(); 4049/// }; 4050/// A a = A(); 4051/// \endcode 4052AST_MATCHER_P(CXXMethodDecl, ofClass, 4053 internal::Matcher<CXXRecordDecl>, InnerMatcher) { 4054 const CXXRecordDecl *Parent = Node.getParent(); 4055 return (Parent != nullptr && 4056 InnerMatcher.matches(*Parent, Finder, Builder)); 4057} 4058 4059/// \brief Matches each method overriden by the given method. This matcher may 4060/// produce multiple matches. 4061/// 4062/// Given 4063/// \code 4064/// class A { virtual void f(); }; 4065/// class B : public A { void f(); }; 4066/// class C : public B { void f(); }; 4067/// \endcode 4068/// cxxMethodDecl(ofClass(hasName("C")), 4069/// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d") 4070/// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note 4071/// that B::f is not overridden by C::f). 4072/// 4073/// The check can produce multiple matches in case of multiple inheritance, e.g. 4074/// \code 4075/// class A1 { virtual void f(); }; 4076/// class A2 { virtual void f(); }; 4077/// class C : public A1, public A2 { void f(); }; 4078/// \endcode 4079/// cxxMethodDecl(ofClass(hasName("C")), 4080/// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d") 4081/// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and 4082/// once with "b" binding "A2::f" and "d" binding "C::f". 4083AST_MATCHER_P(CXXMethodDecl, forEachOverridden, 4084 internal::Matcher<CXXMethodDecl>, InnerMatcher) { 4085 BoundNodesTreeBuilder Result; 4086 bool Matched = false; 4087 for (const auto *Overridden : Node.overridden_methods()) { 4088 BoundNodesTreeBuilder OverriddenBuilder(*Builder); 4089 const bool OverriddenMatched = 4090 InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder); 4091 if (OverriddenMatched) { 4092 Matched = true; 4093 Result.addMatch(OverriddenBuilder); 4094 } 4095 } 4096 *Builder = std::move(Result); 4097 return Matched; 4098} 4099 4100/// \brief Matches if the given method declaration is virtual. 4101/// 4102/// Given 4103/// \code 4104/// class A { 4105/// public: 4106/// virtual void x(); 4107/// }; 4108/// \endcode 4109/// matches A::x 4110AST_MATCHER(CXXMethodDecl, isVirtual) { 4111 return Node.isVirtual(); 4112} 4113 4114/// \brief Matches if the given method declaration has an explicit "virtual". 4115/// 4116/// Given 4117/// \code 4118/// class A { 4119/// public: 4120/// virtual void x(); 4121/// }; 4122/// class B : public A { 4123/// public: 4124/// void x(); 4125/// }; 4126/// \endcode 4127/// matches A::x but not B::x 4128AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) { 4129 return Node.isVirtualAsWritten(); 4130} 4131 4132/// \brief Matches if the given method or class declaration is final. 4133/// 4134/// Given: 4135/// \code 4136/// class A final {}; 4137/// 4138/// struct B { 4139/// virtual void f(); 4140/// }; 4141/// 4142/// struct C : B { 4143/// void f() final; 4144/// }; 4145/// \endcode 4146/// matches A and C::f, but not B, C, or B::f 4147AST_POLYMORPHIC_MATCHER(isFinal, 4148 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, 4149 CXXMethodDecl)) { 4150 return Node.template hasAttr<FinalAttr>(); 4151} 4152 4153/// \brief Matches if the given method declaration is pure. 4154/// 4155/// Given 4156/// \code 4157/// class A { 4158/// public: 4159/// virtual void x() = 0; 4160/// }; 4161/// \endcode 4162/// matches A::x 4163AST_MATCHER(CXXMethodDecl, isPure) { 4164 return Node.isPure(); 4165} 4166 4167/// \brief Matches if the given method declaration is const. 4168/// 4169/// Given 4170/// \code 4171/// struct A { 4172/// void foo() const; 4173/// void bar(); 4174/// }; 4175/// \endcode 4176/// 4177/// cxxMethodDecl(isConst()) matches A::foo() but not A::bar() 4178AST_MATCHER(CXXMethodDecl, isConst) { 4179 return Node.isConst(); 4180} 4181 4182/// \brief Matches if the given method declaration declares a copy assignment 4183/// operator. 4184/// 4185/// Given 4186/// \code 4187/// struct A { 4188/// A &operator=(const A &); 4189/// A &operator=(A &&); 4190/// }; 4191/// \endcode 4192/// 4193/// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not 4194/// the second one. 4195AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) { 4196 return Node.isCopyAssignmentOperator(); 4197} 4198 4199/// \brief Matches if the given method declaration declares a move assignment 4200/// operator. 4201/// 4202/// Given 4203/// \code 4204/// struct A { 4205/// A &operator=(const A &); 4206/// A &operator=(A &&); 4207/// }; 4208/// \endcode 4209/// 4210/// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not 4211/// the first one. 4212AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) { 4213 return Node.isMoveAssignmentOperator(); 4214} 4215 4216/// \brief Matches if the given method declaration overrides another method. 4217/// 4218/// Given 4219/// \code 4220/// class A { 4221/// public: 4222/// virtual void x(); 4223/// }; 4224/// class B : public A { 4225/// public: 4226/// virtual void x(); 4227/// }; 4228/// \endcode 4229/// matches B::x 4230AST_MATCHER(CXXMethodDecl, isOverride) { 4231 return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>(); 4232} 4233 4234/// \brief Matches method declarations that are user-provided. 4235/// 4236/// Given 4237/// \code 4238/// struct S { 4239/// S(); // #1 4240/// S(const S &) = default; // #2 4241/// S(S &&) = delete; // #3 4242/// }; 4243/// \endcode 4244/// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3. 4245AST_MATCHER(CXXMethodDecl, isUserProvided) { 4246 return Node.isUserProvided(); 4247} 4248 4249/// \brief Matches member expressions that are called with '->' as opposed 4250/// to '.'. 4251/// 4252/// Member calls on the implicit this pointer match as called with '->'. 4253/// 4254/// Given 4255/// \code 4256/// class Y { 4257/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 4258/// int a; 4259/// static int b; 4260/// }; 4261/// \endcode 4262/// memberExpr(isArrow()) 4263/// matches this->x, x, y.x, a, this->b 4264AST_MATCHER(MemberExpr, isArrow) { 4265 return Node.isArrow(); 4266} 4267 4268/// \brief Matches QualType nodes that are of integer type. 4269/// 4270/// Given 4271/// \code 4272/// void a(int); 4273/// void b(long); 4274/// void c(double); 4275/// \endcode 4276/// functionDecl(hasAnyParameter(hasType(isInteger()))) 4277/// matches "a(int)", "b(long)", but not "c(double)". 4278AST_MATCHER(QualType, isInteger) { 4279 return Node->isIntegerType(); 4280} 4281 4282/// \brief Matches QualType nodes that are of unsigned integer type. 4283/// 4284/// Given 4285/// \code 4286/// void a(int); 4287/// void b(unsigned long); 4288/// void c(double); 4289/// \endcode 4290/// functionDecl(hasAnyParameter(hasType(isUnsignedInteger()))) 4291/// matches "b(unsigned long)", but not "a(int)" and "c(double)". 4292AST_MATCHER(QualType, isUnsignedInteger) { 4293 return Node->isUnsignedIntegerType(); 4294} 4295 4296/// \brief Matches QualType nodes that are of signed integer type. 4297/// 4298/// Given 4299/// \code 4300/// void a(int); 4301/// void b(unsigned long); 4302/// void c(double); 4303/// \endcode 4304/// functionDecl(hasAnyParameter(hasType(isSignedInteger()))) 4305/// matches "a(int)", but not "b(unsigned long)" and "c(double)". 4306AST_MATCHER(QualType, isSignedInteger) { 4307 return Node->isSignedIntegerType(); 4308} 4309 4310/// \brief Matches QualType nodes that are of character type. 4311/// 4312/// Given 4313/// \code 4314/// void a(char); 4315/// void b(wchar_t); 4316/// void c(double); 4317/// \endcode 4318/// functionDecl(hasAnyParameter(hasType(isAnyCharacter()))) 4319/// matches "a(char)", "b(wchar_t)", but not "c(double)". 4320AST_MATCHER(QualType, isAnyCharacter) { 4321 return Node->isAnyCharacterType(); 4322} 4323 4324/// \brief Matches QualType nodes that are of any pointer type; this includes 4325/// the Objective-C object pointer type, which is different despite being 4326/// syntactically similar. 4327/// 4328/// Given 4329/// \code 4330/// int *i = nullptr; 4331/// 4332/// @interface Foo 4333/// @end 4334/// Foo *f; 4335/// 4336/// int j; 4337/// \endcode 4338/// varDecl(hasType(isAnyPointer())) 4339/// matches "int *i" and "Foo *f", but not "int j". 4340AST_MATCHER(QualType, isAnyPointer) { 4341 return Node->isAnyPointerType(); 4342} 4343 4344/// \brief Matches QualType nodes that are const-qualified, i.e., that 4345/// include "top-level" const. 4346/// 4347/// Given 4348/// \code 4349/// void a(int); 4350/// void b(int const); 4351/// void c(const int); 4352/// void d(const int*); 4353/// void e(int const) {}; 4354/// \endcode 4355/// functionDecl(hasAnyParameter(hasType(isConstQualified()))) 4356/// matches "void b(int const)", "void c(const int)" and 4357/// "void e(int const) {}". It does not match d as there 4358/// is no top-level const on the parameter type "const int *". 4359AST_MATCHER(QualType, isConstQualified) { 4360 return Node.isConstQualified(); 4361} 4362 4363/// \brief Matches QualType nodes that are volatile-qualified, i.e., that 4364/// include "top-level" volatile. 4365/// 4366/// Given 4367/// \code 4368/// void a(int); 4369/// void b(int volatile); 4370/// void c(volatile int); 4371/// void d(volatile int*); 4372/// void e(int volatile) {}; 4373/// \endcode 4374/// functionDecl(hasAnyParameter(hasType(isVolatileQualified()))) 4375/// matches "void b(int volatile)", "void c(volatile int)" and 4376/// "void e(int volatile) {}". It does not match d as there 4377/// is no top-level volatile on the parameter type "volatile int *". 4378AST_MATCHER(QualType, isVolatileQualified) { 4379 return Node.isVolatileQualified(); 4380} 4381 4382/// \brief Matches QualType nodes that have local CV-qualifiers attached to 4383/// the node, not hidden within a typedef. 4384/// 4385/// Given 4386/// \code 4387/// typedef const int const_int; 4388/// const_int i; 4389/// int *const j; 4390/// int *volatile k; 4391/// int m; 4392/// \endcode 4393/// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k. 4394/// \c i is const-qualified but the qualifier is not local. 4395AST_MATCHER(QualType, hasLocalQualifiers) { 4396 return Node.hasLocalQualifiers(); 4397} 4398 4399/// \brief Matches a member expression where the member is matched by a 4400/// given matcher. 4401/// 4402/// Given 4403/// \code 4404/// struct { int first, second; } first, second; 4405/// int i(second.first); 4406/// int j(first.second); 4407/// \endcode 4408/// memberExpr(member(hasName("first"))) 4409/// matches second.first 4410/// but not first.second (because the member name there is "second"). 4411AST_MATCHER_P(MemberExpr, member, 4412 internal::Matcher<ValueDecl>, InnerMatcher) { 4413 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder); 4414} 4415 4416/// \brief Matches a member expression where the object expression is 4417/// matched by a given matcher. 4418/// 4419/// Given 4420/// \code 4421/// struct X { int m; }; 4422/// void f(X x) { x.m; m; } 4423/// \endcode 4424/// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X"))))))) 4425/// matches "x.m" and "m" 4426/// with hasObjectExpression(...) 4427/// matching "x" and the implicit object expression of "m" which has type X*. 4428AST_MATCHER_P(MemberExpr, hasObjectExpression, 4429 internal::Matcher<Expr>, InnerMatcher) { 4430 return InnerMatcher.matches(*Node.getBase(), Finder, Builder); 4431} 4432 4433/// \brief Matches any using shadow declaration. 4434/// 4435/// Given 4436/// \code 4437/// namespace X { void b(); } 4438/// using X::b; 4439/// \endcode 4440/// usingDecl(hasAnyUsingShadowDecl(hasName("b")))) 4441/// matches \code using X::b \endcode 4442AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl, 4443 internal::Matcher<UsingShadowDecl>, InnerMatcher) { 4444 return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(), 4445 Node.shadow_end(), Finder, Builder); 4446} 4447 4448/// \brief Matches a using shadow declaration where the target declaration is 4449/// matched by the given matcher. 4450/// 4451/// Given 4452/// \code 4453/// namespace X { int a; void b(); } 4454/// using X::a; 4455/// using X::b; 4456/// \endcode 4457/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl()))) 4458/// matches \code using X::b \endcode 4459/// but not \code using X::a \endcode 4460AST_MATCHER_P(UsingShadowDecl, hasTargetDecl, 4461 internal::Matcher<NamedDecl>, InnerMatcher) { 4462 return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder); 4463} 4464 4465/// \brief Matches template instantiations of function, class, or static 4466/// member variable template instantiations. 4467/// 4468/// Given 4469/// \code 4470/// template <typename T> class X {}; class A {}; X<A> x; 4471/// \endcode 4472/// or 4473/// \code 4474/// template <typename T> class X {}; class A {}; template class X<A>; 4475/// \endcode 4476/// cxxRecordDecl(hasName("::X"), isTemplateInstantiation()) 4477/// matches the template instantiation of X<A>. 4478/// 4479/// But given 4480/// \code 4481/// template <typename T> class X {}; class A {}; 4482/// template <> class X<A> {}; X<A> x; 4483/// \endcode 4484/// cxxRecordDecl(hasName("::X"), isTemplateInstantiation()) 4485/// does not match, as X<A> is an explicit template specialization. 4486/// 4487/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> 4488AST_POLYMORPHIC_MATCHER(isTemplateInstantiation, 4489 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl, 4490 CXXRecordDecl)) { 4491 return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation || 4492 Node.getTemplateSpecializationKind() == 4493 TSK_ExplicitInstantiationDefinition); 4494} 4495 4496/// \brief Matches declarations that are template instantiations or are inside 4497/// template instantiations. 4498/// 4499/// Given 4500/// \code 4501/// template<typename T> void A(T t) { T i; } 4502/// A(0); 4503/// A(0U); 4504/// \endcode 4505/// functionDecl(isInstantiated()) 4506/// matches 'A(int) {...};' and 'A(unsigned) {...}'. 4507AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) { 4508 auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()), 4509 functionDecl(isTemplateInstantiation()))); 4510 return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation))); 4511} 4512 4513/// \brief Matches statements inside of a template instantiation. 4514/// 4515/// Given 4516/// \code 4517/// int j; 4518/// template<typename T> void A(T t) { T i; j += 42;} 4519/// A(0); 4520/// A(0U); 4521/// \endcode 4522/// declStmt(isInTemplateInstantiation()) 4523/// matches 'int i;' and 'unsigned i'. 4524/// unless(stmt(isInTemplateInstantiation())) 4525/// will NOT match j += 42; as it's shared between the template definition and 4526/// instantiation. 4527AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) { 4528 return stmt( 4529 hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()), 4530 functionDecl(isTemplateInstantiation()))))); 4531} 4532 4533/// \brief Matches explicit template specializations of function, class, or 4534/// static member variable template instantiations. 4535/// 4536/// Given 4537/// \code 4538/// template<typename T> void A(T t) { } 4539/// template<> void A(int N) { } 4540/// \endcode 4541/// functionDecl(isExplicitTemplateSpecialization()) 4542/// matches the specialization A<int>(). 4543/// 4544/// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> 4545AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization, 4546 AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl, 4547 CXXRecordDecl)) { 4548 return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization); 4549} 4550 4551/// \brief Matches \c TypeLocs for which the given inner 4552/// QualType-matcher matches. 4553AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc, 4554 internal::Matcher<QualType>, InnerMatcher, 0) { 4555 return internal::BindableMatcher<TypeLoc>( 4556 new internal::TypeLocTypeMatcher(InnerMatcher)); 4557} 4558 4559/// \brief Matches type \c bool. 4560/// 4561/// Given 4562/// \code 4563/// struct S { bool func(); }; 4564/// \endcode 4565/// functionDecl(returns(booleanType())) 4566/// matches "bool func();" 4567AST_MATCHER(Type, booleanType) { 4568 return Node.isBooleanType(); 4569} 4570 4571/// \brief Matches type \c void. 4572/// 4573/// Given 4574/// \code 4575/// struct S { void func(); }; 4576/// \endcode 4577/// functionDecl(returns(voidType())) 4578/// matches "void func();" 4579AST_MATCHER(Type, voidType) { 4580 return Node.isVoidType(); 4581} 4582 4583/// \brief Matches builtin Types. 4584/// 4585/// Given 4586/// \code 4587/// struct A {}; 4588/// A a; 4589/// int b; 4590/// float c; 4591/// bool d; 4592/// \endcode 4593/// builtinType() 4594/// matches "int b", "float c" and "bool d" 4595AST_TYPE_MATCHER(BuiltinType, builtinType); 4596 4597/// \brief Matches all kinds of arrays. 4598/// 4599/// Given 4600/// \code 4601/// int a[] = { 2, 3 }; 4602/// int b[4]; 4603/// void f() { int c[a[0]]; } 4604/// \endcode 4605/// arrayType() 4606/// matches "int a[]", "int b[4]" and "int c[a[0]]"; 4607AST_TYPE_MATCHER(ArrayType, arrayType); 4608 4609/// \brief Matches C99 complex types. 4610/// 4611/// Given 4612/// \code 4613/// _Complex float f; 4614/// \endcode 4615/// complexType() 4616/// matches "_Complex float f" 4617AST_TYPE_MATCHER(ComplexType, complexType); 4618 4619/// \brief Matches any real floating-point type (float, double, long double). 4620/// 4621/// Given 4622/// \code 4623/// int i; 4624/// float f; 4625/// \endcode 4626/// realFloatingPointType() 4627/// matches "float f" but not "int i" 4628AST_MATCHER(Type, realFloatingPointType) { 4629 return Node.isRealFloatingType(); 4630} 4631 4632/// \brief Matches arrays and C99 complex types that have a specific element 4633/// type. 4634/// 4635/// Given 4636/// \code 4637/// struct A {}; 4638/// A a[7]; 4639/// int b[7]; 4640/// \endcode 4641/// arrayType(hasElementType(builtinType())) 4642/// matches "int b[7]" 4643/// 4644/// Usable as: Matcher<ArrayType>, Matcher<ComplexType> 4645AST_TYPELOC_TRAVERSE_MATCHER(hasElementType, getElement, 4646 AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType, 4647 ComplexType)); 4648 4649/// \brief Matches C arrays with a specified constant size. 4650/// 4651/// Given 4652/// \code 4653/// void() { 4654/// int a[2]; 4655/// int b[] = { 2, 3 }; 4656/// int c[b[0]]; 4657/// } 4658/// \endcode 4659/// constantArrayType() 4660/// matches "int a[2]" 4661AST_TYPE_MATCHER(ConstantArrayType, constantArrayType); 4662 4663/// \brief Matches nodes that have the specified size. 4664/// 4665/// Given 4666/// \code 4667/// int a[42]; 4668/// int b[2 * 21]; 4669/// int c[41], d[43]; 4670/// char *s = "abcd"; 4671/// wchar_t *ws = L"abcd"; 4672/// char *w = "a"; 4673/// \endcode 4674/// constantArrayType(hasSize(42)) 4675/// matches "int a[42]" and "int b[2 * 21]" 4676/// stringLiteral(hasSize(4)) 4677/// matches "abcd", L"abcd" 4678AST_POLYMORPHIC_MATCHER_P(hasSize, 4679 AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType, 4680 StringLiteral), 4681 unsigned, N) { 4682 return internal::HasSizeMatcher<NodeType>::hasSize(Node, N); 4683} 4684 4685/// \brief Matches C++ arrays whose size is a value-dependent expression. 4686/// 4687/// Given 4688/// \code 4689/// template<typename T, int Size> 4690/// class array { 4691/// T data[Size]; 4692/// }; 4693/// \endcode 4694/// dependentSizedArrayType 4695/// matches "T data[Size]" 4696AST_TYPE_MATCHER(DependentSizedArrayType, dependentSizedArrayType); 4697 4698/// \brief Matches C arrays with unspecified size. 4699/// 4700/// Given 4701/// \code 4702/// int a[] = { 2, 3 }; 4703/// int b[42]; 4704/// void f(int c[]) { int d[a[0]]; }; 4705/// \endcode 4706/// incompleteArrayType() 4707/// matches "int a[]" and "int c[]" 4708AST_TYPE_MATCHER(IncompleteArrayType, incompleteArrayType); 4709 4710/// \brief Matches C arrays with a specified size that is not an 4711/// integer-constant-expression. 4712/// 4713/// Given 4714/// \code 4715/// void f() { 4716/// int a[] = { 2, 3 } 4717/// int b[42]; 4718/// int c[a[0]]; 4719/// } 4720/// \endcode 4721/// variableArrayType() 4722/// matches "int c[a[0]]" 4723AST_TYPE_MATCHER(VariableArrayType, variableArrayType); 4724 4725/// \brief Matches \c VariableArrayType nodes that have a specific size 4726/// expression. 4727/// 4728/// Given 4729/// \code 4730/// void f(int b) { 4731/// int a[b]; 4732/// } 4733/// \endcode 4734/// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to( 4735/// varDecl(hasName("b"))))))) 4736/// matches "int a[b]" 4737AST_MATCHER_P(VariableArrayType, hasSizeExpr, 4738 internal::Matcher<Expr>, InnerMatcher) { 4739 return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder); 4740} 4741 4742/// \brief Matches atomic types. 4743/// 4744/// Given 4745/// \code 4746/// _Atomic(int) i; 4747/// \endcode 4748/// atomicType() 4749/// matches "_Atomic(int) i" 4750AST_TYPE_MATCHER(AtomicType, atomicType); 4751 4752/// \brief Matches atomic types with a specific value type. 4753/// 4754/// Given 4755/// \code 4756/// _Atomic(int) i; 4757/// _Atomic(float) f; 4758/// \endcode 4759/// atomicType(hasValueType(isInteger())) 4760/// matches "_Atomic(int) i" 4761/// 4762/// Usable as: Matcher<AtomicType> 4763AST_TYPELOC_TRAVERSE_MATCHER(hasValueType, getValue, 4764 AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType)); 4765 4766/// \brief Matches types nodes representing C++11 auto types. 4767/// 4768/// Given: 4769/// \code 4770/// auto n = 4; 4771/// int v[] = { 2, 3 } 4772/// for (auto i : v) { } 4773/// \endcode 4774/// autoType() 4775/// matches "auto n" and "auto i" 4776AST_TYPE_MATCHER(AutoType, autoType); 4777 4778/// \brief Matches \c AutoType nodes where the deduced type is a specific type. 4779/// 4780/// Note: There is no \c TypeLoc for the deduced type and thus no 4781/// \c getDeducedLoc() matcher. 4782/// 4783/// Given 4784/// \code 4785/// auto a = 1; 4786/// auto b = 2.0; 4787/// \endcode 4788/// autoType(hasDeducedType(isInteger())) 4789/// matches "auto a" 4790/// 4791/// Usable as: Matcher<AutoType> 4792AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType, 4793 AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType)); 4794 4795/// \brief Matches \c FunctionType nodes. 4796/// 4797/// Given 4798/// \code 4799/// int (*f)(int); 4800/// void g(); 4801/// \endcode 4802/// functionType() 4803/// matches "int (*f)(int)" and the type of "g". 4804AST_TYPE_MATCHER(FunctionType, functionType); 4805 4806/// \brief Matches \c FunctionProtoType nodes. 4807/// 4808/// Given 4809/// \code 4810/// int (*f)(int); 4811/// void g(); 4812/// \endcode 4813/// functionProtoType() 4814/// matches "int (*f)(int)" and the type of "g" in C++ mode. 4815/// In C mode, "g" is not matched because it does not contain a prototype. 4816AST_TYPE_MATCHER(FunctionProtoType, functionProtoType); 4817 4818/// \brief Matches \c ParenType nodes. 4819/// 4820/// Given 4821/// \code 4822/// int (*ptr_to_array)[4]; 4823/// int *array_of_ptrs[4]; 4824/// \endcode 4825/// 4826/// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not 4827/// \c array_of_ptrs. 4828AST_TYPE_MATCHER(ParenType, parenType); 4829 4830/// \brief Matches \c ParenType nodes where the inner type is a specific type. 4831/// 4832/// Given 4833/// \code 4834/// int (*ptr_to_array)[4]; 4835/// int (*ptr_to_func)(int); 4836/// \endcode 4837/// 4838/// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches 4839/// \c ptr_to_func but not \c ptr_to_array. 4840/// 4841/// Usable as: Matcher<ParenType> 4842AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType, 4843 AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType)); 4844 4845/// \brief Matches block pointer types, i.e. types syntactically represented as 4846/// "void (^)(int)". 4847/// 4848/// The \c pointee is always required to be a \c FunctionType. 4849AST_TYPE_MATCHER(BlockPointerType, blockPointerType); 4850 4851/// \brief Matches member pointer types. 4852/// Given 4853/// \code 4854/// struct A { int i; } 4855/// A::* ptr = A::i; 4856/// \endcode 4857/// memberPointerType() 4858/// matches "A::* ptr" 4859AST_TYPE_MATCHER(MemberPointerType, memberPointerType); 4860 4861/// \brief Matches pointer types, but does not match Objective-C object pointer 4862/// types. 4863/// 4864/// Given 4865/// \code 4866/// int *a; 4867/// int &b = *a; 4868/// int c = 5; 4869/// 4870/// @interface Foo 4871/// @end 4872/// Foo *f; 4873/// \endcode 4874/// pointerType() 4875/// matches "int *a", but does not match "Foo *f". 4876AST_TYPE_MATCHER(PointerType, pointerType); 4877 4878/// \brief Matches an Objective-C object pointer type, which is different from 4879/// a pointer type, despite being syntactically similar. 4880/// 4881/// Given 4882/// \code 4883/// int *a; 4884/// 4885/// @interface Foo 4886/// @end 4887/// Foo *f; 4888/// \endcode 4889/// pointerType() 4890/// matches "Foo *f", but does not match "int *a". 4891AST_TYPE_MATCHER(ObjCObjectPointerType, objcObjectPointerType); 4892 4893/// \brief Matches both lvalue and rvalue reference types. 4894/// 4895/// Given 4896/// \code 4897/// int *a; 4898/// int &b = *a; 4899/// int &&c = 1; 4900/// auto &d = b; 4901/// auto &&e = c; 4902/// auto &&f = 2; 4903/// int g = 5; 4904/// \endcode 4905/// 4906/// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f. 4907AST_TYPE_MATCHER(ReferenceType, referenceType); 4908 4909/// \brief Matches lvalue reference types. 4910/// 4911/// Given: 4912/// \code 4913/// int *a; 4914/// int &b = *a; 4915/// int &&c = 1; 4916/// auto &d = b; 4917/// auto &&e = c; 4918/// auto &&f = 2; 4919/// int g = 5; 4920/// \endcode 4921/// 4922/// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is 4923/// matched since the type is deduced as int& by reference collapsing rules. 4924AST_TYPE_MATCHER(LValueReferenceType, lValueReferenceType); 4925 4926/// \brief Matches rvalue reference types. 4927/// 4928/// Given: 4929/// \code 4930/// int *a; 4931/// int &b = *a; 4932/// int &&c = 1; 4933/// auto &d = b; 4934/// auto &&e = c; 4935/// auto &&f = 2; 4936/// int g = 5; 4937/// \endcode 4938/// 4939/// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not 4940/// matched as it is deduced to int& by reference collapsing rules. 4941AST_TYPE_MATCHER(RValueReferenceType, rValueReferenceType); 4942 4943/// \brief Narrows PointerType (and similar) matchers to those where the 4944/// \c pointee matches a given matcher. 4945/// 4946/// Given 4947/// \code 4948/// int *a; 4949/// int const *b; 4950/// float const *f; 4951/// \endcode 4952/// pointerType(pointee(isConstQualified(), isInteger())) 4953/// matches "int const *b" 4954/// 4955/// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>, 4956/// Matcher<PointerType>, Matcher<ReferenceType> 4957AST_TYPELOC_TRAVERSE_MATCHER(pointee, getPointee, 4958 AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, 4959 MemberPointerType, 4960 PointerType, 4961 ReferenceType)); 4962 4963/// \brief Matches typedef types. 4964/// 4965/// Given 4966/// \code 4967/// typedef int X; 4968/// \endcode 4969/// typedefType() 4970/// matches "typedef int X" 4971AST_TYPE_MATCHER(TypedefType, typedefType); 4972 4973/// \brief Matches enum types. 4974/// 4975/// Given 4976/// \code 4977/// enum C { Green }; 4978/// enum class S { Red }; 4979/// 4980/// C c; 4981/// S s; 4982/// \endcode 4983// 4984/// \c enumType() matches the type of the variable declarations of both \c c and 4985/// \c s. 4986AST_TYPE_MATCHER(EnumType, enumType); 4987 4988/// \brief Matches template specialization types. 4989/// 4990/// Given 4991/// \code 4992/// template <typename T> 4993/// class C { }; 4994/// 4995/// template class C<int>; // A 4996/// C<char> var; // B 4997/// \endcode 4998/// 4999/// \c templateSpecializationType() matches the type of the explicit 5000/// instantiation in \c A and the type of the variable declaration in \c B. 5001AST_TYPE_MATCHER(TemplateSpecializationType, templateSpecializationType); 5002 5003/// \brief Matches types nodes representing unary type transformations. 5004/// 5005/// Given: 5006/// \code 5007/// typedef __underlying_type(T) type; 5008/// \endcode 5009/// unaryTransformType() 5010/// matches "__underlying_type(T)" 5011AST_TYPE_MATCHER(UnaryTransformType, unaryTransformType); 5012 5013/// \brief Matches record types (e.g. structs, classes). 5014/// 5015/// Given 5016/// \code 5017/// class C {}; 5018/// struct S {}; 5019/// 5020/// C c; 5021/// S s; 5022/// \endcode 5023/// 5024/// \c recordType() matches the type of the variable declarations of both \c c 5025/// and \c s. 5026AST_TYPE_MATCHER(RecordType, recordType); 5027 5028/// \brief Matches types specified with an elaborated type keyword or with a 5029/// qualified name. 5030/// 5031/// Given 5032/// \code 5033/// namespace N { 5034/// namespace M { 5035/// class D {}; 5036/// } 5037/// } 5038/// class C {}; 5039/// 5040/// class C c; 5041/// N::M::D d; 5042/// \endcode 5043/// 5044/// \c elaboratedType() matches the type of the variable declarations of both 5045/// \c c and \c d. 5046AST_TYPE_MATCHER(ElaboratedType, elaboratedType); 5047 5048/// \brief Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier, 5049/// matches \c InnerMatcher if the qualifier exists. 5050/// 5051/// Given 5052/// \code 5053/// namespace N { 5054/// namespace M { 5055/// class D {}; 5056/// } 5057/// } 5058/// N::M::D d; 5059/// \endcode 5060/// 5061/// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))) 5062/// matches the type of the variable declaration of \c d. 5063AST_MATCHER_P(ElaboratedType, hasQualifier, 5064 internal::Matcher<NestedNameSpecifier>, InnerMatcher) { 5065 if (const NestedNameSpecifier *Qualifier = Node.getQualifier()) 5066 return InnerMatcher.matches(*Qualifier, Finder, Builder); 5067 5068 return false; 5069} 5070 5071/// \brief Matches ElaboratedTypes whose named type matches \c InnerMatcher. 5072/// 5073/// Given 5074/// \code 5075/// namespace N { 5076/// namespace M { 5077/// class D {}; 5078/// } 5079/// } 5080/// N::M::D d; 5081/// \endcode 5082/// 5083/// \c elaboratedType(namesType(recordType( 5084/// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable 5085/// declaration of \c d. 5086AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>, 5087 InnerMatcher) { 5088 return InnerMatcher.matches(Node.getNamedType(), Finder, Builder); 5089} 5090 5091/// \brief Matches types that represent the result of substituting a type for a 5092/// template type parameter. 5093/// 5094/// Given 5095/// \code 5096/// template <typename T> 5097/// void F(T t) { 5098/// int i = 1 + t; 5099/// } 5100/// \endcode 5101/// 5102/// \c substTemplateTypeParmType() matches the type of 't' but not '1' 5103AST_TYPE_MATCHER(SubstTemplateTypeParmType, substTemplateTypeParmType); 5104 5105/// \brief Matches template type parameter substitutions that have a replacement 5106/// type that matches the provided matcher. 5107/// 5108/// Given 5109/// \code 5110/// template <typename T> 5111/// double F(T t); 5112/// int i; 5113/// double j = F(i); 5114/// \endcode 5115/// 5116/// \c substTemplateTypeParmType(hasReplacementType(type())) matches int 5117AST_TYPE_TRAVERSE_MATCHER( 5118 hasReplacementType, getReplacementType, 5119 AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType)); 5120 5121/// \brief Matches template type parameter types. 5122/// 5123/// Example matches T, but not int. 5124/// (matcher = templateTypeParmType()) 5125/// \code 5126/// template <typename T> void f(int i); 5127/// \endcode 5128AST_TYPE_MATCHER(TemplateTypeParmType, templateTypeParmType); 5129 5130/// \brief Matches injected class name types. 5131/// 5132/// Example matches S s, but not S<T> s. 5133/// (matcher = parmVarDecl(hasType(injectedClassNameType()))) 5134/// \code 5135/// template <typename T> struct S { 5136/// void f(S s); 5137/// void g(S<T> s); 5138/// }; 5139/// \endcode 5140AST_TYPE_MATCHER(InjectedClassNameType, injectedClassNameType); 5141 5142/// \brief Matches decayed type 5143/// Example matches i[] in declaration of f. 5144/// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType()))))) 5145/// Example matches i[1]. 5146/// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType()))))) 5147/// \code 5148/// void f(int i[]) { 5149/// i[1] = 0; 5150/// } 5151/// \endcode 5152AST_TYPE_MATCHER(DecayedType, decayedType); 5153 5154/// \brief Matches the decayed type, whos decayed type matches \c InnerMatcher 5155AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>, 5156 InnerType) { 5157 return InnerType.matches(Node.getDecayedType(), Finder, Builder); 5158} 5159 5160/// \brief Matches declarations whose declaration context, interpreted as a 5161/// Decl, matches \c InnerMatcher. 5162/// 5163/// Given 5164/// \code 5165/// namespace N { 5166/// namespace M { 5167/// class D {}; 5168/// } 5169/// } 5170/// \endcode 5171/// 5172/// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the 5173/// declaration of \c class \c D. 5174AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) { 5175 const DeclContext *DC = Node.getDeclContext(); 5176 if (!DC) return false; 5177 return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder); 5178} 5179 5180/// \brief Matches nested name specifiers. 5181/// 5182/// Given 5183/// \code 5184/// namespace ns { 5185/// struct A { static void f(); }; 5186/// void A::f() {} 5187/// void g() { A::f(); } 5188/// } 5189/// ns::A a; 5190/// \endcode 5191/// nestedNameSpecifier() 5192/// matches "ns::" and both "A::" 5193const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier; 5194 5195/// \brief Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc. 5196const internal::VariadicAllOfMatcher< 5197 NestedNameSpecifierLoc> nestedNameSpecifierLoc; 5198 5199/// \brief Matches \c NestedNameSpecifierLocs for which the given inner 5200/// NestedNameSpecifier-matcher matches. 5201AST_MATCHER_FUNCTION_P_OVERLOAD( 5202 internal::BindableMatcher<NestedNameSpecifierLoc>, loc, 5203 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) { 5204 return internal::BindableMatcher<NestedNameSpecifierLoc>( 5205 new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>( 5206 InnerMatcher)); 5207} 5208 5209/// \brief Matches nested name specifiers that specify a type matching the 5210/// given \c QualType matcher without qualifiers. 5211/// 5212/// Given 5213/// \code 5214/// struct A { struct B { struct C {}; }; }; 5215/// A::B::C c; 5216/// \endcode 5217/// nestedNameSpecifier(specifiesType( 5218/// hasDeclaration(cxxRecordDecl(hasName("A"))) 5219/// )) 5220/// matches "A::" 5221AST_MATCHER_P(NestedNameSpecifier, specifiesType, 5222 internal::Matcher<QualType>, InnerMatcher) { 5223 if (!Node.getAsType()) 5224 return false; 5225 return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder); 5226} 5227 5228/// \brief Matches nested name specifier locs that specify a type matching the 5229/// given \c TypeLoc. 5230/// 5231/// Given 5232/// \code 5233/// struct A { struct B { struct C {}; }; }; 5234/// A::B::C c; 5235/// \endcode 5236/// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type( 5237/// hasDeclaration(cxxRecordDecl(hasName("A"))))))) 5238/// matches "A::" 5239AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc, 5240 internal::Matcher<TypeLoc>, InnerMatcher) { 5241 return Node && InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder); 5242} 5243 5244/// \brief Matches on the prefix of a \c NestedNameSpecifier. 5245/// 5246/// Given 5247/// \code 5248/// struct A { struct B { struct C {}; }; }; 5249/// A::B::C c; 5250/// \endcode 5251/// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and 5252/// matches "A::" 5253AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix, 5254 internal::Matcher<NestedNameSpecifier>, InnerMatcher, 5255 0) { 5256 const NestedNameSpecifier *NextNode = Node.getPrefix(); 5257 if (!NextNode) 5258 return false; 5259 return InnerMatcher.matches(*NextNode, Finder, Builder); 5260} 5261 5262/// \brief Matches on the prefix of a \c NestedNameSpecifierLoc. 5263/// 5264/// Given 5265/// \code 5266/// struct A { struct B { struct C {}; }; }; 5267/// A::B::C c; 5268/// \endcode 5269/// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A"))))) 5270/// matches "A::" 5271AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix, 5272 internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher, 5273 1) { 5274 NestedNameSpecifierLoc NextNode = Node.getPrefix(); 5275 if (!NextNode) 5276 return false; 5277 return InnerMatcher.matches(NextNode, Finder, Builder); 5278} 5279 5280/// \brief Matches nested name specifiers that specify a namespace matching the 5281/// given namespace matcher. 5282/// 5283/// Given 5284/// \code 5285/// namespace ns { struct A {}; } 5286/// ns::A a; 5287/// \endcode 5288/// nestedNameSpecifier(specifiesNamespace(hasName("ns"))) 5289/// matches "ns::" 5290AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace, 5291 internal::Matcher<NamespaceDecl>, InnerMatcher) { 5292 if (!Node.getAsNamespace()) 5293 return false; 5294 return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder); 5295} 5296 5297/// \brief Overloads for the \c equalsNode matcher. 5298/// FIXME: Implement for other node types. 5299/// @{ 5300 5301/// \brief Matches if a node equals another node. 5302/// 5303/// \c Decl has pointer identity in the AST. 5304AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) { 5305 return &Node == Other; 5306} 5307/// \brief Matches if a node equals another node. 5308/// 5309/// \c Stmt has pointer identity in the AST. 5310AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) { 5311 return &Node == Other; 5312} 5313/// \brief Matches if a node equals another node. 5314/// 5315/// \c Type has pointer identity in the AST. 5316AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) { 5317 return &Node == Other; 5318} 5319 5320/// @} 5321 5322/// \brief Matches each case or default statement belonging to the given switch 5323/// statement. This matcher may produce multiple matches. 5324/// 5325/// Given 5326/// \code 5327/// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } } 5328/// \endcode 5329/// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s") 5330/// matches four times, with "c" binding each of "case 1:", "case 2:", 5331/// "case 3:" and "case 4:", and "s" respectively binding "switch (1)", 5332/// "switch (1)", "switch (2)" and "switch (2)". 5333AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>, 5334 InnerMatcher) { 5335 BoundNodesTreeBuilder Result; 5336 // FIXME: getSwitchCaseList() does not necessarily guarantee a stable 5337 // iteration order. We should use the more general iterating matchers once 5338 // they are capable of expressing this matcher (for example, it should ignore 5339 // case statements belonging to nested switch statements). 5340 bool Matched = false; 5341 for (const SwitchCase *SC = Node.getSwitchCaseList(); SC; 5342 SC = SC->getNextSwitchCase()) { 5343 BoundNodesTreeBuilder CaseBuilder(*Builder); 5344 bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder); 5345 if (CaseMatched) { 5346 Matched = true; 5347 Result.addMatch(CaseBuilder); 5348 } 5349 } 5350 *Builder = std::move(Result); 5351 return Matched; 5352} 5353 5354/// \brief Matches each constructor initializer in a constructor definition. 5355/// 5356/// Given 5357/// \code 5358/// class A { A() : i(42), j(42) {} int i; int j; }; 5359/// \endcode 5360/// cxxConstructorDecl(forEachConstructorInitializer( 5361/// forField(decl().bind("x")) 5362/// )) 5363/// will trigger two matches, binding for 'i' and 'j' respectively. 5364AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer, 5365 internal::Matcher<CXXCtorInitializer>, InnerMatcher) { 5366 BoundNodesTreeBuilder Result; 5367 bool Matched = false; 5368 for (const auto *I : Node.inits()) { 5369 BoundNodesTreeBuilder InitBuilder(*Builder); 5370 if (InnerMatcher.matches(*I, Finder, &InitBuilder)) { 5371 Matched = true; 5372 Result.addMatch(InitBuilder); 5373 } 5374 } 5375 *Builder = std::move(Result); 5376 return Matched; 5377} 5378 5379/// \brief Matches constructor declarations that are copy constructors. 5380/// 5381/// Given 5382/// \code 5383/// struct S { 5384/// S(); // #1 5385/// S(const S &); // #2 5386/// S(S &&); // #3 5387/// }; 5388/// \endcode 5389/// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3. 5390AST_MATCHER(CXXConstructorDecl, isCopyConstructor) { 5391 return Node.isCopyConstructor(); 5392} 5393 5394/// \brief Matches constructor declarations that are move constructors. 5395/// 5396/// Given 5397/// \code 5398/// struct S { 5399/// S(); // #1 5400/// S(const S &); // #2 5401/// S(S &&); // #3 5402/// }; 5403/// \endcode 5404/// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2. 5405AST_MATCHER(CXXConstructorDecl, isMoveConstructor) { 5406 return Node.isMoveConstructor(); 5407} 5408 5409/// \brief Matches constructor declarations that are default constructors. 5410/// 5411/// Given 5412/// \code 5413/// struct S { 5414/// S(); // #1 5415/// S(const S &); // #2 5416/// S(S &&); // #3 5417/// }; 5418/// \endcode 5419/// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3. 5420AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) { 5421 return Node.isDefaultConstructor(); 5422} 5423 5424/// \brief Matches constructors that delegate to another constructor. 5425/// 5426/// Given 5427/// \code 5428/// struct S { 5429/// S(); // #1 5430/// S(int) {} // #2 5431/// S(S &&) : S() {} // #3 5432/// }; 5433/// S::S() : S(0) {} // #4 5434/// \endcode 5435/// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not 5436/// #1 or #2. 5437AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) { 5438 return Node.isDelegatingConstructor(); 5439} 5440 5441/// \brief Matches constructor and conversion declarations that are marked with 5442/// the explicit keyword. 5443/// 5444/// Given 5445/// \code 5446/// struct S { 5447/// S(int); // #1 5448/// explicit S(double); // #2 5449/// operator int(); // #3 5450/// explicit operator bool(); // #4 5451/// }; 5452/// \endcode 5453/// cxxConstructorDecl(isExplicit()) will match #2, but not #1. 5454/// cxxConversionDecl(isExplicit()) will match #4, but not #3. 5455AST_POLYMORPHIC_MATCHER(isExplicit, 5456 AST_POLYMORPHIC_SUPPORTED_TYPES(CXXConstructorDecl, 5457 CXXConversionDecl)) { 5458 return Node.isExplicit(); 5459} 5460 5461/// \brief Matches function and namespace declarations that are marked with 5462/// the inline keyword. 5463/// 5464/// Given 5465/// \code 5466/// inline void f(); 5467/// void g(); 5468/// namespace n { 5469/// inline namespace m {} 5470/// } 5471/// \endcode 5472/// functionDecl(isInline()) will match ::f(). 5473/// namespaceDecl(isInline()) will match n::m. 5474AST_POLYMORPHIC_MATCHER(isInline, 5475 AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl, 5476 FunctionDecl)) { 5477 // This is required because the spelling of the function used to determine 5478 // whether inline is specified or not differs between the polymorphic types. 5479 if (const auto *FD = dyn_cast<FunctionDecl>(&Node)) 5480 return FD->isInlineSpecified(); 5481 else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node)) 5482 return NSD->isInline(); 5483 llvm_unreachable("Not a valid polymorphic type"); 5484} 5485 5486/// \brief Matches anonymous namespace declarations. 5487/// 5488/// Given 5489/// \code 5490/// namespace n { 5491/// namespace {} // #1 5492/// } 5493/// \endcode 5494/// namespaceDecl(isAnonymous()) will match #1 but not ::n. 5495AST_MATCHER(NamespaceDecl, isAnonymous) { 5496 return Node.isAnonymousNamespace(); 5497} 5498 5499/// \brief If the given case statement does not use the GNU case range 5500/// extension, matches the constant given in the statement. 5501/// 5502/// Given 5503/// \code 5504/// switch (1) { case 1: case 1+1: case 3 ... 4: ; } 5505/// \endcode 5506/// caseStmt(hasCaseConstant(integerLiteral())) 5507/// matches "case 1:" 5508AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>, 5509 InnerMatcher) { 5510 if (Node.getRHS()) 5511 return false; 5512 5513 return InnerMatcher.matches(*Node.getLHS(), Finder, Builder); 5514} 5515 5516/// \brief Matches declaration that has a given attribute. 5517/// 5518/// Given 5519/// \code 5520/// __attribute__((device)) void f() { ... } 5521/// \endcode 5522/// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of 5523/// f. If the matcher is use from clang-query, attr::Kind parameter should be 5524/// passed as a quoted string. e.g., hasAttr("attr::CUDADevice"). 5525AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) { 5526 for (const auto *Attr : Node.attrs()) { 5527 if (Attr->getKind() == AttrKind) 5528 return true; 5529 } 5530 return false; 5531} 5532 5533/// \brief Matches the return value expression of a return statement 5534/// 5535/// Given 5536/// \code 5537/// return a + b; 5538/// \endcode 5539/// hasReturnValue(binaryOperator()) 5540/// matches 'return a + b' 5541/// with binaryOperator() 5542/// matching 'a + b' 5543AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>, 5544 InnerMatcher) { 5545 if (const auto *RetValue = Node.getRetValue()) 5546 return InnerMatcher.matches(*RetValue, Finder, Builder); 5547 return false; 5548} 5549 5550 5551/// \brief Matches CUDA kernel call expression. 5552/// 5553/// Example matches, 5554/// \code 5555/// kernel<<<i,j>>>(); 5556/// \endcode 5557const internal::VariadicDynCastAllOfMatcher< 5558 Stmt, 5559 CUDAKernelCallExpr> cudaKernelCallExpr; 5560 5561 5562/// \brief Matches expressions that resolve to a null pointer constant, such as 5563/// GNU's __null, C++11's nullptr, or C's NULL macro. 5564/// 5565/// Given: 5566/// \code 5567/// void *v1 = NULL; 5568/// void *v2 = nullptr; 5569/// void *v3 = __null; // GNU extension 5570/// char *cp = (char *)0; 5571/// int *ip = 0; 5572/// int i = 0; 5573/// \endcode 5574/// expr(nullPointerConstant()) 5575/// matches the initializer for v1, v2, v3, cp, and ip. Does not match the 5576/// initializer for i. 5577AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) { 5578 return anyOf( 5579 gnuNullExpr(), cxxNullPtrLiteralExpr(), 5580 integerLiteral(equals(0), hasParent(expr(hasType(pointerType()))))); 5581} 5582 5583/// \brief Matches declaration of the function the statement belongs to 5584/// 5585/// Given: 5586/// \code 5587/// F& operator=(const F& o) { 5588/// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; }); 5589/// return *this; 5590/// } 5591/// \endcode 5592/// returnStmt(forFunction(hasName("operator="))) 5593/// matches 'return *this' 5594/// but does match 'return > 0' 5595AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>, 5596 InnerMatcher) { 5597 const auto &Parents = Finder->getASTContext().getParents(Node); 5598 5599 llvm::SmallVector<ast_type_traits::DynTypedNode, 8> Stack(Parents.begin(), 5600 Parents.end()); 5601 while(!Stack.empty()) { 5602 const auto &CurNode = Stack.back(); 5603 Stack.pop_back(); 5604 if(const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) { 5605 if(InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) { 5606 return true; 5607 } 5608 } else if(const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) { 5609 if(InnerMatcher.matches(*LambdaExprNode->getCallOperator(), 5610 Finder, Builder)) { 5611 return true; 5612 } 5613 } else { 5614 for(const auto &Parent: Finder->getASTContext().getParents(CurNode)) 5615 Stack.push_back(Parent); 5616 } 5617 } 5618 return false; 5619} 5620 5621/// \brief Matches a declaration that has external formal linkage. 5622/// 5623/// Example matches only z (matcher = varDecl(hasExternalFormalLinkage())) 5624/// \code 5625/// void f() { 5626/// int x; 5627/// static int y; 5628/// } 5629/// int z; 5630/// \endcode 5631/// 5632/// Example matches f() because it has external formal linkage despite being 5633/// unique to the translation unit as though it has internal likage 5634/// (matcher = functionDecl(hasExternalFormalLinkage())) 5635/// 5636/// \code 5637/// namespace { 5638/// void f() {} 5639/// } 5640/// \endcode 5641AST_MATCHER(NamedDecl, hasExternalFormalLinkage) { 5642 return Node.hasExternalFormalLinkage(); 5643} 5644 5645} // end namespace ast_matchers 5646} // end namespace clang 5647 5648#endif 5649