ASTMatchers.h revision 4da216637fa1ad4bdfd31bc265edb57ca35c2c12
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/ASTMatchers/ASTMatchersInternal.h" 49#include "clang/ASTMatchers/ASTMatchersMacros.h" 50#include "llvm/ADT/Twine.h" 51 52namespace clang { 53namespace ast_matchers { 54 55/// \brief Maps string IDs to AST nodes matched by parts of a matcher. 56/// 57/// The bound nodes are generated by adding id(...) matchers into the 58/// match expression around the matchers for the nodes we want to access later. 59/// 60/// The instances of BoundNodes are created by MatchFinder when the user's 61/// callbacks are executed every time a match is found. 62class BoundNodes { 63public: 64 /// \brief Returns the AST node bound to 'ID'. 65 /// Returns NULL if there was no node bound to 'ID' or if there is a node but 66 /// it cannot be converted to the specified type. 67 /// FIXME: We'll need one of those for every base type. 68 /// @{ 69 template <typename T> 70 const T *getDeclAs(StringRef ID) const { 71 return getNodeAs<T>(DeclBindings, ID); 72 } 73 template <typename T> 74 const T *getStmtAs(StringRef ID) const { 75 return getNodeAs<T>(StmtBindings, ID); 76 } 77 /// @} 78 79private: 80 /// \brief Create BoundNodes from a pre-filled map of bindings. 81 BoundNodes(const std::map<std::string, const clang::Decl*> &DeclBindings, 82 const std::map<std::string, const clang::Stmt*> &StmtBindings) 83 : DeclBindings(DeclBindings), StmtBindings(StmtBindings) {} 84 85 template <typename T, typename MapT> 86 const T *getNodeAs(const MapT &Bindings, StringRef ID) const { 87 typename MapT::const_iterator It = Bindings.find(ID); 88 if (It == Bindings.end()) { 89 return NULL; 90 } 91 return llvm::dyn_cast<T>(It->second); 92 } 93 94 std::map<std::string, const clang::Decl*> DeclBindings; 95 std::map<std::string, const clang::Stmt*> StmtBindings; 96 97 friend class internal::BoundNodesTree; 98}; 99 100/// \brief If the provided matcher matches a node, binds the node to 'ID'. 101/// 102/// FIXME: Add example for accessing it. 103template <typename T> 104internal::Matcher<T> id(const std::string &ID, 105 const internal::Matcher<T> &InnerMatcher) { 106 return internal::Matcher<T>(new internal::IdMatcher<T>(ID, InnerMatcher)); 107} 108 109/// \brief Types of matchers for the top-level classes in the AST class 110/// hierarchy. 111/// @{ 112typedef internal::Matcher<clang::Decl> DeclarationMatcher; 113typedef internal::Matcher<clang::QualType> TypeMatcher; 114typedef internal::Matcher<clang::Stmt> StatementMatcher; 115/// @} 116 117/// \brief Matches any node. 118/// 119/// Useful when another matcher requires a child matcher, but there's no 120/// additional constraint. This will often be used with an explicit conversion 121/// to a internal::Matcher<> type such as TypeMatcher. 122/// 123/// Example: DeclarationMatcher(anything()) matches all declarations, e.g., 124/// "int* p" and "void f()" in 125/// int* p; 126/// void f(); 127inline internal::PolymorphicMatcherWithParam0<internal::TrueMatcher> anything() { 128 return internal::PolymorphicMatcherWithParam0<internal::TrueMatcher>(); 129} 130 131/// \brief Matches a declaration of anything that could have a name. 132/// 133/// Example matches X, S, the anonymous union type, i, and U; 134/// typedef int X; 135/// struct S { 136/// union { 137/// int i; 138/// } U; 139/// }; 140const internal::VariadicDynCastAllOfMatcher< 141 clang::Decl, 142 clang::NamedDecl> nameableDeclaration; 143 144/// \brief Matches C++ class declarations. 145/// 146/// Example matches X, Z 147/// class X; 148/// template<class T> class Z {}; 149const internal::VariadicDynCastAllOfMatcher< 150 clang::Decl, 151 clang::CXXRecordDecl> record; 152 153/// \brief Matches C++ constructor declarations. 154/// 155/// Example matches Foo::Foo() and Foo::Foo(int) 156/// class Foo { 157/// public: 158/// Foo(); 159/// Foo(int); 160/// int DoSomething(); 161/// }; 162const internal::VariadicDynCastAllOfMatcher< 163 clang::Decl, 164 clang::CXXConstructorDecl> constructor; 165 166/// \brief Matches method declarations. 167/// 168/// Example matches y 169/// class X { void y() }; 170const internal::VariadicDynCastAllOfMatcher< 171 clang::Decl, 172 clang::CXXMethodDecl> method; 173 174/// \brief Matches variable declarations. 175/// 176/// Note: this does not match declarations of member variables, which are 177/// "field" declarations in Clang parlance. 178/// 179/// Example matches a 180/// int a; 181const internal::VariadicDynCastAllOfMatcher< 182 clang::Decl, 183 clang::VarDecl> variable; 184 185/// \brief Matches field declarations. 186/// 187/// Given 188/// class X { int m; }; 189/// field() 190/// matches 'm'. 191const internal::VariadicDynCastAllOfMatcher< 192 clang::Decl, 193 clang::FieldDecl> field; 194 195/// \brief Matches function declarations. 196/// 197/// Example matches f 198/// void f(); 199const internal::VariadicDynCastAllOfMatcher< 200 clang::Decl, 201 clang::FunctionDecl> function; 202 203 204/// \brief Matches statements. 205/// 206/// Given 207/// { ++a; } 208/// statement() 209/// matches both the compound statement '{ ++a; }' and '++a'. 210const internal::VariadicDynCastAllOfMatcher<clang::Stmt, clang::Stmt> statement; 211 212/// \brief Matches declaration statements. 213/// 214/// Given 215/// int a; 216/// declarationStatement() 217/// matches 'int a'. 218const internal::VariadicDynCastAllOfMatcher< 219 clang::Stmt, 220 clang::DeclStmt> declarationStatement; 221 222/// \brief Matches member expressions. 223/// 224/// Given 225/// class Y { 226/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 227/// int a; static int b; 228/// }; 229/// memberExpression() 230/// matches this->x, x, y.x, a, this->b 231const internal::VariadicDynCastAllOfMatcher< 232 clang::Stmt, 233 clang::MemberExpr> memberExpression; 234 235/// \brief Matches call expressions. 236/// 237/// Example matches x.y() 238/// X x; 239/// x.y(); 240const internal::VariadicDynCastAllOfMatcher<clang::Stmt, clang::CallExpr> call; 241 242/// \brief Matches constructor call expressions (including implicit ones). 243/// 244/// Example matches string(ptr, n) and ptr within arguments of f 245/// (matcher = constructorCall()) 246/// void f(const string &a, const string &b); 247/// char *ptr; 248/// int n; 249/// f(string(ptr, n), ptr); 250const internal::VariadicDynCastAllOfMatcher< 251 clang::Stmt, 252 clang::CXXConstructExpr> constructorCall; 253 254/// \brief Matches nodes where temporaries are created. 255/// 256/// Example matches FunctionTakesString(GetStringByValue()) 257/// (matcher = bindTemporaryExpr()) 258/// FunctionTakesString(GetStringByValue()); 259/// FunctionTakesStringByPointer(GetStringPointer()); 260const internal::VariadicDynCastAllOfMatcher< 261 clang::Stmt, 262 clang::CXXBindTemporaryExpr> bindTemporaryExpression; 263 264/// \brief Matches new expressions. 265/// 266/// Given 267/// new X; 268/// newExpression() 269/// matches 'new X'. 270const internal::VariadicDynCastAllOfMatcher< 271 clang::Stmt, 272 clang::CXXNewExpr> newExpression; 273 274/// \brief Matches the value of a default argument at the call site. 275/// 276/// Example matches the CXXDefaultArgExpr placeholder inserted for the 277/// default value of the second parameter in the call expression f(42) 278/// (matcher = defaultArgument()) 279/// void f(int x, int y = 0); 280/// f(42); 281const internal::VariadicDynCastAllOfMatcher< 282 clang::Stmt, 283 clang::CXXDefaultArgExpr> defaultArgument; 284 285/// \brief Matches overloaded operator calls. 286/// 287/// Note that if an operator isn't overloaded, it won't match. Instead, use 288/// binaryOperator matcher. 289/// Currently it does not match operators such as new delete. 290/// FIXME: figure out why these do not match? 291/// 292/// Example matches both operator<<((o << b), c) and operator<<(o, b) 293/// (matcher = overloadedOperatorCall()) 294/// ostream &operator<< (ostream &out, int i) { }; 295/// ostream &o; int b = 1, c = 1; 296/// o << b << c; 297const internal::VariadicDynCastAllOfMatcher< 298 clang::Stmt, 299 clang::CXXOperatorCallExpr> overloadedOperatorCall; 300 301/// \brief Matches expressions. 302/// 303/// Example matches x() 304/// void f() { x(); } 305const internal::VariadicDynCastAllOfMatcher< 306 clang::Stmt, 307 clang::Expr> expression; 308 309/// \brief Matches expressions that refer to declarations. 310/// 311/// Example matches x in if (x) 312/// bool x; 313/// if (x) {} 314const internal::VariadicDynCastAllOfMatcher< 315 clang::Stmt, 316 clang::DeclRefExpr> declarationReference; 317 318/// \brief Matches if statements. 319/// 320/// Example matches 'if (x) {}' 321/// if (x) {} 322const internal::VariadicDynCastAllOfMatcher<clang::Stmt, clang::IfStmt> ifStmt; 323 324/// \brief Matches for statements. 325/// 326/// Example matches 'for (;;) {}' 327/// for (;;) {} 328const internal::VariadicDynCastAllOfMatcher< 329 clang::Stmt, clang::ForStmt> forStmt; 330 331/// \brief Matches while statements. 332/// 333/// Given 334/// while (true) {} 335/// whileStmt() 336/// matches 'while (true) {}'. 337const internal::VariadicDynCastAllOfMatcher< 338 clang::Stmt, 339 clang::WhileStmt> whileStmt; 340 341/// \brief Matches do statements. 342/// 343/// Given 344/// do {} while (true); 345/// doStmt() 346/// matches 'do {} while(true)' 347const internal::VariadicDynCastAllOfMatcher<clang::Stmt, clang::DoStmt> doStmt; 348 349/// \brief Matches case and default statements inside switch statements. 350/// 351/// Given 352/// switch(a) { case 42: break; default: break; } 353/// switchCase() 354/// matches 'case 42: break;' and 'default: break;'. 355const internal::VariadicDynCastAllOfMatcher< 356 clang::Stmt, 357 clang::SwitchCase> switchCase; 358 359/// \brief Matches compound statements. 360/// 361/// Example matches '{}' and '{{}}'in 'for (;;) {{}}' 362/// for (;;) {{}} 363const internal::VariadicDynCastAllOfMatcher< 364 clang::Stmt, 365 clang::CompoundStmt> compoundStatement; 366 367/// \brief Matches bool literals. 368/// 369/// Example matches true 370/// true 371const internal::VariadicDynCastAllOfMatcher< 372 clang::Expr, 373 clang::CXXBoolLiteralExpr> boolLiteral; 374 375/// \brief Matches string literals (also matches wide string literals). 376/// 377/// Example matches "abcd", L"abcd" 378/// char *s = "abcd"; wchar_t *ws = L"abcd" 379const internal::VariadicDynCastAllOfMatcher< 380 clang::Expr, 381 clang::StringLiteral> stringLiteral; 382 383/// \brief Matches character literals (also matches wchar_t). 384/// 385/// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral), 386/// though. 387/// 388/// Example matches 'a', L'a' 389/// char ch = 'a'; wchar_t chw = L'a'; 390const internal::VariadicDynCastAllOfMatcher< 391 clang::Expr, 392 clang::CharacterLiteral> characterLiteral; 393 394/// \brief Matches integer literals of all sizes / encodings. 395/// 396/// Not matching character-encoded integers such as L'a'. 397/// 398/// Example matches 1, 1L, 0x1, 1U 399const internal::VariadicDynCastAllOfMatcher< 400 clang::Expr, 401 clang::IntegerLiteral> integerLiteral; 402 403/// \brief Matches binary operator expressions. 404/// 405/// Example matches a || b 406/// !(a || b) 407const internal::VariadicDynCastAllOfMatcher< 408 clang::Stmt, 409 clang::BinaryOperator> binaryOperator; 410 411/// \brief Matches unary operator expressions. 412/// 413/// Example matches !a 414/// !a || b 415const internal::VariadicDynCastAllOfMatcher< 416 clang::Stmt, 417 clang::UnaryOperator> unaryOperator; 418 419/// \brief Matches conditional operator expressions. 420/// 421/// Example matches a ? b : c 422/// (a ? b : c) + 42 423const internal::VariadicDynCastAllOfMatcher< 424 clang::Stmt, 425 clang::ConditionalOperator> conditionalOperator; 426 427/// \brief Matches a reinterpret_cast expression. 428/// 429/// Either the source expression or the destination type can be matched 430/// using has(), but hasDestinationType() is more specific and can be 431/// more readable. 432/// 433/// Example matches reinterpret_cast<char*>(&p) in 434/// void* p = reinterpret_cast<char*>(&p); 435const internal::VariadicDynCastAllOfMatcher< 436 clang::Expr, 437 clang::CXXReinterpretCastExpr> reinterpretCast; 438 439/// \brief Matches a C++ static_cast expression. 440/// 441/// \see hasDestinationType 442/// \see reinterpretCast 443/// 444/// Example: 445/// staticCast() 446/// matches 447/// static_cast<long>(8) 448/// in 449/// long eight(static_cast<long>(8)); 450const internal::VariadicDynCastAllOfMatcher< 451 clang::Expr, 452 clang::CXXStaticCastExpr> staticCast; 453 454/// \brief Matches a dynamic_cast expression. 455/// 456/// Example: 457/// dynamicCast() 458/// matches 459/// dynamic_cast<D*>(&b); 460/// in 461/// struct B { virtual ~B() {} }; struct D : B {}; 462/// B b; 463/// D* p = dynamic_cast<D*>(&b); 464const internal::VariadicDynCastAllOfMatcher< 465 clang::Expr, 466 clang::CXXDynamicCastExpr> dynamicCast; 467 468/// \brief Matches a const_cast expression. 469/// 470/// Example: Matches const_cast<int*>(&r) in 471/// int n = 42; 472/// const int& r(n); 473/// int* p = const_cast<int*>(&r); 474const internal::VariadicDynCastAllOfMatcher< 475 clang::Expr, 476 clang::CXXConstCastExpr> constCast; 477 478/// \brief Matches explicit cast expressions. 479/// 480/// Matches any cast expression written in user code, whether it be a 481/// C-style cast, a functional-style cast, or a keyword cast. 482/// 483/// Does not match implicit conversions. 484/// 485/// Note: the name "explicitCast" is chosen to match Clang's terminology, as 486/// Clang uses the term "cast" to apply to implicit conversions as well as to 487/// actual cast expressions. 488/// 489/// \see hasDestinationType. 490/// 491/// Example: matches all five of the casts in 492/// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42))))) 493/// but does not match the implicit conversion in 494/// long ell = 42; 495const internal::VariadicDynCastAllOfMatcher< 496 clang::Expr, 497 clang::ExplicitCastExpr> explicitCast; 498 499/// \brief Matches the implicit cast nodes of Clang's AST. 500/// 501/// This matches many different places, including function call return value 502/// eliding, as well as any type conversions. 503const internal::VariadicDynCastAllOfMatcher< 504 clang::Expr, 505 clang::ImplicitCastExpr> implicitCast; 506 507/// \brief Matches functional cast expressions 508/// 509/// Example: Matches Foo(bar); 510/// Foo f = bar; 511/// Foo g = (Foo) bar; 512/// Foo h = Foo(bar); 513const internal::VariadicDynCastAllOfMatcher< 514 clang::Expr, 515 clang::CXXFunctionalCastExpr> functionalCast; 516 517/// \brief Various overloads for the anyOf matcher. 518/// @{ 519template<typename C1, typename C2> 520internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1, C2> 521anyOf(const C1 &P1, const C2 &P2) { 522 return internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 523 C1, C2 >(P1, P2); 524} 525template<typename C1, typename C2, typename C3> 526internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1, 527 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2, C3> > 528anyOf(const C1 &P1, const C2 &P2, const C3 &P3) { 529 return anyOf(P1, anyOf(P2, P3)); 530} 531template<typename C1, typename C2, typename C3, typename C4> 532internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1, 533 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2, 534 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 535 C3, C4> > > 536anyOf(const C1 &P1, const C2 &P2, const C3 &P3, const C4 &P4) { 537 return AnyOf(P1, AnyOf(P2, AnyOf(P3, P4))); 538} 539template<typename C1, typename C2, typename C3, typename C4, typename C5> 540internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C1, 541 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C2, 542 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, C3, 543 internal::PolymorphicMatcherWithParam2<internal::AnyOfMatcher, 544 C4, C5> > > > 545anyOf(const C1& P1, const C2& P2, const C3& P3, const C4& P4, const C5& P5) { 546 return anyOf(P1, anyOf(P2, anyOf(P3, anyOf(P4, P5)))); 547} 548/// @} 549 550/// \brief Various overloads for the allOf matcher. 551/// @{ 552template<typename C1, typename C2> 553internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C1, C2> 554allOf(const C1 &P1, const C2 &P2) { 555 return internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, 556 C1, C2>(P1, P2); 557} 558template<typename C1, typename C2, typename C3> 559internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C1, 560 internal::PolymorphicMatcherWithParam2<internal::AllOfMatcher, C2, C3> > 561allOf(const C1& P1, const C2& P2, const C3& P3) { 562 return AllOf(P1, AllOf(P2, P3)); 563} 564/// @} 565 566/// \brief Matches NamedDecl nodes that have the specified name. 567/// 568/// Supports specifying enclosing namespaces or classes by prefixing the name 569/// with '<enclosing>::'. 570/// Does not match typedefs of an underlying type with the given name. 571/// 572/// Example matches X (Name == "X") 573/// class X; 574/// 575/// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X") 576/// namespace a { namespace b { class X; } } 577AST_MATCHER_P(clang::NamedDecl, hasName, std::string, Name) { 578 assert(!Name.empty()); 579 const std::string FullNameString = "::" + Node.getQualifiedNameAsString(); 580 const llvm::StringRef FullName = FullNameString; 581 const llvm::StringRef Pattern = Name; 582 if (Pattern.startswith("::")) { 583 return FullName == Pattern; 584 } else { 585 return FullName.endswith(("::" + Pattern).str()); 586 } 587} 588 589/// \brief Matches overloaded operator names. 590/// 591/// Matches overloaded operator names specified in strings without the 592/// "operator" prefix, such as "<<", for OverloadedOperatorCall's. 593/// 594/// Example matches a << b 595/// (matcher == overloadedOperatorCall(hasOverloadedOperatorName("<<"))) 596/// a << b; 597/// c && d; // assuming both operator<< 598/// // and operator&& are overloaded somewhere. 599AST_MATCHER_P(clang::CXXOperatorCallExpr, 600 hasOverloadedOperatorName, std::string, Name) { 601 return clang::getOperatorSpelling(Node.getOperator()) == Name; 602} 603 604/// \brief Matches C++ classes that are directly or indirectly derived from 605/// the given base class. 606/// 607/// Note that a class is considered to be also derived from itself. 608/// The parameter specified the name of the base type (either a class or a 609/// typedef), and does not allow structural matches for namespaces or template 610/// type parameters. 611/// 612/// Example matches X, Y, Z, C (Base == "X") 613/// class X; // A class is considered to be derived from itself 614/// class Y : public X {}; // directly derived 615/// class Z : public Y {}; // indirectly derived 616/// typedef X A; 617/// typedef A B; 618/// class C : public B {}; // derived from a typedef of X 619/// 620/// In the following example, Bar matches isDerivedFrom("X"): 621/// class Foo; 622/// typedef Foo X; 623/// class Bar : public Foo {}; // derived from a type that X is a typedef of 624AST_MATCHER_P(clang::CXXRecordDecl, isDerivedFrom, std::string, Base) { 625 assert(!Base.empty()); 626 return Finder->classIsDerivedFrom(&Node, Base); 627} 628 629/// \brief Matches AST nodes that have child AST nodes that match the 630/// provided matcher. 631/// 632/// Example matches X, Y (matcher = record(has(record(hasName("X"))) 633/// class X {}; // Matches X, because X::X is a class of name X inside X. 634/// class Y { class X {}; }; 635/// class Z { class Y { class X {}; }; }; // Does not match Z. 636/// 637/// ChildT must be an AST base type. 638template <typename ChildT> 639internal::ArgumentAdaptingMatcher<internal::HasMatcher, ChildT> has( 640 const internal::Matcher<ChildT> &ChildMatcher) { 641 return internal::ArgumentAdaptingMatcher<internal::HasMatcher, 642 ChildT>(ChildMatcher); 643} 644 645/// \brief Matches AST nodes that have descendant AST nodes that match the 646/// provided matcher. 647/// 648/// Example matches X, Y, Z 649/// (matcher = record(hasDescendant(record(hasName("X"))))) 650/// class X {}; // Matches X, because X::X is a class of name X inside X. 651/// class Y { class X {}; }; 652/// class Z { class Y { class X {}; }; }; 653/// 654/// DescendantT must be an AST base type. 655template <typename DescendantT> 656internal::ArgumentAdaptingMatcher<internal::HasDescendantMatcher, DescendantT> 657hasDescendant(const internal::Matcher<DescendantT> &DescendantMatcher) { 658 return internal::ArgumentAdaptingMatcher< 659 internal::HasDescendantMatcher, 660 DescendantT>(DescendantMatcher); 661} 662 663 664/// \brief Matches AST nodes that have child AST nodes that match the 665/// provided matcher. 666/// 667/// Example matches X, Y (matcher = record(forEach(record(hasName("X"))) 668/// class X {}; // Matches X, because X::X is a class of name X inside X. 669/// class Y { class X {}; }; 670/// class Z { class Y { class X {}; }; }; // Does not match Z. 671/// 672/// ChildT must be an AST base type. 673/// 674/// As opposed to 'has', 'forEach' will cause a match for each result that 675/// matches instead of only on the first one. 676template <typename ChildT> 677internal::ArgumentAdaptingMatcher<internal::ForEachMatcher, ChildT> forEach( 678 const internal::Matcher<ChildT>& ChildMatcher) { 679 return internal::ArgumentAdaptingMatcher< 680 internal::ForEachMatcher, 681 ChildT>(ChildMatcher); 682} 683 684/// \brief Matches AST nodes that have descendant AST nodes that match the 685/// provided matcher. 686/// 687/// Example matches X, A, B, C 688/// (matcher = record(forEachDescendant(record(hasName("X"))))) 689/// class X {}; // Matches X, because X::X is a class of name X inside X. 690/// class A { class X {}; }; 691/// class B { class C { class X {}; }; }; 692/// 693/// DescendantT must be an AST base type. 694/// 695/// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for 696/// each result that matches instead of only on the first one. 697/// 698/// Note: Recursively combined ForEachDescendant can cause many matches: 699/// record(forEachDescendant(record(forEachDescendant(record())))) 700/// will match 10 times (plus injected class name matches) on: 701/// class A { class B { class C { class D { class E {}; }; }; }; }; 702template <typename DescendantT> 703internal::ArgumentAdaptingMatcher<internal::ForEachDescendantMatcher, DescendantT> 704forEachDescendant( 705 const internal::Matcher<DescendantT>& DescendantMatcher) { 706 return internal::ArgumentAdaptingMatcher< 707 internal::ForEachDescendantMatcher, 708 DescendantT>(DescendantMatcher); 709} 710 711/// \brief Matches if the provided matcher does not match. 712/// 713/// Example matches Y (matcher = record(unless(hasName("X")))) 714/// class X {}; 715/// class Y {}; 716template <typename M> 717internal::PolymorphicMatcherWithParam1<internal::NotMatcher, M> unless(const M &InnerMatcher) { 718 return internal::PolymorphicMatcherWithParam1< 719 internal::NotMatcher, M>(InnerMatcher); 720} 721 722/// \brief Matches a type if the declaration of the type matches the given 723/// matcher. 724inline internal::PolymorphicMatcherWithParam1< internal::HasDeclarationMatcher, 725 internal::Matcher<clang::Decl> > 726 hasDeclaration(const internal::Matcher<clang::Decl> &InnerMatcher) { 727 return internal::PolymorphicMatcherWithParam1< 728 internal::HasDeclarationMatcher, 729 internal::Matcher<clang::Decl> >(InnerMatcher); 730} 731 732/// \brief Matches on the implicit object argument of a member call expression. 733/// 734/// Example matches y.x() (matcher = call(on(hasType(record(hasName("Y")))))) 735/// class Y { public: void x(); }; 736/// void z() { Y y; y.x(); }", 737/// 738/// FIXME: Overload to allow directly matching types? 739AST_MATCHER_P(clang::CXXMemberCallExpr, on, internal::Matcher<clang::Expr>, 740 InnerMatcher) { 741 const clang::Expr *ExprNode = const_cast<clang::CXXMemberCallExpr&>(Node) 742 .getImplicitObjectArgument() 743 ->IgnoreParenImpCasts(); 744 return (ExprNode != NULL && 745 InnerMatcher.matches(*ExprNode, Finder, Builder)); 746} 747 748/// \brief Matches if the call expression's callee expression matches. 749/// 750/// Given 751/// class Y { void x() { this->x(); x(); Y y; y.x(); } }; 752/// void f() { f(); } 753/// call(callee(expression())) 754/// matches this->x(), x(), y.x(), f() 755/// with callee(...) 756/// matching this->x, x, y.x, f respectively 757/// 758/// Note: Callee cannot take the more general internal::Matcher<clang::Expr> 759/// because this introduces ambiguous overloads with calls to Callee taking a 760/// internal::Matcher<clang::Decl>, as the matcher hierarchy is purely 761/// implemented in terms of implicit casts. 762AST_MATCHER_P(clang::CallExpr, callee, internal::Matcher<clang::Stmt>, 763 InnerMatcher) { 764 const clang::Expr *ExprNode = Node.getCallee(); 765 return (ExprNode != NULL && 766 InnerMatcher.matches(*ExprNode, Finder, Builder)); 767} 768 769/// \brief Matches if the call expression's callee's declaration matches the 770/// given matcher. 771/// 772/// Example matches y.x() (matcher = call(callee(method(hasName("x"))))) 773/// class Y { public: void x(); }; 774/// void z() { Y y; y.x(); 775inline internal::Matcher<clang::CallExpr> callee( 776 const internal::Matcher<clang::Decl> &InnerMatcher) { 777 return internal::Matcher<clang::CallExpr>(hasDeclaration(InnerMatcher)); 778} 779 780/// \brief Matches if the expression's or declaration's type matches a type 781/// matcher. 782/// 783/// Example matches x (matcher = expression(hasType( 784/// hasDeclaration(record(hasName("X")))))) 785/// and z (matcher = variable(hasType( 786/// hasDeclaration(record(hasName("X")))))) 787/// class X {}; 788/// void y(X &x) { x; X z; } 789AST_POLYMORPHIC_MATCHER_P(hasType, internal::Matcher<clang::QualType>, 790 InnerMatcher) { 791 TOOLING_COMPILE_ASSERT((llvm::is_base_of<clang::Expr, NodeType>::value || 792 llvm::is_base_of<clang::ValueDecl, NodeType>::value), 793 instantiated_with_wrong_types); 794 return InnerMatcher.matches(Node.getType(), Finder, Builder); 795} 796 797/// \brief Overloaded to match the declaration of the expression's or value 798/// declaration's type. 799/// 800/// In case of a value declaration (for example a variable declaration), 801/// this resolves one layer of indirection. For example, in the value 802/// declaration "X x;", record(hasName("X")) matches the declaration of X, 803/// while variable(hasType(record(hasName("X")))) matches the declaration 804/// of x." 805/// 806/// Example matches x (matcher = expression(hasType(record(hasName("X"))))) 807/// and z (matcher = variable(hasType(record(hasName("X"))))) 808/// class X {}; 809/// void y(X &x) { x; X z; } 810inline internal::PolymorphicMatcherWithParam1< 811 internal::matcher_hasTypeMatcher, 812 internal::Matcher<clang::QualType> > 813hasType(const internal::Matcher<clang::Decl> &InnerMatcher) { 814 return hasType(internal::Matcher<clang::QualType>( 815 hasDeclaration(InnerMatcher))); 816} 817 818/// \brief Matches if the matched type is a pointer type and the pointee type 819/// matches the specified matcher. 820/// 821/// Example matches y->x() 822/// (matcher = call(on(hasType(pointsTo(record(hasName("Y"))))))) 823/// class Y { public: void x(); }; 824/// void z() { Y *y; y->x(); } 825AST_MATCHER_P( 826 clang::QualType, pointsTo, internal::Matcher<clang::QualType>, 827 InnerMatcher) { 828 return (Node->isPointerType() && 829 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 830} 831 832/// \brief Overloaded to match the pointee type's declaration. 833inline internal::Matcher<clang::QualType> pointsTo( 834 const internal::Matcher<clang::Decl> &InnerMatcher) { 835 return pointsTo(internal::Matcher<clang::QualType>( 836 hasDeclaration(InnerMatcher))); 837} 838 839/// \brief Matches if the matched type is a reference type and the referenced 840/// type matches the specified matcher. 841/// 842/// Example matches X &x and const X &y 843/// (matcher = variable(hasType(references(record(hasName("X")))))) 844/// class X { 845/// void a(X b) { 846/// X &x = b; 847/// const X &y = b; 848/// }; 849AST_MATCHER_P(clang::QualType, references, internal::Matcher<clang::QualType>, 850 InnerMatcher) { 851 return (Node->isReferenceType() && 852 InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); 853} 854 855/// \brief Overloaded to match the referenced type's declaration. 856inline internal::Matcher<clang::QualType> references( 857 const internal::Matcher<clang::Decl> &InnerMatcher) { 858 return references(internal::Matcher<clang::QualType>( 859 hasDeclaration(InnerMatcher))); 860} 861 862AST_MATCHER_P(clang::CXXMemberCallExpr, onImplicitObjectArgument, 863 internal::Matcher<clang::Expr>, InnerMatcher) { 864 const clang::Expr *ExprNode = 865 const_cast<clang::CXXMemberCallExpr&>(Node).getImplicitObjectArgument(); 866 return (ExprNode != NULL && 867 InnerMatcher.matches(*ExprNode, Finder, Builder)); 868} 869 870/// \brief Matches if the expression's type either matches the specified 871/// matcher, or is a pointer to a type that matches the InnerMatcher. 872inline internal::Matcher<clang::CallExpr> thisPointerType( 873 const internal::Matcher<clang::QualType> &InnerMatcher) { 874 return onImplicitObjectArgument( 875 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 876} 877 878/// \brief Overloaded to match the type's declaration. 879inline internal::Matcher<clang::CallExpr> thisPointerType( 880 const internal::Matcher<clang::Decl> &InnerMatcher) { 881 return onImplicitObjectArgument( 882 anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))); 883} 884 885/// \brief Matches a DeclRefExpr that refers to a declaration that matches the 886/// specified matcher. 887/// 888/// Example matches x in if(x) 889/// (matcher = declarationReference(to(variable(hasName("x"))))) 890/// bool x; 891/// if (x) {} 892AST_MATCHER_P(clang::DeclRefExpr, to, internal::Matcher<clang::Decl>, 893 InnerMatcher) { 894 const clang::Decl *DeclNode = Node.getDecl(); 895 return (DeclNode != NULL && 896 InnerMatcher.matches(*DeclNode, Finder, Builder)); 897} 898 899/// \brief Matches a variable declaration that has an initializer expression 900/// that matches the given matcher. 901/// 902/// Example matches x (matcher = variable(hasInitializer(call()))) 903/// bool y() { return true; } 904/// bool x = y(); 905AST_MATCHER_P( 906 clang::VarDecl, hasInitializer, internal::Matcher<clang::Expr>, 907 InnerMatcher) { 908 const clang::Expr *Initializer = Node.getAnyInitializer(); 909 return (Initializer != NULL && 910 InnerMatcher.matches(*Initializer, Finder, Builder)); 911} 912 913/// \brief Checks that a call expression or a constructor call expression has 914/// a specific number of arguments (including absent default arguments). 915/// 916/// Example matches f(0, 0) (matcher = call(argumentCountIs(2))) 917/// void f(int x, int y); 918/// f(0, 0); 919AST_POLYMORPHIC_MATCHER_P(argumentCountIs, unsigned, N) { 920 TOOLING_COMPILE_ASSERT((llvm::is_base_of<clang::CallExpr, NodeType>::value || 921 llvm::is_base_of<clang::CXXConstructExpr, 922 NodeType>::value), 923 instantiated_with_wrong_types); 924 return Node.getNumArgs() == N; 925} 926 927/// \brief Matches the n'th argument of a call expression or a constructor 928/// call expression. 929/// 930/// Example matches y in x(y) 931/// (matcher = call(hasArgument(0, declarationReference()))) 932/// void x(int) { int y; x(y); } 933AST_POLYMORPHIC_MATCHER_P2( 934 hasArgument, unsigned, N, internal::Matcher<clang::Expr>, InnerMatcher) { 935 TOOLING_COMPILE_ASSERT((llvm::is_base_of<clang::CallExpr, NodeType>::value || 936 llvm::is_base_of<clang::CXXConstructExpr, 937 NodeType>::value), 938 instantiated_with_wrong_types); 939 return (N < Node.getNumArgs() && 940 InnerMatcher.matches( 941 *Node.getArg(N)->IgnoreParenImpCasts(), Finder, Builder)); 942} 943 944/// \brief Matches a constructor initializer. 945/// 946/// Given 947/// struct Foo { 948/// Foo() : foo_(1) { } 949/// int foo_; 950/// }; 951/// record(Has(Constructor(hasAnyConstructorInitializer(anything())))) 952/// Class matches Foo, hasAnyConstructorInitializer matches foo_(1) 953AST_MATCHER_P(clang::CXXConstructorDecl, hasAnyConstructorInitializer, 954 internal::Matcher<clang::CXXCtorInitializer>, InnerMatcher) { 955 for (clang::CXXConstructorDecl::init_const_iterator I = Node.init_begin(); 956 I != Node.init_end(); ++I) { 957 if (InnerMatcher.matches(**I, Finder, Builder)) { 958 return true; 959 } 960 } 961 return false; 962} 963 964/// \brief Matches the field declaration of a constructor initializer. 965/// 966/// Given 967/// struct Foo { 968/// Foo() : foo_(1) { } 969/// int foo_; 970/// }; 971/// record(has(constructor(hasAnyConstructorInitializer( 972/// forField(hasName("foo_")))))) 973/// matches Foo 974/// with forField matching foo_ 975AST_MATCHER_P(clang::CXXCtorInitializer, forField, 976 internal::Matcher<clang::FieldDecl>, InnerMatcher) { 977 const clang::FieldDecl *NodeAsDecl = Node.getMember(); 978 return (NodeAsDecl != NULL && 979 InnerMatcher.matches(*NodeAsDecl, Finder, Builder)); 980} 981 982/// \brief Matches the initializer expression of a constructor initializer. 983/// 984/// Given 985/// struct Foo { 986/// Foo() : foo_(1) { } 987/// int foo_; 988/// }; 989/// record(has(constructor(hasAnyConstructorInitializer( 990/// withInitializer(integerLiteral(equals(1))))))) 991/// matches Foo 992/// with withInitializer matching (1) 993AST_MATCHER_P(clang::CXXCtorInitializer, withInitializer, 994 internal::Matcher<clang::Expr>, InnerMatcher) { 995 const clang::Expr* NodeAsExpr = Node.getInit(); 996 return (NodeAsExpr != NULL && 997 InnerMatcher.matches(*NodeAsExpr, Finder, Builder)); 998} 999 1000/// \brief Matches a contructor initializer if it is explicitly written in 1001/// code (as opposed to implicitly added by the compiler). 1002/// 1003/// Given 1004/// struct Foo { 1005/// Foo() { } 1006/// Foo(int) : foo_("A") { } 1007/// string foo_; 1008/// }; 1009/// constructor(hasAnyConstructorInitializer(isWritten())) 1010/// will match Foo(int), but not Foo() 1011AST_MATCHER(clang::CXXCtorInitializer, isWritten) { 1012 return Node.isWritten(); 1013} 1014 1015/// \brief Matches a constructor declaration that has been implicitly added 1016/// by the compiler (eg. implicit default/copy constructors). 1017AST_MATCHER(clang::CXXConstructorDecl, isImplicit) { 1018 return Node.isImplicit(); 1019} 1020 1021/// \brief Matches any argument of a call expression or a constructor call 1022/// expression. 1023/// 1024/// Given 1025/// void x(int, int, int) { int y; x(1, y, 42); } 1026/// call(hasAnyArgument(declarationReference())) 1027/// matches x(1, y, 42) 1028/// with hasAnyArgument(...) 1029/// matching y 1030AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, internal::Matcher<clang::Expr>, 1031 InnerMatcher) { 1032 TOOLING_COMPILE_ASSERT((llvm::is_base_of<clang::CallExpr, NodeType>::value || 1033 llvm::is_base_of<clang::CXXConstructExpr, 1034 NodeType>::value), 1035 instantiated_with_wrong_types); 1036 for (unsigned I = 0; I < Node.getNumArgs(); ++I) { 1037 if (InnerMatcher.matches(*Node.getArg(I)->IgnoreParenImpCasts(), 1038 Finder, Builder)) { 1039 return true; 1040 } 1041 } 1042 return false; 1043} 1044 1045/// \brief Matches the n'th parameter of a function declaration. 1046/// 1047/// Given 1048/// class X { void f(int x) {} }; 1049/// method(hasParameter(0, hasType(variable()))) 1050/// matches f(int x) {} 1051/// with hasParameter(...) 1052/// matching int x 1053AST_MATCHER_P2(clang::FunctionDecl, hasParameter, 1054 unsigned, N, internal::Matcher<clang::ParmVarDecl>, 1055 InnerMatcher) { 1056 return (N < Node.getNumParams() && 1057 InnerMatcher.matches( 1058 *Node.getParamDecl(N), Finder, Builder)); 1059} 1060 1061/// \brief Matches any parameter of a function declaration. 1062/// 1063/// Does not match the 'this' parameter of a method. 1064/// 1065/// Given 1066/// class X { void f(int x, int y, int z) {} }; 1067/// method(hasAnyParameter(hasName("y"))) 1068/// matches f(int x, int y, int z) {} 1069/// with hasAnyParameter(...) 1070/// matching int y 1071AST_MATCHER_P(clang::FunctionDecl, hasAnyParameter, 1072 internal::Matcher<clang::ParmVarDecl>, InnerMatcher) { 1073 for (unsigned I = 0; I < Node.getNumParams(); ++I) { 1074 if (InnerMatcher.matches(*Node.getParamDecl(I), Finder, Builder)) { 1075 return true; 1076 } 1077 } 1078 return false; 1079} 1080 1081/// \brief Matches the condition expression of an if statement or conditional 1082/// operator. 1083/// 1084/// Example matches true (matcher = hasCondition(boolLiteral(equals(true)))) 1085/// if (true) {} 1086AST_POLYMORPHIC_MATCHER_P(hasCondition, internal::Matcher<clang::Expr>, 1087 InnerMatcher) { 1088 TOOLING_COMPILE_ASSERT( 1089 (llvm::is_base_of<clang::IfStmt, NodeType>::value) || 1090 (llvm::is_base_of<clang::ConditionalOperator, NodeType>::value), 1091 has_condition_requires_if_statement_or_conditional_operator); 1092 const clang::Expr *const Condition = Node.getCond(); 1093 return (Condition != NULL && 1094 InnerMatcher.matches(*Condition, Finder, Builder)); 1095} 1096 1097/// \brief Matches the condition variable statement in an if statement. 1098/// 1099/// Given 1100/// if (A* a = GetAPointer()) {} 1101/// hasConditionVariableStatment(...) 1102/// matches 'A* a = GetAPointer()'. 1103AST_MATCHER_P(clang::IfStmt, hasConditionVariableStatement, 1104 internal::Matcher<clang::DeclStmt>, InnerMatcher) { 1105 const clang::DeclStmt* const DeclarationStatement = 1106 Node.getConditionVariableDeclStmt(); 1107 return DeclarationStatement != NULL && 1108 InnerMatcher.matches(*DeclarationStatement, Finder, Builder); 1109} 1110 1111/// \brief Matches a 'for' statement that has a given body. 1112/// 1113/// Given 1114/// for (;;) {} 1115/// hasBody(compoundStatement()) 1116/// matches 'for (;;) {}' 1117/// with compoundStatement() 1118/// matching '{}' 1119AST_MATCHER_P(clang::ForStmt, hasBody, internal::Matcher<clang::Stmt>, 1120 InnerMatcher) { 1121 const clang::Stmt *const Statement = Node.getBody(); 1122 return (Statement != NULL && 1123 InnerMatcher.matches(*Statement, Finder, Builder)); 1124} 1125 1126/// \brief Matches compound statements where at least one substatement matches 1127/// a given matcher. 1128/// 1129/// Given 1130/// { {}; 1+2; } 1131/// hasAnySubstatement(compoundStatement()) 1132/// matches '{ {}; 1+2; }' 1133/// with compoundStatement() 1134/// matching '{}' 1135AST_MATCHER_P(clang::CompoundStmt, hasAnySubstatement, 1136 internal::Matcher<clang::Stmt>, InnerMatcher) { 1137 for (clang::CompoundStmt::const_body_iterator It = Node.body_begin(); 1138 It != Node.body_end(); 1139 ++It) { 1140 if (InnerMatcher.matches(**It, Finder, Builder)) return true; 1141 } 1142 return false; 1143} 1144 1145/// \brief Checks that a compound statement contains a specific number of 1146/// child statements. 1147/// 1148/// Example: Given 1149/// { for (;;) {} } 1150/// compoundStatement(statementCountIs(0))) 1151/// matches '{}' 1152/// but does not match the outer compound statement. 1153AST_MATCHER_P(clang::CompoundStmt, statementCountIs, unsigned, N) { 1154 return Node.size() == N; 1155} 1156 1157/// \brief Matches literals that are equal to the given value. 1158/// 1159/// Example matches true (matcher = boolLiteral(equals(true))) 1160/// true 1161template <typename ValueT> 1162internal::PolymorphicMatcherWithParam1<internal::ValueEqualsMatcher, ValueT> 1163equals(const ValueT &Value) { 1164 return internal::PolymorphicMatcherWithParam1< 1165 internal::ValueEqualsMatcher, 1166 ValueT>(Value); 1167} 1168 1169/// \brief Matches the operator Name of operator expressions (binary or 1170/// unary). 1171/// 1172/// Example matches a || b (matcher = binaryOperator(hasOperatorName("||"))) 1173/// !(a || b) 1174AST_POLYMORPHIC_MATCHER_P(hasOperatorName, std::string, Name) { 1175 TOOLING_COMPILE_ASSERT( 1176 (llvm::is_base_of<clang::BinaryOperator, NodeType>::value) || 1177 (llvm::is_base_of<clang::UnaryOperator, NodeType>::value), 1178 has_condition_requires_if_statement_or_conditional_operator); 1179 return Name == Node.getOpcodeStr(Node.getOpcode()); 1180} 1181 1182/// \brief Matches the left hand side of binary operator expressions. 1183/// 1184/// Example matches a (matcher = binaryOperator(hasLHS())) 1185/// a || b 1186AST_MATCHER_P(clang::BinaryOperator, hasLHS, 1187 internal::Matcher<clang::Expr>, InnerMatcher) { 1188 clang::Expr *LeftHandSide = Node.getLHS(); 1189 return (LeftHandSide != NULL && 1190 InnerMatcher.matches(*LeftHandSide, Finder, Builder)); 1191} 1192 1193/// \brief Matches the right hand side of binary operator expressions. 1194/// 1195/// Example matches b (matcher = binaryOperator(hasRHS())) 1196/// a || b 1197AST_MATCHER_P(clang::BinaryOperator, hasRHS, 1198 internal::Matcher<clang::Expr>, InnerMatcher) { 1199 clang::Expr *RightHandSide = Node.getRHS(); 1200 return (RightHandSide != NULL && 1201 InnerMatcher.matches(*RightHandSide, Finder, Builder)); 1202} 1203 1204/// \brief Matches if either the left hand side or the right hand side of a 1205/// binary operator matches. 1206inline internal::Matcher<clang::BinaryOperator> hasEitherOperand( 1207 const internal::Matcher<clang::Expr> &InnerMatcher) { 1208 return anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher)); 1209} 1210 1211/// \brief Matches if the operand of a unary operator matches. 1212/// 1213/// Example matches true (matcher = hasOperand(boolLiteral(equals(true)))) 1214/// !true 1215AST_MATCHER_P(clang::UnaryOperator, hasUnaryOperand, 1216 internal::Matcher<clang::Expr>, InnerMatcher) { 1217 const clang::Expr * const Operand = Node.getSubExpr(); 1218 return (Operand != NULL && 1219 InnerMatcher.matches(*Operand, Finder, Builder)); 1220} 1221 1222/// Matches if the implicit cast's source expression matches the given matcher. 1223/// 1224/// Example: matches "a string" (matcher = 1225/// hasSourceExpression(constructorCall())) 1226/// 1227/// class URL { URL(string); }; 1228/// URL url = "a string"; 1229AST_MATCHER_P(clang::ImplicitCastExpr, hasSourceExpression, 1230 internal::Matcher<clang::Expr>, InnerMatcher) { 1231 const clang::Expr* const SubExpression = Node.getSubExpr(); 1232 return (SubExpression != NULL && 1233 InnerMatcher.matches(*SubExpression, Finder, Builder)); 1234} 1235 1236/// \brief Matches casts whose destination type matches a given matcher. 1237/// 1238/// (Note: Clang's AST refers to other conversions as "casts" too, and calls 1239/// actual casts "explicit" casts.) 1240AST_MATCHER_P(clang::ExplicitCastExpr, hasDestinationType, 1241 internal::Matcher<clang::QualType>, InnerMatcher) { 1242 const clang::QualType NodeType = Node.getTypeAsWritten(); 1243 return InnerMatcher.matches(NodeType, Finder, Builder); 1244} 1245 1246/// \brief Matches implicit casts whose destination type matches a given 1247/// matcher. 1248/// 1249/// FIXME: Unit test this matcher 1250AST_MATCHER_P(clang::ImplicitCastExpr, hasImplicitDestinationType, 1251 internal::Matcher<clang::QualType>, InnerMatcher) { 1252 return InnerMatcher.matches(Node.getType(), Finder, Builder); 1253} 1254 1255/// \brief Matches the true branch expression of a conditional operator. 1256/// 1257/// Example matches a 1258/// condition ? a : b 1259AST_MATCHER_P(clang::ConditionalOperator, hasTrueExpression, 1260 internal::Matcher<clang::Expr>, InnerMatcher) { 1261 clang::Expr *Expression = Node.getTrueExpr(); 1262 return (Expression != NULL && 1263 InnerMatcher.matches(*Expression, Finder, Builder)); 1264} 1265 1266/// \brief Matches the false branch expression of a conditional operator. 1267/// 1268/// Example matches b 1269/// condition ? a : b 1270AST_MATCHER_P(clang::ConditionalOperator, hasFalseExpression, 1271 internal::Matcher<clang::Expr>, InnerMatcher) { 1272 clang::Expr *Expression = Node.getFalseExpr(); 1273 return (Expression != NULL && 1274 InnerMatcher.matches(*Expression, Finder, Builder)); 1275} 1276 1277/// \brief Matches if a declaration has a body attached. 1278/// 1279/// Example matches A, va, fa 1280/// class A {}; 1281/// class B; // Doesn't match, as it has no body. 1282/// int va; 1283/// extern int vb; // Doesn't match, as it doesn't define the variable. 1284/// void fa() {} 1285/// void fb(); // Doesn't match, as it has no body. 1286inline internal::PolymorphicMatcherWithParam0<internal::IsDefinitionMatcher> 1287isDefinition() { 1288 return internal::PolymorphicMatcherWithParam0< 1289 internal::IsDefinitionMatcher>(); 1290} 1291 1292/// \brief Matches the class declaration that the given method declaration 1293/// belongs to. 1294/// 1295/// FIXME: Generalize this for other kinds of declarations. 1296/// FIXME: What other kind of declarations would we need to generalize 1297/// this to? 1298/// 1299/// Example matches A() in the last line 1300/// (matcher = constructorCall(hasDeclaration(method( 1301/// ofClass(hasName("A")))))) 1302/// class A { 1303/// public: 1304/// A(); 1305/// }; 1306/// A a = A(); 1307AST_MATCHER_P(clang::CXXMethodDecl, ofClass, 1308 internal::Matcher<clang::CXXRecordDecl>, InnerMatcher) { 1309 const clang::CXXRecordDecl *Parent = Node.getParent(); 1310 return (Parent != NULL && 1311 InnerMatcher.matches(*Parent, Finder, Builder)); 1312} 1313 1314/// \brief Matches member expressions that are called with '->' as opposed 1315/// to '.'. 1316/// 1317/// Member calls on the implicit this pointer match as called with '->'. 1318/// 1319/// Given 1320/// class Y { 1321/// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } 1322/// int a; 1323/// static int b; 1324/// }; 1325/// memberExpression(isArrow()) 1326/// matches this->x, x, y.x, a, this->b 1327inline internal::Matcher<clang::MemberExpr> isArrow() { 1328 return makeMatcher(new internal::IsArrowMatcher()); 1329} 1330 1331/// \brief Matches clang::QualType nodes that are const-qualified, i.e., that 1332/// include "top-level" const. 1333/// 1334/// Given 1335/// void a(int); 1336/// void b(int const); 1337/// void c(const int); 1338/// void d(const int*); 1339/// void e(int const) {}; 1340/// function(hasAnyParameter(hasType(isConstQualified()))) 1341/// matches "void b(int const)", "void c(const int)" and 1342/// "void e(int const) {}". It does not match d as there 1343/// is no top-level const on the parameter type "const int *". 1344inline internal::Matcher<clang::QualType> isConstQualified() { 1345 return makeMatcher(new internal::IsConstQualifiedMatcher()); 1346} 1347 1348/// \brief Matches a member expression where the member is matched by a 1349/// given matcher. 1350/// 1351/// Given 1352/// struct { int first, second; } first, second; 1353/// int i(second.first); 1354/// int j(first.second); 1355/// memberExpression(member(hasName("first"))) 1356/// matches second.first 1357/// but not first.second (because the member name there is "second"). 1358AST_MATCHER_P(clang::MemberExpr, member, 1359 internal::Matcher<clang::ValueDecl>, InnerMatcher) { 1360 return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder); 1361} 1362 1363/// \brief Matches a member expression where the object expression is 1364/// matched by a given matcher. 1365/// 1366/// Given 1367/// struct X { int m; }; 1368/// void f(X x) { x.m; m; } 1369/// memberExpression(hasObjectExpression(hasType(record(hasName("X"))))))) 1370/// matches "x.m" and "m" 1371/// with hasObjectExpression(...) 1372/// matching "x" and the implicit object expression of "m" which has type X*. 1373AST_MATCHER_P(clang::MemberExpr, hasObjectExpression, 1374 internal::Matcher<clang::Expr>, InnerMatcher) { 1375 return InnerMatcher.matches(*Node.getBase(), Finder, Builder); 1376} 1377 1378/// \brief Matches template instantiations of function, class, or static 1379/// member variable template instantiations. 1380/// 1381/// Given 1382/// template <typename T> class X {}; class A {}; X<A> x; 1383/// or 1384/// template <typename T> class X {}; class A {}; template class X<A>; 1385/// record(hasName("::X"), isTemplateInstantiation()) 1386/// matches the template instantiation of X<A>. 1387/// 1388/// But given 1389/// template <typename T> class X {}; class A {}; 1390/// template <> class X<A> {}; X<A> x; 1391/// record(hasName("::X"), isTemplateInstantiation()) 1392/// does not match, as X<A> is an explicit template specialization. 1393inline internal::PolymorphicMatcherWithParam0< 1394 internal::IsTemplateInstantiationMatcher> 1395isTemplateInstantiation() { 1396 return internal::PolymorphicMatcherWithParam0< 1397 internal::IsTemplateInstantiationMatcher>(); 1398} 1399 1400} // end namespace ast_matchers 1401} // end namespace clang 1402 1403#endif // LLVM_CLANG_AST_MATCHERS_AST_MATCHERS_H 1404