ASTMatchers.h revision e0e6b9e79a0c4edae92abd3928263875c78e23aa
1//===--- ASTMatchers.h - Structural query framework -------------*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements matchers to be used together with the MatchFinder to 11// match AST nodes. 12// 13// Matchers are created by generator functions, which can be combined in 14// a functional in-language DSL to express queries over the C++ AST. 15// 16// For example, to match a class with a certain name, one would call: 17// record(hasName("MyClass")) 18// which returns a matcher that can be used to find all AST nodes that declare 19// a class named 'MyClass'. 20// 21// For more complicated match expressions we're often interested in accessing 22// multiple parts of the matched AST nodes once a match is found. In that case, 23// use the id(...) matcher around the match expressions that match the nodes 24// you want to access. 25// 26// For example, when we're interested in child classes of a certain class, we 27// would write: 28// record(hasName("MyClass"), hasChild(id("child", record()))) 29// When the match is found via the MatchFinder, a user provided callback will 30// be called with a BoundNodes instance that contains a mapping from the 31// strings that we provided for the id(...) calls to the nodes that were 32// matched. 33// In the given example, each time our matcher finds a match we get a callback 34// where "child" is bound to the CXXRecordDecl node of the matching child 35// class declaration. 36// 37// See ASTMatchersInternal.h for a more in-depth explanation of the 38// implementation details of the matcher framework. 39// 40// See ASTMatchFinder.h for how to use the generated matchers to run over 41// an AST. 42// 43//===----------------------------------------------------------------------===// 44 45#ifndef LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H 46#define LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H 47 48#include "clang/AST/DeclTemplate.h" 49#include "clang/ASTMatchers/ASTMatchersInternal.h" 50#include "clang/ASTMatchers/ASTMatchersMacros.h" 51#include "llvm/ADT/Twine.h" 52#include "llvm/Support/Regex.h" 53 54namespace clang { 55namespace ast_matchers { 56 57/// \brief Maps string IDs to AST nodes matched by parts of a matcher. 58/// 59/// The bound nodes are generated by adding id(...) matchers into the 60/// match expression around the matchers for the nodes we want to access later. 61/// 62/// The instances of BoundNodes are created by MatchFinder when the user's 63/// callbacks are executed every time a match is found. 64class BoundNodes { 65public: 66 /// \brief Returns the AST node bound to 'ID'. 67 /// Returns NULL if there was no node bound to 'ID' or if there is a node but 68 /// it cannot be converted to the specified type. 69 /// FIXME: We'll need one of those for every base type. 70 /// @{ 71 template <typename T> 72 const T *getDeclAs(StringRef ID) const { 73 return getNodeAs<T>(DeclBindings, ID); 74 } 75 template <typename T> 76 const T *getStmtAs(StringRef ID) const { 77 return getNodeAs<T>(StmtBindings, ID); 78 } 79 /// @} 80 81private: 82 /// \brief Create BoundNodes from a pre-filled map of bindings. 83 BoundNodes(const std::map<std::string, const Decl*> &DeclBindings, 84 const std::map<std::string, const Stmt*> &StmtBindings) 85 : DeclBindings(DeclBindings), StmtBindings(StmtBindings) {} 86 87 template <typename T, typename MapT> 88 const T *getNodeAs(const MapT &Bindings, StringRef ID) const { 89 typename MapT::const_iterator It = Bindings.find(ID); 90 if (It == Bindings.end()) { 91 return NULL; 92 } 93 return llvm::dyn_cast<T>(It->second); 94 } 95 96 std::map<std::string, const Decl*> DeclBindings; 97 std::map<std::string, const Stmt*> StmtBindings; 98 99 friend class internal::BoundNodesTree; 100}; 101 102/// \brief If the provided matcher matches a node, binds the node to 'ID'. 103/// 104/// FIXME: Add example for accessing it. 105template <typename T> 106internal::Matcher<T> id(const std::string &ID, 107 const internal::Matcher<T> &InnerMatcher) { 108 return internal::Matcher<T>(new internal::IdMatcher<T>(ID, InnerMatcher)); 109} 110 111/// \brief Types of matchers for the top-level classes in the AST class 112/// hierarchy. 113/// @{ 114typedef internal::Matcher<Decl> DeclarationMatcher; 115typedef internal::Matcher<QualType> TypeMatcher; 116typedef internal::Matcher<Stmt> StatementMatcher; 117/// @} 118 119/// \brief Matches any node. 120/// 121/// Useful when another matcher requires a child matcher, but there's no 122/// additional constraint. This will often be used with an explicit conversion 123/// to a internal::Matcher<> type such as TypeMatcher. 124/// 125/// Example: DeclarationMatcher(anything()) matches all declarations, e.g., 126/// "int* p" and "void f()" in 127/// int* p; 128/// void f(); 129inline internal::PolymorphicMatcherWithParam0<internal::TrueMatcher> anything() { 130 return internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>(); 131} 132 133/// \brief Matches a declaration of anything that could have a name. 134/// 135/// Example matches X, S, the anonymous union type, i, and U; 136/// typedef int X; 137/// struct S { 138/// union { 139/// int i; 140/// } U; 141/// }; 142const internal::VariadicDynCastAllOfMatcher< 143 Decl, 144 NamedDecl> nameableDeclaration; 145 146/// \brief Matches C++ class declarations. 147/// 148/// Example matches X, Z 149/// class X; 150/// template<class T> class Z {}; 151const internal::VariadicDynCastAllOfMatcher< 152 Decl, 153 CXXRecordDecl> record; 154 155/// \brief Matches C++ class template specializations. 156/// 157/// Given 158/// template<typename T> class A {}; 159/// template<> class A<double> {}; 160/// A<int> a; 161/// classTemplateSpecialization() 162/// matches the specializations \c A<int> and \c A<double> 163const internal::VariadicDynCastAllOfMatcher< 164 Decl, 165 ClassTemplateSpecializationDecl> classTemplateSpecialization; 166 167/// \brief Matches classTemplateSpecializations that have at least one 168/// TemplateArgument matching the given Matcher. 169/// 170/// Given 171/// template<typename T> class A {}; 172/// template<> class A<double> {}; 173/// A<int> a; 174/// classTemplateSpecialization(hasAnyTemplateArgument( 175/// refersToType(asString("int")))) 176/// matches the specialization \c A<int> 177AST_MATCHER_P(ClassTemplateSpecializationDecl, hasAnyTemplateArgument, 178 internal::Matcher<TemplateArgument>, Matcher) { 179 const TemplateArgumentList &List = Node.getTemplateArgs(); 180 for (unsigned i = 0; i < List.size(); ++i) { 181 if (Matcher.matches(List.get(i), Finder, Builder)) 182 return true; 183 } 184 return false; 185} 186 187/// \brief Matches classTemplateSpecializations where the n'th TemplateArgument 188/// matches the given Matcher. 189/// 190/// Given 191/// template<typename T, typename U> class A {}; 192/// A<bool, int> b; 193/// A<int, bool> c; 194/// classTemplateSpecialization(hasTemplateArgument( 195/// 1, refersToType(asString("int")))) 196/// matches the specialization \c A<bool, int> 197AST_MATCHER_P2(ClassTemplateSpecializationDecl, hasTemplateArgument, 198 unsigned, N, internal::Matcher<TemplateArgument>, Matcher) { 199 const TemplateArgumentList &List = Node.getTemplateArgs(); 200 if (List.size() <= N) 201 return false; 202 return Matcher.matches(List.get(N), Finder, Builder); 203} 204 205/// \brief Matches a TemplateArgument that refers to a certain type. 206/// 207/// Given 208/// struct X {}; 209/// template<typename T> struct A {}; 210/// A<X> a; 211/// classTemplateSpecialization(hasAnyTemplateArgument( 212/// refersToType(class(hasName("X"))))) 213/// matches the specialization \c A<X> 214AST_MATCHER_P(TemplateArgument, refersToType, 215 internal::Matcher<QualType>, Matcher) { 216 if (Node.getKind() != TemplateArgument::Type) 217 return false; 218 return Matcher.matches(Node.getAsType(), Finder, Builder); 219} 220 221/// \brief Matches a TemplateArgument that refers to a certain declaration. 222/// 223/// Given 224/// template<typename T> struct A {}; 225/// struct B { B* next; }; 226/// A<&B::next> a; 227/// classTemplateSpecialization(hasAnyTemplateArgument( 228/// refersToDeclaration(field(hasName("next")))) 229/// matches the specialization \c A<&B::next> with \c field(...) matching 230/// \c B::next 231AST_MATCHER_P(TemplateArgument, refersToDeclaration, 232 internal::Matcher<Decl>, Matcher) { 233 if (const Decl *Declaration = Node.getAsDecl()) 234 return Matcher.matches(*Declaration, Finder, Builder); 235 return false; 236} 237 238/// \brief Matches C++ constructor declarations. 239/// 240/// Example matches Foo::Foo() and Foo::Foo(int) 241/// class Foo { 242/// public: 243/// Foo(); 244/// Foo(int); 245/// int DoSomething(); 246/// }; 247const internal::VariadicDynCastAllOfMatcher< 248 Decl, 249 CXXConstructorDecl> constructor; 250 251/// \brief Matches explicit C++ destructor declarations. 252/// 253/// Example matches Foo::~Foo() 254/// class Foo { 255/// public: 256/// virtual ~Foo(); 257/// }; 258const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl> destructor; 259 260/// \brief Matches enum declarations. 261/// 262/// Example matches X 263/// enum X { 264/// A, B, C 265/// }; 266const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl; 267 268/// \brief Matches enum constants. 269/// 270/// Example matches A, B, C 271/// enum X { 272/// A, B, C 273/// }; 274const internal::VariadicDynCastAllOfMatcher< 275 Decl, 276 EnumConstantDecl> enumConstant; 277 278/// \brief Matches method declarations. 279/// 280/// Example matches y 281/// class X { void y() }; 282const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> method; 283 284/// \brief Matches variable declarations. 285/// 286/// Note: this does not match declarations of member variables, which are 287/// "field" declarations in Clang parlance. 288/// 289/// Example matches a 290/// int a; 291const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> variable; 292 293/// \brief Matches field declarations. 294/// 295/// Given 296/// class X { int m; }; 297/// field() 298/// matches 'm'. 299const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> field; 300 301/// \brief Matches function declarations. 302/// 303/// Example matches f 304/// void f(); 305const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> function; 306 307 308/// \brief Matches statements. 309/// 310/// Given 311/// { ++a; } 312/// statement() 313/// matches both the compound statement '{ ++a; }' and '++a'. 314const internal::VariadicDynCastAllOfMatcher<Stmt, Stmt> statement; 315 316/// \brief Matches declaration statements. 317/// 318/// Given 319/// int a; 320/// declarationStatement() 321/// matches 'int a'. 322const internal::VariadicDynCastAllOfMatcher< 323 Stmt, 324 DeclStmt> declarationStatement; 325 326/// \brief Matches member expressions. 327/// 328/// Given 329/// class Y { 330/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 331/// int a; static int b; 332/// }; 333/// memberExpression() 334/// matches this->x, x, y.x, a, this->b 335const internal::VariadicDynCastAllOfMatcher< 336 Stmt, 337 MemberExpr> memberExpression; 338 339/// \brief Matches call expressions. 340/// 341/// Example matches x.y() 342/// X x; 343/// x.y(); 344const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> call; 345 346/// \brief Matches init list expressions. 347/// 348/// Given 349/// int a[] = { 1, 2 }; 350/// struct B { int x, y; }; 351/// B b = { 5, 6 }; 352/// initList() 353/// matches "{ 1, 2 }" and "{ 5, 6 }" 354const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr; 355 356/// \brief Matches using declarations. 357/// 358/// Given 359/// namespace X { int x; } 360/// using X::x; 361/// usingDecl() 362/// matches \code using X::x \endcode 363const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl; 364 365/// \brief Matches constructor call expressions (including implicit ones). 366/// 367/// Example matches string(ptr, n) and ptr within arguments of f 368/// (matcher = constructorCall()) 369/// void f(const string &a, const string &b); 370/// char *ptr; 371/// int n; 372/// f(string(ptr, n), ptr); 373const internal::VariadicDynCastAllOfMatcher< 374 Stmt, 375 CXXConstructExpr> constructorCall; 376 377/// \brief Matches nodes where temporaries are created. 378/// 379/// Example matches FunctionTakesString(GetStringByValue()) 380/// (matcher = bindTemporaryExpression()) 381/// FunctionTakesString(GetStringByValue()); 382/// FunctionTakesStringByPointer(GetStringPointer()); 383const internal::VariadicDynCastAllOfMatcher< 384 Stmt, 385 CXXBindTemporaryExpr> bindTemporaryExpression; 386 387/// \brief Matches new expressions. 388/// 389/// Given 390/// new X; 391/// newExpression() 392/// matches 'new X'. 393const internal::VariadicDynCastAllOfMatcher< 394 Stmt, 395 CXXNewExpr> newExpression; 396 397/// \brief Matches delete expressions. 398/// 399/// Given 400/// delete X; 401/// deleteExpression() 402/// matches 'delete X'. 403const internal::VariadicDynCastAllOfMatcher< 404 Stmt, 405 CXXDeleteExpr> deleteExpression; 406 407/// \brief Matches array subscript expressions. 408/// 409/// Given 410/// int i = a[1]; 411/// arraySubscriptExpr() 412/// matches "a[1]" 413const internal::VariadicDynCastAllOfMatcher< 414 Stmt, 415 ArraySubscriptExpr> arraySubscriptExpr; 416 417/// \brief Matches the value of a default argument at the call site. 418/// 419/// Example matches the CXXDefaultArgExpr placeholder inserted for the 420/// default value of the second parameter in the call expression f(42) 421/// (matcher = defaultArgument()) 422/// void f(int x, int y = 0); 423/// f(42); 424const internal::VariadicDynCastAllOfMatcher< 425 Stmt, 426 CXXDefaultArgExpr> defaultArgument; 427 428/// \brief Matches overloaded operator calls. 429/// 430/// Note that if an operator isn't overloaded, it won't match. Instead, use 431/// binaryOperator matcher. 432/// Currently it does not match operators such as new delete. 433/// FIXME: figure out why these do not match? 434/// 435/// Example matches both operator<<((o << b), c) and operator<<(o, b) 436/// (matcher = overloadedOperatorCall()) 437/// ostream &operator<< (ostream &out, int i) { }; 438/// ostream &o; int b = 1, c = 1; 439/// o << b << c; 440const internal::VariadicDynCastAllOfMatcher< 441 Stmt, 442 CXXOperatorCallExpr> overloadedOperatorCall; 443 444/// \brief Matches expressions. 445/// 446/// Example matches x() 447/// void f() { x(); } 448const internal::VariadicDynCastAllOfMatcher< 449 Stmt, 450 Expr> expression; 451 452/// \brief Matches expressions that refer to declarations. 453/// 454/// Example matches x in if (x) 455/// bool x; 456/// if (x) {} 457const internal::VariadicDynCastAllOfMatcher< 458 Stmt, 459 DeclRefExpr> declarationReference; 460 461/// \brief Matches if statements. 462/// 463/// Example matches 'if (x) {}' 464/// if (x) {} 465const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt; 466 467/// \brief Matches for statements. 468/// 469/// Example matches 'for (;;) {}' 470/// for (;;) {} 471const internal::VariadicDynCastAllOfMatcher< 472 Stmt, ForStmt> forStmt; 473 474/// \brief Matches while statements. 475/// 476/// Given 477/// while (true) {} 478/// whileStmt() 479/// matches 'while (true) {}'. 480const internal::VariadicDynCastAllOfMatcher< 481 Stmt, 482 WhileStmt> whileStmt; 483 484/// \brief Matches do statements. 485/// 486/// Given 487/// do {} while (true); 488/// doStmt() 489/// matches 'do {} while(true)' 490const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt; 491 492/// \brief Matches case and default statements inside switch statements. 493/// 494/// Given 495/// switch(a) { case 42: break; default: break; } 496/// switchCase() 497/// matches 'case 42: break;' and 'default: break;'. 498const internal::VariadicDynCastAllOfMatcher< 499 Stmt, 500 SwitchCase> switchCase; 501 502/// \brief Matches compound statements. 503/// 504/// Example matches '{}' and '{{}}'in 'for (;;) {{}}' 505/// for (;;) {{}} 506const internal::VariadicDynCastAllOfMatcher< 507 Stmt, 508 CompoundStmt> compoundStatement; 509 510/// \brief Matches bool literals. 511/// 512/// Example matches true 513/// true 514const internal::VariadicDynCastAllOfMatcher< 515 Expr, 516 CXXBoolLiteralExpr> boolLiteral; 517 518/// \brief Matches string literals (also matches wide string literals). 519/// 520/// Example matches "abcd", L"abcd" 521/// char *s = "abcd"; wchar_t *ws = L"abcd" 522const internal::VariadicDynCastAllOfMatcher< 523 Expr, 524 StringLiteral> stringLiteral; 525 526/// \brief Matches character literals (also matches wchar_t). 527/// 528/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral), 529/// though. 530/// 531/// Example matches 'a', L'a' 532/// char ch = 'a'; wchar_t chw = L'a'; 533const internal::VariadicDynCastAllOfMatcher< 534 Expr, 535 CharacterLiteral> characterLiteral; 536 537/// \brief Matches integer literals of all sizes / encodings. 538/// 539/// Not matching character-encoded integers such as L'a'. 540/// 541/// Example matches 1, 1L, 0x1, 1U 542const internal::VariadicDynCastAllOfMatcher< 543 Expr, 544 IntegerLiteral> integerLiteral; 545 546/// \brief Matches binary operator expressions. 547/// 548/// Example matches a || b 549/// !(a || b) 550const internal::VariadicDynCastAllOfMatcher< 551 Stmt, 552 BinaryOperator> binaryOperator; 553 554/// \brief Matches unary operator expressions. 555/// 556/// Example matches !a 557/// !a || b 558const internal::VariadicDynCastAllOfMatcher< 559 Stmt, 560 UnaryOperator> unaryOperator; 561 562/// \brief Matches conditional operator expressions. 563/// 564/// Example matches a ? b : c 565/// (a ? b : c) + 42 566const internal::VariadicDynCastAllOfMatcher< 567 Stmt, 568 ConditionalOperator> conditionalOperator; 569 570/// \brief Matches a reinterpret_cast expression. 571/// 572/// Either the source expression or the destination type can be matched 573/// using has(), but hasDestinationType() is more specific and can be 574/// more readable. 575/// 576/// Example matches reinterpret_cast<char*>(&p) in 577/// void* p = reinterpret_cast<char*>(&p); 578const internal::VariadicDynCastAllOfMatcher< 579 Expr, 580 CXXReinterpretCastExpr> reinterpretCast; 581 582/// \brief Matches a C++ static_cast expression. 583/// 584/// \see hasDestinationType 585/// \see reinterpretCast 586/// 587/// Example: 588/// staticCast() 589/// matches 590/// static_cast<long>(8) 591/// in 592/// long eight(static_cast<long>(8)); 593const internal::VariadicDynCastAllOfMatcher< 594 Expr, 595 CXXStaticCastExpr> staticCast; 596 597/// \brief Matches a dynamic_cast expression. 598/// 599/// Example: 600/// dynamicCast() 601/// matches 602/// dynamic_cast<D*>(&b); 603/// in 604/// struct B { virtual ~B() {} }; struct D : B {}; 605/// B b; 606/// D* p = dynamic_cast<D*>(&b); 607const internal::VariadicDynCastAllOfMatcher< 608 Expr, 609 CXXDynamicCastExpr> dynamicCast; 610 611/// \brief Matches a const_cast expression. 612/// 613/// Example: Matches const_cast<int*>(&r) in 614/// int n = 42; 615/// const int& r(n); 616/// int* p = const_cast<int*>(&r); 617const internal::VariadicDynCastAllOfMatcher< 618 Expr, 619 CXXConstCastExpr> constCast; 620 621/// \brief Matches explicit cast expressions. 622/// 623/// Matches any cast expression written in user code, whether it be a 624/// C-style cast, a functional-style cast, or a keyword cast. 625/// 626/// Does not match implicit conversions. 627/// 628/// Note: the name "explicitCast" is chosen to match Clang's terminology, as 629/// Clang uses the term "cast" to apply to implicit conversions as well as to 630/// actual cast expressions. 631/// 632/// \see hasDestinationType. 633/// 634/// Example: matches all five of the casts in 635/// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42))))) 636/// but does not match the implicit conversion in 637/// long ell = 42; 638const internal::VariadicDynCastAllOfMatcher< 639 Expr, 640 ExplicitCastExpr> explicitCast; 641 642/// \brief Matches the implicit cast nodes of Clang's AST. 643/// 644/// This matches many different places, including function call return value 645/// eliding, as well as any type conversions. 646const internal::VariadicDynCastAllOfMatcher< 647 Expr, 648 ImplicitCastExpr> implicitCast; 649 650/// \brief Matches functional cast expressions 651/// 652/// Example: Matches Foo(bar); 653/// Foo f = bar; 654/// Foo g = (Foo) bar; 655/// Foo h = Foo(bar); 656const internal::VariadicDynCastAllOfMatcher< 657 Expr, 658 CXXFunctionalCastExpr> functionalCast; 659 660/// \brief Various overloads for the anyOf matcher. 661/// @{ 662template<typename C1, typename C2> 663internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1, C2> 664anyOf(const C1 &P1, const C2 &P2) { 665 return internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 666 C1, C2 >(P1, P2); 667} 668template<typename C1, typename C2, typename C3> 669internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1, 670 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2, C3> > 671anyOf(const C1 &P1, const C2 &P2, const C3 &P3) { 672 return anyOf(P1, anyOf(P2, P3)); 673} 674template<typename C1, typename C2, typename C3, typename C4> 675internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1, 676 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2, 677 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 678 C3, C4> > > 679anyOf(const C1 &P1, const C2 &P2, const C3 &P3, const C4 &P4) { 680 return AnyOf(P1, AnyOf(P2, AnyOf(P3, P4))); 681} 682template<typename C1, typename C2, typename C3, typename C4, typename C5> 683internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1, 684 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2, 685 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C3, 686 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 687 C4, C5> > > > 688anyOf(const C1& P1, const C2& P2, const C3& P3, const C4& P4, const C5& P5) { 689 return anyOf(P1, anyOf(P2, anyOf(P3, anyOf(P4, P5)))); 690} 691/// @} 692 693/// \brief Various overloads for the allOf matcher. 694/// @{ 695template<typename C1, typename C2> 696internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C1, C2> 697allOf(const C1 &P1, const C2 &P2) { 698 return internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, 699 C1, C2>(P1, P2); 700} 701template<typename C1, typename C2, typename C3> 702internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C1, 703 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C2, C3> > 704allOf(const C1& P1, const C2& P2, const C3& P3) { 705 return AllOf(P1, AllOf(P2, P3)); 706} 707/// @} 708 709/// \brief Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL) 710/// 711/// Given 712/// Foo x = bar; 713/// int y = sizeof(x) + alignof(x); 714/// unaryExprOrTypeTraitExpr() 715/// matches \c sizeof(x) and \c alignof(x) 716const internal::VariadicDynCastAllOfMatcher< 717 Stmt, 718 UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr; 719 720/// \brief Matches unary expressions that have a specific type of argument. 721/// 722/// Given 723/// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c); 724/// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int")) 725/// matches \c sizeof(a) and \c alignof(c) 726AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType, 727 internal::Matcher<QualType>, Matcher) { 728 const QualType ArgumentType = Node.getTypeOfArgument(); 729 return Matcher.matches(ArgumentType, Finder, Builder); 730} 731 732/// \brief Matches unary expressions of a certain kind. 733/// 734/// Given 735/// int x; 736/// int s = sizeof(x) + alignof(x) 737/// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf)) 738/// matches \c sizeof(x) 739AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) { 740 return Node.getKind() == Kind; 741} 742 743/// \brief Same as unaryExprOrTypeTraitExpr, but only matching 744/// alignof. 745inline internal::Matcher<Stmt> alignOfExpr( 746 const internal::Matcher<UnaryExprOrTypeTraitExpr> &Matcher) { 747 return internal::Matcher<Stmt>(unaryExprOrTypeTraitExpr(allOf( 748 ofKind(UETT_AlignOf), Matcher))); 749} 750 751/// \brief Same as unaryExprOrTypeTraitExpr, but only matching 752/// sizeof. 753inline internal::Matcher<Stmt> sizeOfExpr( 754 const internal::Matcher<UnaryExprOrTypeTraitExpr> &Matcher) { 755 return internal::Matcher<Stmt>(unaryExprOrTypeTraitExpr(allOf( 756 ofKind(UETT_SizeOf), Matcher))); 757} 758 759/// \brief Matches NamedDecl nodes that have the specified name. 760/// 761/// Supports specifying enclosing namespaces or classes by prefixing the name 762/// with '<enclosing>::'. 763/// Does not match typedefs of an underlying type with the given name. 764/// 765/// Example matches X (Name == "X") 766/// class X; 767/// 768/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X") 769/// namespace a { namespace b { class X; } } 770AST_MATCHER_P(NamedDecl, hasName, std::string, Name) { 771 assert(!Name.empty()); 772 const std::string FullNameString = "::" + Node.getQualifiedNameAsString(); 773 const llvm::StringRef FullName = FullNameString; 774 const llvm::StringRef Pattern = Name; 775 if (Pattern.startswith("::")) { 776 return FullName == Pattern; 777 } else { 778 return FullName.endswith(("::" + Pattern).str()); 779 } 780} 781 782/// \brief Matches NamedDecl nodes whose full names partially match the 783/// given RegExp. 784/// 785/// Supports specifying enclosing namespaces or classes by 786/// prefixing the name with '<enclosing>::'. Does not match typedefs 787/// of an underlying type with the given name. 788/// 789/// Example matches X (regexp == "::X") 790/// class X; 791/// 792/// Example matches X (regexp is one of "::X", "^foo::.*X", among others) 793/// namespace foo { namespace bar { class X; } } 794AST_MATCHER_P(NamedDecl, matchesName, std::string, RegExp) { 795 assert(!RegExp.empty()); 796 std::string FullNameString = "::" + Node.getQualifiedNameAsString(); 797 llvm::Regex RE(RegExp); 798 return RE.match(FullNameString); 799} 800 801/// \brief Matches overloaded operator names. 802/// 803/// Matches overloaded operator names specified in strings without the 804/// "operator" prefix, such as "<<", for OverloadedOperatorCall's. 805/// 806/// Example matches a << b 807/// (matcher == overloadedOperatorCall(hasOverloadedOperatorName("<<"))) 808/// a << b; 809/// c && d; // assuming both operator<< 810/// // and operator&& are overloaded somewhere. 811AST_MATCHER_P(CXXOperatorCallExpr, 812 hasOverloadedOperatorName, std::string, Name) { 813 return getOperatorSpelling(Node.getOperator()) == Name; 814} 815 816/// \brief Matches C++ classes that are directly or indirectly derived from 817/// the given base class. 818/// 819/// Note that a class is considered to be also derived from itself. 820/// The parameter specified the name of the base type (either a class or a 821/// typedef), and does not allow structural matches for namespaces or template 822/// type parameters. 823/// 824/// Example matches X, Y, Z, C (Base == "X") 825/// class X; // A class is considered to be derived from itself 826/// class Y : public X {}; // directly derived 827/// class Z : public Y {}; // indirectly derived 828/// typedef X A; 829/// typedef A B; 830/// class C : public B {}; // derived from a typedef of X 831/// 832/// In the following example, Bar matches isDerivedFrom("X"): 833/// class Foo; 834/// typedef Foo X; 835/// class Bar : public Foo {}; // derived from a type that X is a typedef of 836AST_MATCHER_P(CXXRecordDecl, isDerivedFrom, std::string, Base) { 837 assert(!Base.empty()); 838 return Finder->classIsDerivedFrom(&Node, Base); 839} 840 841/// \brief Matches AST nodes that have child AST nodes that match the 842/// provided matcher. 843/// 844/// Example matches X, Y (matcher = record(has(record(hasName("X"))) 845/// class X {}; // Matches X, because X::X is a class of name X inside X. 846/// class Y { class X {}; }; 847/// class Z { class Y { class X {}; }; }; // Does not match Z. 848/// 849/// ChildT must be an AST base type. 850template <typename ChildT> 851internal::ArgumentAdaptingMatcher<internal::HasMatcher, ChildT> has( 852 const internal::Matcher<ChildT> &ChildMatcher) { 853 return internal::ArgumentAdaptingMatcher<internal::HasMatcher, 854 ChildT>(ChildMatcher); 855} 856 857/// \brief Matches AST nodes that have descendant AST nodes that match the 858/// provided matcher. 859/// 860/// Example matches X, Y, Z 861/// (matcher = record(hasDescendant(record(hasName("X"))))) 862/// class X {}; // Matches X, because X::X is a class of name X inside X. 863/// class Y { class X {}; }; 864/// class Z { class Y { class X {}; }; }; 865/// 866/// DescendantT must be an AST base type. 867template <typename DescendantT> 868internal::ArgumentAdaptingMatcher<internal::HasDescendantMatcher, DescendantT> 869hasDescendant(const internal::Matcher<DescendantT> &DescendantMatcher) { 870 return internal::ArgumentAdaptingMatcher< 871 internal::HasDescendantMatcher, 872 DescendantT>(DescendantMatcher); 873} 874 875 876/// \brief Matches AST nodes that have child AST nodes that match the 877/// provided matcher. 878/// 879/// Example matches X, Y (matcher = record(forEach(record(hasName("X"))) 880/// class X {}; // Matches X, because X::X is a class of name X inside X. 881/// class Y { class X {}; }; 882/// class Z { class Y { class X {}; }; }; // Does not match Z. 883/// 884/// ChildT must be an AST base type. 885/// 886/// As opposed to 'has', 'forEach' will cause a match for each result that 887/// matches instead of only on the first one. 888template <typename ChildT> 889internal::ArgumentAdaptingMatcher<internal::ForEachMatcher, ChildT> forEach( 890 const internal::Matcher<ChildT>& ChildMatcher) { 891 return internal::ArgumentAdaptingMatcher< 892 internal::ForEachMatcher, 893 ChildT>(ChildMatcher); 894} 895 896/// \brief Matches AST nodes that have descendant AST nodes that match the 897/// provided matcher. 898/// 899/// Example matches X, A, B, C 900/// (matcher = record(forEachDescendant(record(hasName("X"))))) 901/// class X {}; // Matches X, because X::X is a class of name X inside X. 902/// class A { class X {}; }; 903/// class B { class C { class X {}; }; }; 904/// 905/// DescendantT must be an AST base type. 906/// 907/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for 908/// each result that matches instead of only on the first one. 909/// 910/// Note: Recursively combined ForEachDescendant can cause many matches: 911/// record(forEachDescendant(record(forEachDescendant(record())))) 912/// will match 10 times (plus injected class name matches) on: 913/// class A { class B { class C { class D { class E {}; }; }; }; }; 914template <typename DescendantT> 915internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, DescendantT> 916forEachDescendant( 917 const internal::Matcher<DescendantT>& DescendantMatcher) { 918 return internal::ArgumentAdaptingMatcher< 919 internal::ForEachDescendantMatcher, 920 DescendantT>(DescendantMatcher); 921} 922 923/// \brief Matches if the provided matcher does not match. 924/// 925/// Example matches Y (matcher = record(unless(hasName("X")))) 926/// class X {}; 927/// class Y {}; 928template <typename M> 929internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M> unless(const M &InnerMatcher) { 930 return internal::PolymorphicMatcherWithParam1< 931 internal::NotMatcher, M>(InnerMatcher); 932} 933 934/// \brief Matches a type if the declaration of the type matches the given 935/// matcher. 936inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher, 937 internal::Matcher<Decl> > 938 hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) { 939 return internal::PolymorphicMatcherWithParam1< 940 internal::HasDeclarationMatcher, 941 internal::Matcher<Decl> >(InnerMatcher); 942} 943 944/// \brief Matches on the implicit object argument of a member call expression. 945/// 946/// Example matches y.x() (matcher = call(on(hasType(record(hasName("Y")))))) 947/// class Y { public: void x(); }; 948/// void z() { Y y; y.x(); }", 949/// 950/// FIXME: Overload to allow directly matching types? 951AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>, 952 InnerMatcher) { 953 const Expr *ExprNode = const_cast<CXXMemberCallExpr&>(Node) 954 .getImplicitObjectArgument() 955 ->IgnoreParenImpCasts(); 956 return (ExprNode != NULL && 957 InnerMatcher.matches(*ExprNode, Finder, Builder)); 958} 959 960/// \brief Matches if the call expression's callee expression matches. 961/// 962/// Given 963/// class Y { void x() { this->x(); x(); Y y; y.x(); } }; 964/// void f() { f(); } 965/// call(callee(expression())) 966/// matches this->x(), x(), y.x(), f() 967/// with callee(...) 968/// matching this->x, x, y.x, f respectively 969/// 970/// Note: Callee cannot take the more general internal::Matcher<Expr> 971/// because this introduces ambiguous overloads with calls to Callee taking a 972/// internal::Matcher<Decl>, as the matcher hierarchy is purely 973/// implemented in terms of implicit casts. 974AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>, 975 InnerMatcher) { 976 const Expr *ExprNode = Node.getCallee(); 977 return (ExprNode != NULL && 978 InnerMatcher.matches(*ExprNode, Finder, Builder)); 979} 980 981/// \brief Matches if the call expression's callee's declaration matches the 982/// given matcher. 983/// 984/// Example matches y.x() (matcher = call(callee(method(hasName("x"))))) 985/// class Y { public: void x(); }; 986/// void z() { Y y; y.x(); 987inline internal::Matcher<CallExpr> callee( 988 const internal::Matcher<Decl> &InnerMatcher) { 989 return internal::Matcher<CallExpr>(hasDeclaration(InnerMatcher)); 990} 991 992/// \brief Matches if the expression's or declaration's type matches a type 993/// matcher. 994/// 995/// Example matches x (matcher = expression(hasType( 996/// hasDeclaration(record(hasName("X")))))) 997/// and z (matcher = variable(hasType( 998/// hasDeclaration(record(hasName("X")))))) 999/// class X {}; 1000/// void y(X &x) { x; X z; } 1001AST_POLYMORPHIC_MATCHER_P(hasType, internal::Matcher<QualType>, 1002 InnerMatcher) { 1003 TOOLING_COMPILE_ASSERT((llvm::is_base_of<Expr, NodeType>::value || 1004 llvm::is_base_of<ValueDecl, NodeType>::value), 1005 instantiated_with_wrong_types); 1006 return InnerMatcher.matches(Node.getType(), Finder, Builder); 1007} 1008 1009/// \brief Overloaded to match the declaration of the expression's or value 1010/// declaration's type. 1011/// 1012/// In case of a value declaration (for example a variable declaration), 1013/// this resolves one layer of indirection. For example, in the value 1014/// declaration "X x;", record(hasName("X")) matches the declaration of X, 1015/// while variable(hasType(record(hasName("X")))) matches the declaration 1016/// of x." 1017/// 1018/// Example matches x (matcher = expression(hasType(record(hasName("X"))))) 1019/// and z (matcher = variable(hasType(record(hasName("X"))))) 1020/// class X {}; 1021/// void y(X &x) { x; X z; } 1022inline internal::PolymorphicMatcherWithParam1< 1023 internal::matcher_hasTypeMatcher, 1024 internal::Matcher<QualType> > 1025hasType(const internal::Matcher<Decl> &InnerMatcher) { 1026 return hasType(internal::Matcher<QualType>( 1027 hasDeclaration(InnerMatcher))); 1028} 1029 1030/// \brief Matches if the matched type is represented by the given string. 1031/// 1032/// Given 1033/// class Y { public: void x(); }; 1034/// void z() { Y* y; y->x(); } 1035/// call(on(hasType(asString("class Y *")))) 1036/// matches y->x() 1037AST_MATCHER_P(QualType, asString, std::string, Name) { 1038 return Name == Node.getAsString(); 1039} 1040 1041/// \brief Matches if the matched type is a pointer type and the pointee type 1042/// matches the specified matcher. 1043/// 1044/// Example matches y->x() 1045/// (matcher = call(on(hasType(pointsTo(record(hasName("Y"))))))) 1046/// class Y { public: void x(); }; 1047/// void z() { Y *y; y->x(); } 1048AST_MATCHER_P( 1049 QualType, pointsTo, internal::Matcher<QualType>, 1050 InnerMatcher) { 1051 return (!Node.isNull() && Node->isPointerType() && 1052 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1053} 1054 1055/// \brief Overloaded to match the pointee type's declaration. 1056inline internal::Matcher<QualType> pointsTo( 1057 const internal::Matcher<Decl> &InnerMatcher) { 1058 return pointsTo(internal::Matcher<QualType>( 1059 hasDeclaration(InnerMatcher))); 1060} 1061 1062/// \brief Matches if the matched type is a reference type and the referenced 1063/// type matches the specified matcher. 1064/// 1065/// Example matches X &x and const X &y 1066/// (matcher = variable(hasType(references(record(hasName("X")))))) 1067/// class X { 1068/// void a(X b) { 1069/// X &x = b; 1070/// const X &y = b; 1071/// }; 1072AST_MATCHER_P(QualType, references, internal::Matcher<QualType>, 1073 InnerMatcher) { 1074 return (!Node.isNull() && Node->isReferenceType() && 1075 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 1076} 1077 1078/// \brief Overloaded to match the referenced type's declaration. 1079inline internal::Matcher<QualType> references( 1080 const internal::Matcher<Decl> &InnerMatcher) { 1081 return references(internal::Matcher<QualType>( 1082 hasDeclaration(InnerMatcher))); 1083} 1084 1085AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument, 1086 internal::Matcher<Expr>, InnerMatcher) { 1087 const Expr *ExprNode = 1088 const_cast<CXXMemberCallExpr&>(Node).getImplicitObjectArgument(); 1089 return (ExprNode != NULL && 1090 InnerMatcher.matches(*ExprNode, Finder, Builder)); 1091} 1092 1093/// \brief Matches if the expression's type either matches the specified 1094/// matcher, or is a pointer to a type that matches the InnerMatcher. 1095inline internal::Matcher<CallExpr> thisPointerType( 1096 const internal::Matcher<QualType> &InnerMatcher) { 1097 return onImplicitObjectArgument( 1098 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 1099} 1100 1101/// \brief Overloaded to match the type's declaration. 1102inline internal::Matcher<CallExpr> thisPointerType( 1103 const internal::Matcher<Decl> &InnerMatcher) { 1104 return onImplicitObjectArgument( 1105 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 1106} 1107 1108/// \brief Matches a DeclRefExpr that refers to a declaration that matches the 1109/// specified matcher. 1110/// 1111/// Example matches x in if(x) 1112/// (matcher = declarationReference(to(variable(hasName("x"))))) 1113/// bool x; 1114/// if (x) {} 1115AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>, 1116 InnerMatcher) { 1117 const Decl *DeclNode = Node.getDecl(); 1118 return (DeclNode != NULL && 1119 InnerMatcher.matches(*DeclNode, Finder, Builder)); 1120} 1121 1122/// \brief Matches a \c DeclRefExpr that refers to a declaration through a 1123/// specific using shadow declaration. 1124/// 1125/// FIXME: This currently only works for functions. Fix. 1126/// 1127/// Given 1128/// namespace a { void f() {} } 1129/// using a::f; 1130/// void g() { 1131/// f(); // Matches this .. 1132/// a::f(); // .. but not this. 1133/// } 1134/// declarationReference(throughUsingDeclaration(anything())) 1135/// matches \c f() 1136AST_MATCHER_P(DeclRefExpr, throughUsingDecl, 1137 internal::Matcher<UsingShadowDecl>, Matcher) { 1138 const NamedDecl *FoundDecl = Node.getFoundDecl(); 1139 if (const UsingShadowDecl *UsingDecl = 1140 llvm::dyn_cast<UsingShadowDecl>(FoundDecl)) 1141 return Matcher.matches(*UsingDecl, Finder, Builder); 1142 return false; 1143} 1144 1145/// \brief Matches a variable declaration that has an initializer expression 1146/// that matches the given matcher. 1147/// 1148/// Example matches x (matcher = variable(hasInitializer(call()))) 1149/// bool y() { return true; } 1150/// bool x = y(); 1151AST_MATCHER_P( 1152 VarDecl, hasInitializer, internal::Matcher<Expr>, 1153 InnerMatcher) { 1154 const Expr *Initializer = Node.getAnyInitializer(); 1155 return (Initializer != NULL && 1156 InnerMatcher.matches(*Initializer, Finder, Builder)); 1157} 1158 1159/// \brief Checks that a call expression or a constructor call expression has 1160/// a specific number of arguments (including absent default arguments). 1161/// 1162/// Example matches f(0, 0) (matcher = call(argumentCountIs(2))) 1163/// void f(int x, int y); 1164/// f(0, 0); 1165AST_POLYMORPHIC_MATCHER_P(argumentCountIs, unsigned, N) { 1166 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 1167 llvm::is_base_of<CXXConstructExpr, 1168 NodeType>::value), 1169 instantiated_with_wrong_types); 1170 return Node.getNumArgs() == N; 1171} 1172 1173/// \brief Matches the n'th argument of a call expression or a constructor 1174/// call expression. 1175/// 1176/// Example matches y in x(y) 1177/// (matcher = call(hasArgument(0, declarationReference()))) 1178/// void x(int) { int y; x(y); } 1179AST_POLYMORPHIC_MATCHER_P2( 1180 hasArgument, unsigned, N, internal::Matcher<Expr>, InnerMatcher) { 1181 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 1182 llvm::is_base_of<CXXConstructExpr, 1183 NodeType>::value), 1184 instantiated_with_wrong_types); 1185 return (N < Node.getNumArgs() && 1186 InnerMatcher.matches( 1187 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder)); 1188} 1189 1190/// \brief Matches a constructor initializer. 1191/// 1192/// Given 1193/// struct Foo { 1194/// Foo() : foo_(1) { } 1195/// int foo_; 1196/// }; 1197/// record(has(constructor(hasAnyConstructorInitializer(anything())))) 1198/// record matches Foo, hasAnyConstructorInitializer matches foo_(1) 1199AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer, 1200 internal::Matcher<CXXCtorInitializer>, InnerMatcher) { 1201 for (CXXConstructorDecl::init_const_iterator I = Node.init_begin(); 1202 I != Node.init_end(); ++I) { 1203 if (InnerMatcher.matches(**I, Finder, Builder)) { 1204 return true; 1205 } 1206 } 1207 return false; 1208} 1209 1210/// \brief Matches the field declaration of a constructor initializer. 1211/// 1212/// Given 1213/// struct Foo { 1214/// Foo() : foo_(1) { } 1215/// int foo_; 1216/// }; 1217/// record(has(constructor(hasAnyConstructorInitializer( 1218/// forField(hasName("foo_")))))) 1219/// matches Foo 1220/// with forField matching foo_ 1221AST_MATCHER_P(CXXCtorInitializer, forField, 1222 internal::Matcher<FieldDecl>, InnerMatcher) { 1223 const FieldDecl *NodeAsDecl = Node.getMember(); 1224 return (NodeAsDecl != NULL && 1225 InnerMatcher.matches(*NodeAsDecl, Finder, Builder)); 1226} 1227 1228/// \brief Matches the initializer expression of a constructor initializer. 1229/// 1230/// Given 1231/// struct Foo { 1232/// Foo() : foo_(1) { } 1233/// int foo_; 1234/// }; 1235/// record(has(constructor(hasAnyConstructorInitializer( 1236/// withInitializer(integerLiteral(equals(1))))))) 1237/// matches Foo 1238/// with withInitializer matching (1) 1239AST_MATCHER_P(CXXCtorInitializer, withInitializer, 1240 internal::Matcher<Expr>, InnerMatcher) { 1241 const Expr* NodeAsExpr = Node.getInit(); 1242 return (NodeAsExpr != NULL && 1243 InnerMatcher.matches(*NodeAsExpr, Finder, Builder)); 1244} 1245 1246/// \brief Matches a contructor initializer if it is explicitly written in 1247/// code (as opposed to implicitly added by the compiler). 1248/// 1249/// Given 1250/// struct Foo { 1251/// Foo() { } 1252/// Foo(int) : foo_("A") { } 1253/// string foo_; 1254/// }; 1255/// constructor(hasAnyConstructorInitializer(isWritten())) 1256/// will match Foo(int), but not Foo() 1257AST_MATCHER(CXXCtorInitializer, isWritten) { 1258 return Node.isWritten(); 1259} 1260 1261/// \brief Matches a constructor declaration that has been implicitly added 1262/// by the compiler (eg. implicit default/copy constructors). 1263AST_MATCHER(CXXConstructorDecl, isImplicit) { 1264 return Node.isImplicit(); 1265} 1266 1267/// \brief Matches any argument of a call expression or a constructor call 1268/// expression. 1269/// 1270/// Given 1271/// void x(int, int, int) { int y; x(1, y, 42); } 1272/// call(hasAnyArgument(declarationReference())) 1273/// matches x(1, y, 42) 1274/// with hasAnyArgument(...) 1275/// matching y 1276AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, internal::Matcher<Expr>, 1277 InnerMatcher) { 1278 TOOLING_COMPILE_ASSERT((llvm::is_base_of<CallExpr, NodeType>::value || 1279 llvm::is_base_of<CXXConstructExpr, 1280 NodeType>::value), 1281 instantiated_with_wrong_types); 1282 for (unsigned I = 0; I < Node.getNumArgs(); ++I) { 1283 if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(), 1284 Finder, Builder)) { 1285 return true; 1286 } 1287 } 1288 return false; 1289} 1290 1291/// \brief Matches the n'th parameter of a function declaration. 1292/// 1293/// Given 1294/// class X { void f(int x) {} }; 1295/// method(hasParameter(0, hasType(variable()))) 1296/// matches f(int x) {} 1297/// with hasParameter(...) 1298/// matching int x 1299AST_MATCHER_P2(FunctionDecl, hasParameter, 1300 unsigned, N, internal::Matcher<ParmVarDecl>, 1301 InnerMatcher) { 1302 return (N < Node.getNumParams() && 1303 InnerMatcher.matches( 1304 *Node.getParamDecl(N), Finder, Builder)); 1305} 1306 1307/// \brief Matches any parameter of a function declaration. 1308/// 1309/// Does not match the 'this' parameter of a method. 1310/// 1311/// Given 1312/// class X { void f(int x, int y, int z) {} }; 1313/// method(hasAnyParameter(hasName("y"))) 1314/// matches f(int x, int y, int z) {} 1315/// with hasAnyParameter(...) 1316/// matching int y 1317AST_MATCHER_P(FunctionDecl, hasAnyParameter, 1318 internal::Matcher<ParmVarDecl>, InnerMatcher) { 1319 for (unsigned I = 0; I < Node.getNumParams(); ++I) { 1320 if (InnerMatcher.matches(*Node.getParamDecl(I), Finder, Builder)) { 1321 return true; 1322 } 1323 } 1324 return false; 1325} 1326 1327/// \brief Matches the return type of a function declaration. 1328/// 1329/// Given: 1330/// class X { int f() { return 1; } }; 1331/// method(returns(asString("int"))) 1332/// matches int f() { return 1; } 1333AST_MATCHER_P(FunctionDecl, returns, internal::Matcher<QualType>, Matcher) { 1334 return Matcher.matches(Node.getResultType(), Finder, Builder); 1335} 1336 1337/// \brief Matches the condition expression of an if statement or conditional 1338/// operator. 1339/// 1340/// Example matches true (matcher = hasCondition(boolLiteral(equals(true)))) 1341/// if (true) {} 1342AST_POLYMORPHIC_MATCHER_P(hasCondition, internal::Matcher<Expr>, 1343 InnerMatcher) { 1344 TOOLING_COMPILE_ASSERT( 1345 (llvm::is_base_of<IfStmt, NodeType>::value) || 1346 (llvm::is_base_of<ConditionalOperator, NodeType>::value), 1347 has_condition_requires_if_statement_or_conditional_operator); 1348 const Expr *const Condition = Node.getCond(); 1349 return (Condition != NULL && 1350 InnerMatcher.matches(*Condition, Finder, Builder)); 1351} 1352 1353/// \brief Matches the condition variable statement in an if statement. 1354/// 1355/// Given 1356/// if (A* a = GetAPointer()) {} 1357/// hasConditionVariableStatment(...) 1358/// matches 'A* a = GetAPointer()'. 1359AST_MATCHER_P(IfStmt, hasConditionVariableStatement, 1360 internal::Matcher<DeclStmt>, InnerMatcher) { 1361 const DeclStmt* const DeclarationStatement = 1362 Node.getConditionVariableDeclStmt(); 1363 return DeclarationStatement != NULL && 1364 InnerMatcher.matches(*DeclarationStatement, Finder, Builder); 1365} 1366 1367/// \brief Matches the index expression of an array subscript expression. 1368/// 1369/// Given 1370/// int i[5]; 1371/// void f() { i[1] = 42; } 1372/// arraySubscriptExpression(hasIndex(integerLiteral())) 1373/// matches \c i[1] with the \c integerLiteral() matching \c 1 1374AST_MATCHER_P(ArraySubscriptExpr, hasIndex, 1375 internal::Matcher<Expr>, matcher) { 1376 if (const Expr* Expression = Node.getIdx()) 1377 return matcher.matches(*Expression, Finder, Builder); 1378 return false; 1379} 1380 1381/// \brief Matches the base expression of an array subscript expression. 1382/// 1383/// Given 1384/// int i[5]; 1385/// void f() { i[1] = 42; } 1386/// arraySubscriptExpression(hasBase(implicitCast( 1387/// hasSourceExpression(declarationReference())))) 1388/// matches \c i[1] with the \c declarationReference() matching \c i 1389AST_MATCHER_P(ArraySubscriptExpr, hasBase, 1390 internal::Matcher<Expr>, matcher) { 1391 if (const Expr* Expression = Node.getBase()) 1392 return matcher.matches(*Expression, Finder, Builder); 1393 return false; 1394} 1395 1396/// \brief Matches a 'for' statement that has a given body. 1397/// 1398/// Given 1399/// for (;;) {} 1400/// hasBody(compoundStatement()) 1401/// matches 'for (;;) {}' 1402/// with compoundStatement() 1403/// matching '{}' 1404AST_MATCHER_P(ForStmt, hasBody, internal::Matcher<Stmt>, 1405 InnerMatcher) { 1406 const Stmt *const Statement = Node.getBody(); 1407 return (Statement != NULL && 1408 InnerMatcher.matches(*Statement, Finder, Builder)); 1409} 1410 1411/// \brief Matches compound statements where at least one substatement matches 1412/// a given matcher. 1413/// 1414/// Given 1415/// { {}; 1+2; } 1416/// hasAnySubstatement(compoundStatement()) 1417/// matches '{ {}; 1+2; }' 1418/// with compoundStatement() 1419/// matching '{}' 1420AST_MATCHER_P(CompoundStmt, hasAnySubstatement, 1421 internal::Matcher<Stmt>, InnerMatcher) { 1422 for (CompoundStmt::const_body_iterator It = Node.body_begin(); 1423 It != Node.body_end(); 1424 ++It) { 1425 if (InnerMatcher.matches(**It, Finder, Builder)) return true; 1426 } 1427 return false; 1428} 1429 1430/// \brief Checks that a compound statement contains a specific number of 1431/// child statements. 1432/// 1433/// Example: Given 1434/// { for (;;) {} } 1435/// compoundStatement(statementCountIs(0))) 1436/// matches '{}' 1437/// but does not match the outer compound statement. 1438AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) { 1439 return Node.size() == N; 1440} 1441 1442/// \brief Matches literals that are equal to the given value. 1443/// 1444/// Example matches true (matcher = boolLiteral(equals(true))) 1445/// true 1446template <typename ValueT> 1447internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT> 1448equals(const ValueT &Value) { 1449 return internal::PolymorphicMatcherWithParam1< 1450 internal::ValueEqualsMatcher, 1451 ValueT>(Value); 1452} 1453 1454/// \brief Matches the operator Name of operator expressions (binary or 1455/// unary). 1456/// 1457/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||"))) 1458/// !(a || b) 1459AST_POLYMORPHIC_MATCHER_P(hasOperatorName, std::string, Name) { 1460 TOOLING_COMPILE_ASSERT( 1461 (llvm::is_base_of<BinaryOperator, NodeType>::value) || 1462 (llvm::is_base_of<UnaryOperator, NodeType>::value), 1463 has_condition_requires_if_statement_or_conditional_operator); 1464 return Name == Node.getOpcodeStr(Node.getOpcode()); 1465} 1466 1467/// \brief Matches the left hand side of binary operator expressions. 1468/// 1469/// Example matches a (matcher = binaryOperator(hasLHS())) 1470/// a || b 1471AST_MATCHER_P(BinaryOperator, hasLHS, 1472 internal::Matcher<Expr>, InnerMatcher) { 1473 Expr *LeftHandSide = Node.getLHS(); 1474 return (LeftHandSide != NULL && 1475 InnerMatcher.matches(*LeftHandSide, Finder, Builder)); 1476} 1477 1478/// \brief Matches the right hand side of binary operator expressions. 1479/// 1480/// Example matches b (matcher = binaryOperator(hasRHS())) 1481/// a || b 1482AST_MATCHER_P(BinaryOperator, hasRHS, 1483 internal::Matcher<Expr>, InnerMatcher) { 1484 Expr *RightHandSide = Node.getRHS(); 1485 return (RightHandSide != NULL && 1486 InnerMatcher.matches(*RightHandSide, Finder, Builder)); 1487} 1488 1489/// \brief Matches if either the left hand side or the right hand side of a 1490/// binary operator matches. 1491inline internal::Matcher<BinaryOperator> hasEitherOperand( 1492 const internal::Matcher<Expr> &InnerMatcher) { 1493 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)); 1494} 1495 1496/// \brief Matches if the operand of a unary operator matches. 1497/// 1498/// Example matches true (matcher = hasOperand(boolLiteral(equals(true)))) 1499/// !true 1500AST_MATCHER_P(UnaryOperator, hasUnaryOperand, 1501 internal::Matcher<Expr>, InnerMatcher) { 1502 const Expr * const Operand = Node.getSubExpr(); 1503 return (Operand != NULL && 1504 InnerMatcher.matches(*Operand, Finder, Builder)); 1505} 1506 1507/// \brief Matches if the implicit cast's source expression matches the given 1508/// matcher. 1509/// 1510/// Example: matches "a string" (matcher = 1511/// hasSourceExpression(constructorCall())) 1512/// 1513/// class URL { URL(string); }; 1514/// URL url = "a string"; 1515AST_MATCHER_P(ImplicitCastExpr, hasSourceExpression, 1516 internal::Matcher<Expr>, InnerMatcher) { 1517 const Expr* const SubExpression = Node.getSubExpr(); 1518 return (SubExpression != NULL && 1519 InnerMatcher.matches(*SubExpression, Finder, Builder)); 1520} 1521 1522/// \brief Matches casts whose destination type matches a given matcher. 1523/// 1524/// (Note: Clang's AST refers to other conversions as "casts" too, and calls 1525/// actual casts "explicit" casts.) 1526AST_MATCHER_P(ExplicitCastExpr, hasDestinationType, 1527 internal::Matcher<QualType>, InnerMatcher) { 1528 const QualType NodeType = Node.getTypeAsWritten(); 1529 return InnerMatcher.matches(NodeType, Finder, Builder); 1530} 1531 1532/// \brief Matches implicit casts whose destination type matches a given 1533/// matcher. 1534/// 1535/// FIXME: Unit test this matcher 1536AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType, 1537 internal::Matcher<QualType>, InnerMatcher) { 1538 return InnerMatcher.matches(Node.getType(), Finder, Builder); 1539} 1540 1541/// \brief Matches the true branch expression of a conditional operator. 1542/// 1543/// Example matches a 1544/// condition ? a : b 1545AST_MATCHER_P(ConditionalOperator, hasTrueExpression, 1546 internal::Matcher<Expr>, InnerMatcher) { 1547 Expr *Expression = Node.getTrueExpr(); 1548 return (Expression != NULL && 1549 InnerMatcher.matches(*Expression, Finder, Builder)); 1550} 1551 1552/// \brief Matches the false branch expression of a conditional operator. 1553/// 1554/// Example matches b 1555/// condition ? a : b 1556AST_MATCHER_P(ConditionalOperator, hasFalseExpression, 1557 internal::Matcher<Expr>, InnerMatcher) { 1558 Expr *Expression = Node.getFalseExpr(); 1559 return (Expression != NULL && 1560 InnerMatcher.matches(*Expression, Finder, Builder)); 1561} 1562 1563/// \brief Matches if a declaration has a body attached. 1564/// 1565/// Example matches A, va, fa 1566/// class A {}; 1567/// class B; // Doesn't match, as it has no body. 1568/// int va; 1569/// extern int vb; // Doesn't match, as it doesn't define the variable. 1570/// void fa() {} 1571/// void fb(); // Doesn't match, as it has no body. 1572inline internal::PolymorphicMatcherWithParam0<internal::IsDefinitionMatcher> 1573isDefinition() { 1574 return internal::PolymorphicMatcherWithParam0< 1575 internal::IsDefinitionMatcher>(); 1576} 1577 1578/// \brief Matches the class declaration that the given method declaration 1579/// belongs to. 1580/// 1581/// FIXME: Generalize this for other kinds of declarations. 1582/// FIXME: What other kind of declarations would we need to generalize 1583/// this to? 1584/// 1585/// Example matches A() in the last line 1586/// (matcher = constructorCall(hasDeclaration(method( 1587/// ofClass(hasName("A")))))) 1588/// class A { 1589/// public: 1590/// A(); 1591/// }; 1592/// A a = A(); 1593AST_MATCHER_P(CXXMethodDecl, ofClass, 1594 internal::Matcher<CXXRecordDecl>, InnerMatcher) { 1595 const CXXRecordDecl *Parent = Node.getParent(); 1596 return (Parent != NULL && 1597 InnerMatcher.matches(*Parent, Finder, Builder)); 1598} 1599 1600/// \brief Matches member expressions that are called with '->' as opposed 1601/// to '.'. 1602/// 1603/// Member calls on the implicit this pointer match as called with '->'. 1604/// 1605/// Given 1606/// class Y { 1607/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 1608/// int a; 1609/// static int b; 1610/// }; 1611/// memberExpression(isArrow()) 1612/// matches this->x, x, y.x, a, this->b 1613inline internal::Matcher<MemberExpr> isArrow() { 1614 return makeMatcher(new internal::IsArrowMatcher()); 1615} 1616 1617/// \brief Matches QualType nodes that are const-qualified, i.e., that 1618/// include "top-level" const. 1619/// 1620/// Given 1621/// void a(int); 1622/// void b(int const); 1623/// void c(const int); 1624/// void d(const int*); 1625/// void e(int const) {}; 1626/// function(hasAnyParameter(hasType(isConstQualified()))) 1627/// matches "void b(int const)", "void c(const int)" and 1628/// "void e(int const) {}". It does not match d as there 1629/// is no top-level const on the parameter type "const int *". 1630inline internal::Matcher<QualType> isConstQualified() { 1631 return makeMatcher(new internal::IsConstQualifiedMatcher()); 1632} 1633 1634/// \brief Matches a member expression where the member is matched by a 1635/// given matcher. 1636/// 1637/// Given 1638/// struct { int first, second; } first, second; 1639/// int i(second.first); 1640/// int j(first.second); 1641/// memberExpression(member(hasName("first"))) 1642/// matches second.first 1643/// but not first.second (because the member name there is "second"). 1644AST_MATCHER_P(MemberExpr, member, 1645 internal::Matcher<ValueDecl>, InnerMatcher) { 1646 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder); 1647} 1648 1649/// \brief Matches a member expression where the object expression is 1650/// matched by a given matcher. 1651/// 1652/// Given 1653/// struct X { int m; }; 1654/// void f(X x) { x.m; m; } 1655/// memberExpression(hasObjectExpression(hasType(record(hasName("X"))))))) 1656/// matches "x.m" and "m" 1657/// with hasObjectExpression(...) 1658/// matching "x" and the implicit object expression of "m" which has type X*. 1659AST_MATCHER_P(MemberExpr, hasObjectExpression, 1660 internal::Matcher<Expr>, InnerMatcher) { 1661 return InnerMatcher.matches(*Node.getBase(), Finder, Builder); 1662} 1663 1664/// \brief Matches any using shadow declaration. 1665/// 1666/// Given 1667/// namespace X { void b(); } 1668/// using X::b; 1669/// usingDecl(hasAnyUsingShadowDecl(hasName("b")))) 1670/// matches \code using X::b \endcode 1671AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl, 1672 internal::Matcher<UsingShadowDecl>, Matcher) { 1673 for (UsingDecl::shadow_iterator II = Node.shadow_begin(); 1674 II != Node.shadow_end(); ++II) { 1675 if (Matcher.matches(**II, Finder, Builder)) 1676 return true; 1677 } 1678 return false; 1679} 1680 1681/// \brief Matches a using shadow declaration where the target declaration is 1682/// matched by the given matcher. 1683/// 1684/// Given 1685/// namespace X { int a; void b(); } 1686/// using X::a; 1687/// using X::b; 1688/// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(function()))) 1689/// matches \code using X::b \endcode 1690/// but not \code using X::a \endcode 1691AST_MATCHER_P(UsingShadowDecl, hasTargetDecl, 1692 internal::Matcher<NamedDecl>, Matcher) { 1693 return Matcher.matches(*Node.getTargetDecl(), Finder, Builder); 1694} 1695 1696/// \brief Matches template instantiations of function, class, or static 1697/// member variable template instantiations. 1698/// 1699/// Given 1700/// template <typename T> class X {}; class A {}; X<A> x; 1701/// or 1702/// template <typename T> class X {}; class A {}; template class X<A>; 1703/// record(hasName("::X"), isTemplateInstantiation()) 1704/// matches the template instantiation of X<A>. 1705/// 1706/// But given 1707/// template <typename T> class X {}; class A {}; 1708/// template <> class X<A> {}; X<A> x; 1709/// record(hasName("::X"), isTemplateInstantiation()) 1710/// does not match, as X<A> is an explicit template specialization. 1711inline internal::PolymorphicMatcherWithParam0< 1712 internal::IsTemplateInstantiationMatcher> 1713isTemplateInstantiation() { 1714 return internal::PolymorphicMatcherWithParam0< 1715 internal::IsTemplateInstantiationMatcher>(); 1716} 1717 1718} // end namespace ast_matchers 1719} // end namespace clang 1720 1721#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H 1722