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