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