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