1 //===- ASTMatchersInternal.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 // Implements the base layer of the matcher framework. 10 // 11 // Matchers are methods that return a Matcher<T> which provides a method 12 // Matches(...) which is a predicate on an AST node. The Matches method's 13 // parameters define the context of the match, which allows matchers to recurse 14 // or store the current node as bound to a specific string, so that it can be 15 // retrieved later. 16 // 17 // In general, matchers have two parts: 18 // 1. A function Matcher<T> MatcherName(<arguments>) which returns a Matcher<T> 19 // based on the arguments and optionally on template type deduction based 20 // on the arguments. Matcher<T>s form an implicit reverse hierarchy 21 // to clang's AST class hierarchy, meaning that you can use a Matcher<Base> 22 // everywhere a Matcher<Derived> is required. 23 // 2. An implementation of a class derived from MatcherInterface<T>. 24 // 25 // The matcher functions are defined in ASTMatchers.h. To make it possible 26 // to implement both the matcher function and the implementation of the matcher 27 // interface in one place, ASTMatcherMacros.h defines macros that allow 28 // implementing a matcher in a single place. 29 // 30 // This file contains the base classes needed to construct the actual matchers. 31 // 32 //===----------------------------------------------------------------------===// 33 34 #ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERSINTERNAL_H 35 #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERSINTERNAL_H 36 37 #include "clang/AST/ASTTypeTraits.h" 38 #include "clang/AST/Decl.h" 39 #include "clang/AST/DeclCXX.h" 40 #include "clang/AST/DeclFriend.h" 41 #include "clang/AST/DeclTemplate.h" 42 #include "clang/AST/Expr.h" 43 #include "clang/AST/ExprCXX.h" 44 #include "clang/AST/ExprObjC.h" 45 #include "clang/AST/NestedNameSpecifier.h" 46 #include "clang/AST/Stmt.h" 47 #include "clang/AST/TemplateName.h" 48 #include "clang/AST/Type.h" 49 #include "clang/AST/TypeLoc.h" 50 #include "clang/Basic/LLVM.h" 51 #include "clang/Basic/OperatorKinds.h" 52 #include "llvm/ADT/APFloat.h" 53 #include "llvm/ADT/ArrayRef.h" 54 #include "llvm/ADT/IntrusiveRefCntPtr.h" 55 #include "llvm/ADT/STLExtras.h" 56 #include "llvm/ADT/SmallVector.h" 57 #include "llvm/ADT/StringRef.h" 58 #include "llvm/ADT/iterator.h" 59 #include "llvm/Support/Casting.h" 60 #include "llvm/Support/ManagedStatic.h" 61 #include "llvm/Support/Regex.h" 62 #include <algorithm> 63 #include <cassert> 64 #include <cstddef> 65 #include <cstdint> 66 #include <map> 67 #include <memory> 68 #include <optional> 69 #include <string> 70 #include <tuple> 71 #include <type_traits> 72 #include <utility> 73 #include <vector> 74 75 namespace clang { 76 77 class ASTContext; 78 79 namespace ast_matchers { 80 81 class BoundNodes; 82 83 namespace internal { 84 85 /// A type-list implementation. 86 /// 87 /// A "linked list" of types, accessible by using the ::head and ::tail 88 /// typedefs. 89 template <typename... Ts> struct TypeList {}; // Empty sentinel type list. 90 91 template <typename T1, typename... Ts> struct TypeList<T1, Ts...> { 92 /// The first type on the list. 93 using head = T1; 94 95 /// A sublist with the tail. ie everything but the head. 96 /// 97 /// This type is used to do recursion. TypeList<>/EmptyTypeList indicates the 98 /// end of the list. 99 using tail = TypeList<Ts...>; 100 }; 101 102 /// The empty type list. 103 using EmptyTypeList = TypeList<>; 104 105 /// Helper meta-function to determine if some type \c T is present or 106 /// a parent type in the list. 107 template <typename AnyTypeList, typename T> struct TypeListContainsSuperOf { 108 static const bool value = 109 std::is_base_of<typename AnyTypeList::head, T>::value || 110 TypeListContainsSuperOf<typename AnyTypeList::tail, T>::value; 111 }; 112 template <typename T> struct TypeListContainsSuperOf<EmptyTypeList, T> { 113 static const bool value = false; 114 }; 115 116 /// Variadic function object. 117 /// 118 /// Most of the functions below that use VariadicFunction could be implemented 119 /// using plain C++11 variadic functions, but the function object allows us to 120 /// capture it on the dynamic matcher registry. 121 template <typename ResultT, typename ArgT, 122 ResultT (*Func)(ArrayRef<const ArgT *>)> 123 struct VariadicFunction { 124 ResultT operator()() const { return Func({}); } 125 126 template <typename... ArgsT> 127 ResultT operator()(const ArgT &Arg1, const ArgsT &... Args) const { 128 return Execute(Arg1, static_cast<const ArgT &>(Args)...); 129 } 130 131 // We also allow calls with an already created array, in case the caller 132 // already had it. 133 ResultT operator()(ArrayRef<ArgT> Args) const { 134 return Func(llvm::to_vector<8>(llvm::make_pointer_range(Args))); 135 } 136 137 private: 138 // Trampoline function to allow for implicit conversions to take place 139 // before we make the array. 140 template <typename... ArgsT> ResultT Execute(const ArgsT &... Args) const { 141 const ArgT *const ArgsArray[] = {&Args...}; 142 return Func(ArrayRef<const ArgT *>(ArgsArray, sizeof...(ArgsT))); 143 } 144 }; 145 146 /// Unifies obtaining the underlying type of a regular node through 147 /// `getType` and a TypedefNameDecl node through `getUnderlyingType`. 148 inline QualType getUnderlyingType(const Expr &Node) { return Node.getType(); } 149 150 inline QualType getUnderlyingType(const ValueDecl &Node) { 151 return Node.getType(); 152 } 153 inline QualType getUnderlyingType(const TypedefNameDecl &Node) { 154 return Node.getUnderlyingType(); 155 } 156 inline QualType getUnderlyingType(const FriendDecl &Node) { 157 if (const TypeSourceInfo *TSI = Node.getFriendType()) 158 return TSI->getType(); 159 return QualType(); 160 } 161 inline QualType getUnderlyingType(const CXXBaseSpecifier &Node) { 162 return Node.getType(); 163 } 164 inline QualType getUnderlyingType(const ObjCInterfaceDecl &Node) { 165 return Node.getTypeForDecl()->getPointeeType(); 166 } 167 168 /// Unifies obtaining a `TypeSourceInfo` from different node types. 169 template <typename T, 170 std::enable_if_t<TypeListContainsSuperOf< 171 TypeList<CXXBaseSpecifier, CXXCtorInitializer, 172 CXXTemporaryObjectExpr, CXXUnresolvedConstructExpr, 173 CompoundLiteralExpr, DeclaratorDecl, ObjCPropertyDecl, 174 TemplateArgumentLoc, TypedefNameDecl>, 175 T>::value> * = nullptr> 176 inline TypeSourceInfo *GetTypeSourceInfo(const T &Node) { 177 return Node.getTypeSourceInfo(); 178 } 179 template <typename T, 180 std::enable_if_t<TypeListContainsSuperOf< 181 TypeList<CXXFunctionalCastExpr, ExplicitCastExpr>, T>::value> * = 182 nullptr> 183 inline TypeSourceInfo *GetTypeSourceInfo(const T &Node) { 184 return Node.getTypeInfoAsWritten(); 185 } 186 inline TypeSourceInfo *GetTypeSourceInfo(const BlockDecl &Node) { 187 return Node.getSignatureAsWritten(); 188 } 189 inline TypeSourceInfo *GetTypeSourceInfo(const CXXNewExpr &Node) { 190 return Node.getAllocatedTypeSourceInfo(); 191 } 192 193 /// Unifies obtaining the FunctionProtoType pointer from both 194 /// FunctionProtoType and FunctionDecl nodes.. 195 inline const FunctionProtoType * 196 getFunctionProtoType(const FunctionProtoType &Node) { 197 return &Node; 198 } 199 200 inline const FunctionProtoType *getFunctionProtoType(const FunctionDecl &Node) { 201 return Node.getType()->getAs<FunctionProtoType>(); 202 } 203 204 /// Unifies obtaining the access specifier from Decl and CXXBaseSpecifier nodes. 205 inline clang::AccessSpecifier getAccessSpecifier(const Decl &Node) { 206 return Node.getAccess(); 207 } 208 209 inline clang::AccessSpecifier getAccessSpecifier(const CXXBaseSpecifier &Node) { 210 return Node.getAccessSpecifier(); 211 } 212 213 /// Internal version of BoundNodes. Holds all the bound nodes. 214 class BoundNodesMap { 215 public: 216 /// Adds \c Node to the map with key \c ID. 217 /// 218 /// The node's base type should be in NodeBaseType or it will be unaccessible. 219 void addNode(StringRef ID, const DynTypedNode &DynNode) { 220 NodeMap[std::string(ID)] = DynNode; 221 } 222 223 /// Returns the AST node bound to \c ID. 224 /// 225 /// Returns NULL if there was no node bound to \c ID or if there is a node but 226 /// it cannot be converted to the specified type. 227 template <typename T> 228 const T *getNodeAs(StringRef ID) const { 229 IDToNodeMap::const_iterator It = NodeMap.find(ID); 230 if (It == NodeMap.end()) { 231 return nullptr; 232 } 233 return It->second.get<T>(); 234 } 235 236 DynTypedNode getNode(StringRef ID) const { 237 IDToNodeMap::const_iterator It = NodeMap.find(ID); 238 if (It == NodeMap.end()) { 239 return DynTypedNode(); 240 } 241 return It->second; 242 } 243 244 /// Imposes an order on BoundNodesMaps. 245 bool operator<(const BoundNodesMap &Other) const { 246 return NodeMap < Other.NodeMap; 247 } 248 249 /// A map from IDs to the bound nodes. 250 /// 251 /// Note that we're using std::map here, as for memoization: 252 /// - we need a comparison operator 253 /// - we need an assignment operator 254 using IDToNodeMap = std::map<std::string, DynTypedNode, std::less<>>; 255 256 const IDToNodeMap &getMap() const { 257 return NodeMap; 258 } 259 260 /// Returns \c true if this \c BoundNodesMap can be compared, i.e. all 261 /// stored nodes have memoization data. 262 bool isComparable() const { 263 for (const auto &IDAndNode : NodeMap) { 264 if (!IDAndNode.second.getMemoizationData()) 265 return false; 266 } 267 return true; 268 } 269 270 private: 271 IDToNodeMap NodeMap; 272 }; 273 274 /// Creates BoundNodesTree objects. 275 /// 276 /// The tree builder is used during the matching process to insert the bound 277 /// nodes from the Id matcher. 278 class BoundNodesTreeBuilder { 279 public: 280 /// A visitor interface to visit all BoundNodes results for a 281 /// BoundNodesTree. 282 class Visitor { 283 public: 284 virtual ~Visitor() = default; 285 286 /// Called multiple times during a single call to VisitMatches(...). 287 /// 288 /// 'BoundNodesView' contains the bound nodes for a single match. 289 virtual void visitMatch(const BoundNodes& BoundNodesView) = 0; 290 }; 291 292 /// Add a binding from an id to a node. 293 void setBinding(StringRef Id, const DynTypedNode &DynNode) { 294 if (Bindings.empty()) 295 Bindings.emplace_back(); 296 for (BoundNodesMap &Binding : Bindings) 297 Binding.addNode(Id, DynNode); 298 } 299 300 /// Adds a branch in the tree. 301 void addMatch(const BoundNodesTreeBuilder &Bindings); 302 303 /// Visits all matches that this BoundNodesTree represents. 304 /// 305 /// The ownership of 'ResultVisitor' remains at the caller. 306 void visitMatches(Visitor* ResultVisitor); 307 308 template <typename ExcludePredicate> 309 bool removeBindings(const ExcludePredicate &Predicate) { 310 llvm::erase_if(Bindings, Predicate); 311 return !Bindings.empty(); 312 } 313 314 /// Imposes an order on BoundNodesTreeBuilders. 315 bool operator<(const BoundNodesTreeBuilder &Other) const { 316 return Bindings < Other.Bindings; 317 } 318 319 /// Returns \c true if this \c BoundNodesTreeBuilder can be compared, 320 /// i.e. all stored node maps have memoization data. 321 bool isComparable() const { 322 for (const BoundNodesMap &NodesMap : Bindings) { 323 if (!NodesMap.isComparable()) 324 return false; 325 } 326 return true; 327 } 328 329 private: 330 SmallVector<BoundNodesMap, 1> Bindings; 331 }; 332 333 class ASTMatchFinder; 334 335 /// Generic interface for all matchers. 336 /// 337 /// Used by the implementation of Matcher<T> and DynTypedMatcher. 338 /// In general, implement MatcherInterface<T> or SingleNodeMatcherInterface<T> 339 /// instead. 340 class DynMatcherInterface 341 : public llvm::ThreadSafeRefCountedBase<DynMatcherInterface> { 342 public: 343 virtual ~DynMatcherInterface() = default; 344 345 /// Returns true if \p DynNode can be matched. 346 /// 347 /// May bind \p DynNode to an ID via \p Builder, or recurse into 348 /// the AST via \p Finder. 349 virtual bool dynMatches(const DynTypedNode &DynNode, ASTMatchFinder *Finder, 350 BoundNodesTreeBuilder *Builder) const = 0; 351 352 virtual std::optional<clang::TraversalKind> TraversalKind() const { 353 return std::nullopt; 354 } 355 }; 356 357 /// Generic interface for matchers on an AST node of type T. 358 /// 359 /// Implement this if your matcher may need to inspect the children or 360 /// descendants of the node or bind matched nodes to names. If you are 361 /// writing a simple matcher that only inspects properties of the 362 /// current node and doesn't care about its children or descendants, 363 /// implement SingleNodeMatcherInterface instead. 364 template <typename T> 365 class MatcherInterface : public DynMatcherInterface { 366 public: 367 /// Returns true if 'Node' can be matched. 368 /// 369 /// May bind 'Node' to an ID via 'Builder', or recurse into 370 /// the AST via 'Finder'. 371 virtual bool matches(const T &Node, 372 ASTMatchFinder *Finder, 373 BoundNodesTreeBuilder *Builder) const = 0; 374 375 bool dynMatches(const DynTypedNode &DynNode, ASTMatchFinder *Finder, 376 BoundNodesTreeBuilder *Builder) const override { 377 return matches(DynNode.getUnchecked<T>(), Finder, Builder); 378 } 379 }; 380 381 /// Interface for matchers that only evaluate properties on a single 382 /// node. 383 template <typename T> 384 class SingleNodeMatcherInterface : public MatcherInterface<T> { 385 public: 386 /// Returns true if the matcher matches the provided node. 387 /// 388 /// A subclass must implement this instead of Matches(). 389 virtual bool matchesNode(const T &Node) const = 0; 390 391 private: 392 /// Implements MatcherInterface::Matches. 393 bool matches(const T &Node, 394 ASTMatchFinder * /* Finder */, 395 BoundNodesTreeBuilder * /* Builder */) const override { 396 return matchesNode(Node); 397 } 398 }; 399 400 template <typename> class Matcher; 401 402 /// Matcher that works on a \c DynTypedNode. 403 /// 404 /// It is constructed from a \c Matcher<T> object and redirects most calls to 405 /// underlying matcher. 406 /// It checks whether the \c DynTypedNode is convertible into the type of the 407 /// underlying matcher and then do the actual match on the actual node, or 408 /// return false if it is not convertible. 409 class DynTypedMatcher { 410 public: 411 /// Takes ownership of the provided implementation pointer. 412 template <typename T> 413 DynTypedMatcher(MatcherInterface<T> *Implementation) 414 : SupportedKind(ASTNodeKind::getFromNodeKind<T>()), 415 RestrictKind(SupportedKind), Implementation(Implementation) {} 416 417 /// Construct from a variadic function. 418 enum VariadicOperator { 419 /// Matches nodes for which all provided matchers match. 420 VO_AllOf, 421 422 /// Matches nodes for which at least one of the provided matchers 423 /// matches. 424 VO_AnyOf, 425 426 /// Matches nodes for which at least one of the provided matchers 427 /// matches, but doesn't stop at the first match. 428 VO_EachOf, 429 430 /// Matches any node but executes all inner matchers to find result 431 /// bindings. 432 VO_Optionally, 433 434 /// Matches nodes that do not match the provided matcher. 435 /// 436 /// Uses the variadic matcher interface, but fails if 437 /// InnerMatchers.size() != 1. 438 VO_UnaryNot 439 }; 440 441 static DynTypedMatcher 442 constructVariadic(VariadicOperator Op, ASTNodeKind SupportedKind, 443 std::vector<DynTypedMatcher> InnerMatchers); 444 445 static DynTypedMatcher 446 constructRestrictedWrapper(const DynTypedMatcher &InnerMatcher, 447 ASTNodeKind RestrictKind); 448 449 /// Get a "true" matcher for \p NodeKind. 450 /// 451 /// It only checks that the node is of the right kind. 452 static DynTypedMatcher trueMatcher(ASTNodeKind NodeKind); 453 454 void setAllowBind(bool AB) { AllowBind = AB; } 455 456 /// Check whether this matcher could ever match a node of kind \p Kind. 457 /// \return \c false if this matcher will never match such a node. Otherwise, 458 /// return \c true. 459 bool canMatchNodesOfKind(ASTNodeKind Kind) const; 460 461 /// Return a matcher that points to the same implementation, but 462 /// restricts the node types for \p Kind. 463 DynTypedMatcher dynCastTo(const ASTNodeKind Kind) const; 464 465 /// Return a matcher that points to the same implementation, but sets the 466 /// traversal kind. 467 /// 468 /// If the traversal kind is already set, then \c TK overrides it. 469 DynTypedMatcher withTraversalKind(TraversalKind TK); 470 471 /// Returns true if the matcher matches the given \c DynNode. 472 bool matches(const DynTypedNode &DynNode, ASTMatchFinder *Finder, 473 BoundNodesTreeBuilder *Builder) const; 474 475 /// Same as matches(), but skips the kind check. 476 /// 477 /// It is faster, but the caller must ensure the node is valid for the 478 /// kind of this matcher. 479 bool matchesNoKindCheck(const DynTypedNode &DynNode, ASTMatchFinder *Finder, 480 BoundNodesTreeBuilder *Builder) const; 481 482 /// Bind the specified \p ID to the matcher. 483 /// \return A new matcher with the \p ID bound to it if this matcher supports 484 /// binding. Otherwise, returns an empty \c std::optional<>. 485 std::optional<DynTypedMatcher> tryBind(StringRef ID) const; 486 487 /// Returns a unique \p ID for the matcher. 488 /// 489 /// Casting a Matcher<T> to Matcher<U> creates a matcher that has the 490 /// same \c Implementation pointer, but different \c RestrictKind. We need to 491 /// include both in the ID to make it unique. 492 /// 493 /// \c MatcherIDType supports operator< and provides strict weak ordering. 494 using MatcherIDType = std::pair<ASTNodeKind, uint64_t>; 495 MatcherIDType getID() const { 496 /// FIXME: Document the requirements this imposes on matcher 497 /// implementations (no new() implementation_ during a Matches()). 498 return std::make_pair(RestrictKind, 499 reinterpret_cast<uint64_t>(Implementation.get())); 500 } 501 502 /// Returns the type this matcher works on. 503 /// 504 /// \c matches() will always return false unless the node passed is of this 505 /// or a derived type. 506 ASTNodeKind getSupportedKind() const { return SupportedKind; } 507 508 /// Returns \c true if the passed \c DynTypedMatcher can be converted 509 /// to a \c Matcher<T>. 510 /// 511 /// This method verifies that the underlying matcher in \c Other can process 512 /// nodes of types T. 513 template <typename T> bool canConvertTo() const { 514 return canConvertTo(ASTNodeKind::getFromNodeKind<T>()); 515 } 516 bool canConvertTo(ASTNodeKind To) const; 517 518 /// Construct a \c Matcher<T> interface around the dynamic matcher. 519 /// 520 /// This method asserts that \c canConvertTo() is \c true. Callers 521 /// should call \c canConvertTo() first to make sure that \c this is 522 /// compatible with T. 523 template <typename T> Matcher<T> convertTo() const { 524 assert(canConvertTo<T>()); 525 return unconditionalConvertTo<T>(); 526 } 527 528 /// Same as \c convertTo(), but does not check that the underlying 529 /// matcher can handle a value of T. 530 /// 531 /// If it is not compatible, then this matcher will never match anything. 532 template <typename T> Matcher<T> unconditionalConvertTo() const; 533 534 /// Returns the \c TraversalKind respected by calls to `match()`, if any. 535 /// 536 /// Most matchers will not have a traversal kind set, instead relying on the 537 /// surrounding context. For those, \c std::nullopt is returned. 538 std::optional<clang::TraversalKind> getTraversalKind() const { 539 return Implementation->TraversalKind(); 540 } 541 542 private: 543 DynTypedMatcher(ASTNodeKind SupportedKind, ASTNodeKind RestrictKind, 544 IntrusiveRefCntPtr<DynMatcherInterface> Implementation) 545 : SupportedKind(SupportedKind), RestrictKind(RestrictKind), 546 Implementation(std::move(Implementation)) {} 547 548 bool AllowBind = false; 549 ASTNodeKind SupportedKind; 550 551 /// A potentially stricter node kind. 552 /// 553 /// It allows to perform implicit and dynamic cast of matchers without 554 /// needing to change \c Implementation. 555 ASTNodeKind RestrictKind; 556 IntrusiveRefCntPtr<DynMatcherInterface> Implementation; 557 }; 558 559 /// Wrapper of a MatcherInterface<T> *that allows copying. 560 /// 561 /// A Matcher<Base> can be used anywhere a Matcher<Derived> is 562 /// required. This establishes an is-a relationship which is reverse 563 /// to the AST hierarchy. In other words, Matcher<T> is contravariant 564 /// with respect to T. The relationship is built via a type conversion 565 /// operator rather than a type hierarchy to be able to templatize the 566 /// type hierarchy instead of spelling it out. 567 template <typename T> 568 class Matcher { 569 public: 570 /// Takes ownership of the provided implementation pointer. 571 explicit Matcher(MatcherInterface<T> *Implementation) 572 : Implementation(Implementation) {} 573 574 /// Implicitly converts \c Other to a Matcher<T>. 575 /// 576 /// Requires \c T to be derived from \c From. 577 template <typename From> 578 Matcher(const Matcher<From> &Other, 579 std::enable_if_t<std::is_base_of<From, T>::value && 580 !std::is_same<From, T>::value> * = nullptr) 581 : Implementation(restrictMatcher(Other.Implementation)) { 582 assert(Implementation.getSupportedKind().isSame( 583 ASTNodeKind::getFromNodeKind<T>())); 584 } 585 586 /// Implicitly converts \c Matcher<Type> to \c Matcher<QualType>. 587 /// 588 /// The resulting matcher is not strict, i.e. ignores qualifiers. 589 template <typename TypeT> 590 Matcher(const Matcher<TypeT> &Other, 591 std::enable_if_t<std::is_same<T, QualType>::value && 592 std::is_same<TypeT, Type>::value> * = nullptr) 593 : Implementation(new TypeToQualType<TypeT>(Other)) {} 594 595 /// Convert \c this into a \c Matcher<T> by applying dyn_cast<> to the 596 /// argument. 597 /// \c To must be a base class of \c T. 598 template <typename To> Matcher<To> dynCastTo() const & { 599 static_assert(std::is_base_of<To, T>::value, "Invalid dynCast call."); 600 return Matcher<To>(Implementation); 601 } 602 603 template <typename To> Matcher<To> dynCastTo() && { 604 static_assert(std::is_base_of<To, T>::value, "Invalid dynCast call."); 605 return Matcher<To>(std::move(Implementation)); 606 } 607 608 /// Forwards the call to the underlying MatcherInterface<T> pointer. 609 bool matches(const T &Node, 610 ASTMatchFinder *Finder, 611 BoundNodesTreeBuilder *Builder) const { 612 return Implementation.matches(DynTypedNode::create(Node), Finder, Builder); 613 } 614 615 /// Returns an ID that uniquely identifies the matcher. 616 DynTypedMatcher::MatcherIDType getID() const { 617 return Implementation.getID(); 618 } 619 620 /// Extract the dynamic matcher. 621 /// 622 /// The returned matcher keeps the same restrictions as \c this and remembers 623 /// that it is meant to support nodes of type \c T. 624 operator DynTypedMatcher() const & { return Implementation; } 625 626 operator DynTypedMatcher() && { return std::move(Implementation); } 627 628 /// Allows the conversion of a \c Matcher<Type> to a \c 629 /// Matcher<QualType>. 630 /// 631 /// Depending on the constructor argument, the matcher is either strict, i.e. 632 /// does only matches in the absence of qualifiers, or not, i.e. simply 633 /// ignores any qualifiers. 634 template <typename TypeT> 635 class TypeToQualType : public MatcherInterface<QualType> { 636 const DynTypedMatcher InnerMatcher; 637 638 public: 639 TypeToQualType(const Matcher<TypeT> &InnerMatcher) 640 : InnerMatcher(InnerMatcher) {} 641 642 bool matches(const QualType &Node, ASTMatchFinder *Finder, 643 BoundNodesTreeBuilder *Builder) const override { 644 if (Node.isNull()) 645 return false; 646 return this->InnerMatcher.matches(DynTypedNode::create(*Node), Finder, 647 Builder); 648 } 649 650 std::optional<clang::TraversalKind> TraversalKind() const override { 651 return this->InnerMatcher.getTraversalKind(); 652 } 653 }; 654 655 private: 656 // For Matcher<T> <=> Matcher<U> conversions. 657 template <typename U> friend class Matcher; 658 659 // For DynTypedMatcher::unconditionalConvertTo<T>. 660 friend class DynTypedMatcher; 661 662 static DynTypedMatcher restrictMatcher(const DynTypedMatcher &Other) { 663 return Other.dynCastTo(ASTNodeKind::getFromNodeKind<T>()); 664 } 665 666 explicit Matcher(const DynTypedMatcher &Implementation) 667 : Implementation(restrictMatcher(Implementation)) { 668 assert(this->Implementation.getSupportedKind().isSame( 669 ASTNodeKind::getFromNodeKind<T>())); 670 } 671 672 DynTypedMatcher Implementation; 673 }; // class Matcher 674 675 // Deduction guide for Matcher. 676 template <typename T> Matcher(MatcherInterface<T> *) -> Matcher<T>; 677 678 // TODO: Remove in LLVM 23. 679 template <typename T> 680 [[deprecated( 681 "Use CTAD constructor instead, 'makeMatcher' will be removed in LLVM 23.")]] 682 inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) { 683 return Matcher<T>(Implementation); 684 } 685 686 /// Interface that allows matchers to traverse the AST. 687 /// FIXME: Find a better name. 688 /// 689 /// This provides three entry methods for each base node type in the AST: 690 /// - \c matchesChildOf: 691 /// Matches a matcher on every child node of the given node. Returns true 692 /// if at least one child node could be matched. 693 /// - \c matchesDescendantOf: 694 /// Matches a matcher on all descendant nodes of the given node. Returns true 695 /// if at least one descendant matched. 696 /// - \c matchesAncestorOf: 697 /// Matches a matcher on all ancestors of the given node. Returns true if 698 /// at least one ancestor matched. 699 /// 700 /// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal. 701 /// In the future, we want to implement this for all nodes for which it makes 702 /// sense. In the case of matchesAncestorOf, we'll want to implement it for 703 /// all nodes, as all nodes have ancestors. 704 class ASTMatchFinder { 705 public: 706 /// Defines how bindings are processed on recursive matches. 707 enum BindKind { 708 /// Stop at the first match and only bind the first match. 709 BK_First, 710 711 /// Create results for all combinations of bindings that match. 712 BK_All 713 }; 714 715 /// Defines which ancestors are considered for a match. 716 enum AncestorMatchMode { 717 /// All ancestors. 718 AMM_All, 719 720 /// Direct parent only. 721 AMM_ParentOnly 722 }; 723 724 virtual ~ASTMatchFinder() = default; 725 726 /// Returns true if the given C++ class is directly or indirectly derived 727 /// from a base type matching \c base. 728 /// 729 /// A class is not considered to be derived from itself. 730 virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration, 731 const Matcher<NamedDecl> &Base, 732 BoundNodesTreeBuilder *Builder, 733 bool Directly) = 0; 734 735 /// Returns true if the given Objective-C class is directly or indirectly 736 /// derived from a base class matching \c base. 737 /// 738 /// A class is not considered to be derived from itself. 739 virtual bool objcClassIsDerivedFrom(const ObjCInterfaceDecl *Declaration, 740 const Matcher<NamedDecl> &Base, 741 BoundNodesTreeBuilder *Builder, 742 bool Directly) = 0; 743 744 template <typename T> 745 bool matchesChildOf(const T &Node, const DynTypedMatcher &Matcher, 746 BoundNodesTreeBuilder *Builder, BindKind Bind) { 747 static_assert(std::is_base_of<Decl, T>::value || 748 std::is_base_of<Stmt, T>::value || 749 std::is_base_of<NestedNameSpecifier, T>::value || 750 std::is_base_of<NestedNameSpecifierLoc, T>::value || 751 std::is_base_of<TypeLoc, T>::value || 752 std::is_base_of<QualType, T>::value || 753 std::is_base_of<Attr, T>::value, 754 "unsupported type for recursive matching"); 755 return matchesChildOf(DynTypedNode::create(Node), getASTContext(), Matcher, 756 Builder, Bind); 757 } 758 759 template <typename T> 760 bool matchesDescendantOf(const T &Node, const DynTypedMatcher &Matcher, 761 BoundNodesTreeBuilder *Builder, BindKind Bind) { 762 static_assert(std::is_base_of<Decl, T>::value || 763 std::is_base_of<Stmt, T>::value || 764 std::is_base_of<NestedNameSpecifier, T>::value || 765 std::is_base_of<NestedNameSpecifierLoc, T>::value || 766 std::is_base_of<TypeLoc, T>::value || 767 std::is_base_of<QualType, T>::value || 768 std::is_base_of<Attr, T>::value, 769 "unsupported type for recursive matching"); 770 return matchesDescendantOf(DynTypedNode::create(Node), getASTContext(), 771 Matcher, Builder, Bind); 772 } 773 774 // FIXME: Implement support for BindKind. 775 template <typename T> 776 bool matchesAncestorOf(const T &Node, const DynTypedMatcher &Matcher, 777 BoundNodesTreeBuilder *Builder, 778 AncestorMatchMode MatchMode) { 779 static_assert(std::is_base_of<Decl, T>::value || 780 std::is_base_of<NestedNameSpecifierLoc, T>::value || 781 std::is_base_of<Stmt, T>::value || 782 std::is_base_of<TypeLoc, T>::value || 783 std::is_base_of<Attr, T>::value, 784 "type not allowed for recursive matching"); 785 return matchesAncestorOf(DynTypedNode::create(Node), getASTContext(), 786 Matcher, Builder, MatchMode); 787 } 788 789 virtual ASTContext &getASTContext() const = 0; 790 791 virtual bool IsMatchingInASTNodeNotSpelledInSource() const = 0; 792 793 virtual bool IsMatchingInASTNodeNotAsIs() const = 0; 794 795 bool isTraversalIgnoringImplicitNodes() const; 796 797 protected: 798 virtual bool matchesChildOf(const DynTypedNode &Node, ASTContext &Ctx, 799 const DynTypedMatcher &Matcher, 800 BoundNodesTreeBuilder *Builder, 801 BindKind Bind) = 0; 802 803 virtual bool matchesDescendantOf(const DynTypedNode &Node, ASTContext &Ctx, 804 const DynTypedMatcher &Matcher, 805 BoundNodesTreeBuilder *Builder, 806 BindKind Bind) = 0; 807 808 virtual bool matchesAncestorOf(const DynTypedNode &Node, ASTContext &Ctx, 809 const DynTypedMatcher &Matcher, 810 BoundNodesTreeBuilder *Builder, 811 AncestorMatchMode MatchMode) = 0; 812 private: 813 friend struct ASTChildrenNotSpelledInSourceScope; 814 virtual bool isMatchingChildrenNotSpelledInSource() const = 0; 815 virtual void setMatchingChildrenNotSpelledInSource(bool Set) = 0; 816 }; 817 818 struct ASTChildrenNotSpelledInSourceScope { 819 ASTChildrenNotSpelledInSourceScope(ASTMatchFinder *V, bool B) 820 : MV(V), MB(V->isMatchingChildrenNotSpelledInSource()) { 821 V->setMatchingChildrenNotSpelledInSource(B); 822 } 823 ~ASTChildrenNotSpelledInSourceScope() { 824 MV->setMatchingChildrenNotSpelledInSource(MB); 825 } 826 827 private: 828 ASTMatchFinder *MV; 829 bool MB; 830 }; 831 832 /// Specialization of the conversion functions for QualType. 833 /// 834 /// This specialization provides the Matcher<Type>->Matcher<QualType> 835 /// conversion that the static API does. 836 template <> 837 inline Matcher<QualType> DynTypedMatcher::convertTo<QualType>() const { 838 assert(canConvertTo<QualType>()); 839 const ASTNodeKind SourceKind = getSupportedKind(); 840 if (SourceKind.isSame(ASTNodeKind::getFromNodeKind<Type>())) { 841 // We support implicit conversion from Matcher<Type> to Matcher<QualType> 842 return unconditionalConvertTo<Type>(); 843 } 844 return unconditionalConvertTo<QualType>(); 845 } 846 847 /// Finds the first node in a range that matches the given matcher. 848 template <typename MatcherT, typename IteratorT> 849 IteratorT matchesFirstInRange(const MatcherT &Matcher, IteratorT Start, 850 IteratorT End, ASTMatchFinder *Finder, 851 BoundNodesTreeBuilder *Builder) { 852 for (IteratorT I = Start; I != End; ++I) { 853 BoundNodesTreeBuilder Result(*Builder); 854 if (Matcher.matches(*I, Finder, &Result)) { 855 *Builder = std::move(Result); 856 return I; 857 } 858 } 859 return End; 860 } 861 862 /// Finds the first node in a pointer range that matches the given 863 /// matcher. 864 template <typename MatcherT, typename IteratorT> 865 IteratorT matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start, 866 IteratorT End, ASTMatchFinder *Finder, 867 BoundNodesTreeBuilder *Builder) { 868 for (IteratorT I = Start; I != End; ++I) { 869 BoundNodesTreeBuilder Result(*Builder); 870 if (Matcher.matches(**I, Finder, &Result)) { 871 *Builder = std::move(Result); 872 return I; 873 } 874 } 875 return End; 876 } 877 878 template <typename T> inline bool isDefaultedHelper(const T *FD) { 879 if constexpr (std::is_base_of_v<FunctionDecl, T>) 880 return FD->isDefaulted(); 881 return false; 882 } 883 884 // Metafunction to determine if type T has a member called getDecl. 885 template <typename T> 886 using check_has_getDecl = decltype(std::declval<T &>().getDecl()); 887 888 template <typename T> 889 static constexpr bool has_getDecl = 890 llvm::is_detected<check_has_getDecl, T>::value; 891 892 /// Matches overloaded operators with a specific name. 893 /// 894 /// The type argument ArgT is not used by this matcher but is used by 895 /// PolymorphicMatcher and should be StringRef. 896 template <typename T, typename ArgT> 897 class HasOverloadedOperatorNameMatcher : public SingleNodeMatcherInterface<T> { 898 static_assert(std::is_same<T, CXXOperatorCallExpr>::value || 899 std::is_base_of<FunctionDecl, T>::value, 900 "unsupported class for matcher"); 901 static_assert(std::is_same<ArgT, std::vector<std::string>>::value, 902 "argument type must be std::vector<std::string>"); 903 904 public: 905 explicit HasOverloadedOperatorNameMatcher(std::vector<std::string> Names) 906 : SingleNodeMatcherInterface<T>(), Names(std::move(Names)) {} 907 908 bool matchesNode(const T &Node) const override { 909 return matchesSpecialized(Node); 910 } 911 912 private: 913 914 /// CXXOperatorCallExpr exist only for calls to overloaded operators 915 /// so this function returns true if the call is to an operator of the given 916 /// name. 917 bool matchesSpecialized(const CXXOperatorCallExpr &Node) const { 918 return llvm::is_contained(Names, getOperatorSpelling(Node.getOperator())); 919 } 920 921 /// Returns true only if CXXMethodDecl represents an overloaded 922 /// operator and has the given operator name. 923 bool matchesSpecialized(const FunctionDecl &Node) const { 924 return Node.isOverloadedOperator() && 925 llvm::is_contained( 926 Names, getOperatorSpelling(Node.getOverloadedOperator())); 927 } 928 929 std::vector<std::string> Names; 930 }; 931 932 /// Matches named declarations with a specific name. 933 /// 934 /// See \c hasName() and \c hasAnyName() in ASTMatchers.h for details. 935 class HasNameMatcher : public SingleNodeMatcherInterface<NamedDecl> { 936 public: 937 explicit HasNameMatcher(std::vector<std::string> Names); 938 939 bool matchesNode(const NamedDecl &Node) const override; 940 941 private: 942 /// Unqualified match routine. 943 /// 944 /// It is much faster than the full match, but it only works for unqualified 945 /// matches. 946 bool matchesNodeUnqualified(const NamedDecl &Node) const; 947 948 /// Full match routine 949 /// 950 /// Fast implementation for the simple case of a named declaration at 951 /// namespace or RecordDecl scope. 952 /// It is slower than matchesNodeUnqualified, but faster than 953 /// matchesNodeFullSlow. 954 bool matchesNodeFullFast(const NamedDecl &Node) const; 955 956 /// Full match routine 957 /// 958 /// It generates the fully qualified name of the declaration (which is 959 /// expensive) before trying to match. 960 /// It is slower but simple and works on all cases. 961 bool matchesNodeFullSlow(const NamedDecl &Node) const; 962 963 bool UseUnqualifiedMatch; 964 std::vector<std::string> Names; 965 }; 966 967 /// Trampoline function to use VariadicFunction<> to construct a 968 /// HasNameMatcher. 969 Matcher<NamedDecl> hasAnyNameFunc(ArrayRef<const StringRef *> NameRefs); 970 971 /// Trampoline function to use VariadicFunction<> to construct a 972 /// hasAnySelector matcher. 973 Matcher<ObjCMessageExpr> hasAnySelectorFunc( 974 ArrayRef<const StringRef *> NameRefs); 975 976 /// Matches declarations for QualType and CallExpr. 977 /// 978 /// Type argument DeclMatcherT is required by PolymorphicMatcher but 979 /// not actually used. 980 template <typename T, typename DeclMatcherT> 981 class HasDeclarationMatcher : public MatcherInterface<T> { 982 static_assert(std::is_same<DeclMatcherT, Matcher<Decl>>::value, 983 "instantiated with wrong types"); 984 985 DynTypedMatcher InnerMatcher; 986 987 public: 988 explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher) 989 : InnerMatcher(InnerMatcher) {} 990 991 bool matches(const T &Node, ASTMatchFinder *Finder, 992 BoundNodesTreeBuilder *Builder) const override { 993 return matchesSpecialized(Node, Finder, Builder); 994 } 995 996 private: 997 /// Forwards to matching on the underlying type of the QualType. 998 bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder, 999 BoundNodesTreeBuilder *Builder) const { 1000 if (Node.isNull()) 1001 return false; 1002 1003 return matchesSpecialized(*Node, Finder, Builder); 1004 } 1005 1006 /// Finds the best declaration for a type and returns whether the inner 1007 /// matcher matches on it. 1008 bool matchesSpecialized(const Type &Node, ASTMatchFinder *Finder, 1009 BoundNodesTreeBuilder *Builder) const { 1010 // DeducedType does not have declarations of its own, so 1011 // match the deduced type instead. 1012 if (const auto *S = dyn_cast<DeducedType>(&Node)) { 1013 QualType DT = S->getDeducedType(); 1014 return !DT.isNull() ? matchesSpecialized(*DT, Finder, Builder) : false; 1015 } 1016 1017 // First, for any types that have a declaration, extract the declaration and 1018 // match on it. 1019 if (const auto *S = dyn_cast<TagType>(&Node)) { 1020 return matchesDecl(S->getDecl(), Finder, Builder); 1021 } 1022 if (const auto *S = dyn_cast<InjectedClassNameType>(&Node)) { 1023 return matchesDecl(S->getDecl(), Finder, Builder); 1024 } 1025 if (const auto *S = dyn_cast<TemplateTypeParmType>(&Node)) { 1026 return matchesDecl(S->getDecl(), Finder, Builder); 1027 } 1028 if (const auto *S = dyn_cast<TypedefType>(&Node)) { 1029 return matchesDecl(S->getDecl(), Finder, Builder); 1030 } 1031 if (const auto *S = dyn_cast<UnresolvedUsingType>(&Node)) { 1032 return matchesDecl(S->getDecl(), Finder, Builder); 1033 } 1034 if (const auto *S = dyn_cast<ObjCObjectType>(&Node)) { 1035 return matchesDecl(S->getInterface(), Finder, Builder); 1036 } 1037 1038 // A SubstTemplateTypeParmType exists solely to mark a type substitution 1039 // on the instantiated template. As users usually want to match the 1040 // template parameter on the uninitialized template, we can always desugar 1041 // one level without loss of expressiveness. 1042 // For example, given: 1043 // template<typename T> struct X { T t; } class A {}; X<A> a; 1044 // The following matcher will match, which otherwise would not: 1045 // fieldDecl(hasType(pointerType())). 1046 if (const auto *S = dyn_cast<SubstTemplateTypeParmType>(&Node)) { 1047 return matchesSpecialized(S->getReplacementType(), Finder, Builder); 1048 } 1049 1050 // For template specialization types, we want to match the template 1051 // declaration, as long as the type is still dependent, and otherwise the 1052 // declaration of the instantiated tag type. 1053 if (const auto *S = dyn_cast<TemplateSpecializationType>(&Node)) { 1054 if (!S->isTypeAlias() && S->isSugared()) { 1055 // If the template is non-dependent, we want to match the instantiated 1056 // tag type. 1057 // For example, given: 1058 // template<typename T> struct X {}; X<int> a; 1059 // The following matcher will match, which otherwise would not: 1060 // templateSpecializationType(hasDeclaration(cxxRecordDecl())). 1061 return matchesSpecialized(*S->desugar(), Finder, Builder); 1062 } 1063 // If the template is dependent or an alias, match the template 1064 // declaration. 1065 return matchesDecl(S->getTemplateName().getAsTemplateDecl(), Finder, 1066 Builder); 1067 } 1068 1069 // FIXME: We desugar elaborated types. This makes the assumption that users 1070 // do never want to match on whether a type is elaborated - there are 1071 // arguments for both sides; for now, continue desugaring. 1072 if (const auto *S = dyn_cast<ElaboratedType>(&Node)) { 1073 return matchesSpecialized(S->desugar(), Finder, Builder); 1074 } 1075 // Similarly types found via using declarations. 1076 // These are *usually* meaningless sugar, and this matches the historical 1077 // behavior prior to the introduction of UsingType. 1078 if (const auto *S = dyn_cast<UsingType>(&Node)) { 1079 return matchesSpecialized(S->desugar(), Finder, Builder); 1080 } 1081 return false; 1082 } 1083 1084 /// Extracts the Decl the DeclRefExpr references and returns whether 1085 /// the inner matcher matches on it. 1086 bool matchesSpecialized(const DeclRefExpr &Node, ASTMatchFinder *Finder, 1087 BoundNodesTreeBuilder *Builder) const { 1088 return matchesDecl(Node.getDecl(), Finder, Builder); 1089 } 1090 1091 /// Extracts the Decl of the callee of a CallExpr and returns whether 1092 /// the inner matcher matches on it. 1093 bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder, 1094 BoundNodesTreeBuilder *Builder) const { 1095 return matchesDecl(Node.getCalleeDecl(), Finder, Builder); 1096 } 1097 1098 /// Extracts the Decl of the constructor call and returns whether the 1099 /// inner matcher matches on it. 1100 bool matchesSpecialized(const CXXConstructExpr &Node, 1101 ASTMatchFinder *Finder, 1102 BoundNodesTreeBuilder *Builder) const { 1103 return matchesDecl(Node.getConstructor(), Finder, Builder); 1104 } 1105 1106 bool matchesSpecialized(const ObjCIvarRefExpr &Node, 1107 ASTMatchFinder *Finder, 1108 BoundNodesTreeBuilder *Builder) const { 1109 return matchesDecl(Node.getDecl(), Finder, Builder); 1110 } 1111 1112 bool matchesSpecialized(const ObjCInterfaceDecl &Node, ASTMatchFinder *Finder, 1113 BoundNodesTreeBuilder *Builder) const { 1114 return matchesDecl(Node.getCanonicalDecl(), Finder, Builder); 1115 } 1116 1117 /// Extracts the operator new of the new call and returns whether the 1118 /// inner matcher matches on it. 1119 bool matchesSpecialized(const CXXNewExpr &Node, 1120 ASTMatchFinder *Finder, 1121 BoundNodesTreeBuilder *Builder) const { 1122 return matchesDecl(Node.getOperatorNew(), Finder, Builder); 1123 } 1124 1125 /// Extracts the \c ValueDecl a \c MemberExpr refers to and returns 1126 /// whether the inner matcher matches on it. 1127 bool matchesSpecialized(const MemberExpr &Node, 1128 ASTMatchFinder *Finder, 1129 BoundNodesTreeBuilder *Builder) const { 1130 return matchesDecl(Node.getMemberDecl(), Finder, Builder); 1131 } 1132 1133 /// Extracts the \c LabelDecl a \c AddrLabelExpr refers to and returns 1134 /// whether the inner matcher matches on it. 1135 bool matchesSpecialized(const AddrLabelExpr &Node, 1136 ASTMatchFinder *Finder, 1137 BoundNodesTreeBuilder *Builder) const { 1138 return matchesDecl(Node.getLabel(), Finder, Builder); 1139 } 1140 1141 /// Extracts the declaration of a LabelStmt and returns whether the 1142 /// inner matcher matches on it. 1143 bool matchesSpecialized(const LabelStmt &Node, ASTMatchFinder *Finder, 1144 BoundNodesTreeBuilder *Builder) const { 1145 return matchesDecl(Node.getDecl(), Finder, Builder); 1146 } 1147 1148 /// Returns whether the inner matcher \c Node. Returns false if \c Node 1149 /// is \c NULL. 1150 bool matchesDecl(const Decl *Node, ASTMatchFinder *Finder, 1151 BoundNodesTreeBuilder *Builder) const { 1152 return Node != nullptr && 1153 !(Finder->isTraversalIgnoringImplicitNodes() && 1154 Node->isImplicit()) && 1155 this->InnerMatcher.matches(DynTypedNode::create(*Node), Finder, 1156 Builder); 1157 } 1158 }; 1159 1160 /// IsBaseType<T>::value is true if T is a "base" type in the AST 1161 /// node class hierarchies. 1162 template <typename T> 1163 struct IsBaseType { 1164 static const bool value = 1165 std::is_same<T, Decl>::value || std::is_same<T, Stmt>::value || 1166 std::is_same<T, QualType>::value || std::is_same<T, Type>::value || 1167 std::is_same<T, TypeLoc>::value || 1168 std::is_same<T, NestedNameSpecifier>::value || 1169 std::is_same<T, NestedNameSpecifierLoc>::value || 1170 std::is_same<T, CXXCtorInitializer>::value || 1171 std::is_same<T, TemplateArgumentLoc>::value || 1172 std::is_same<T, Attr>::value; 1173 }; 1174 template <typename T> 1175 const bool IsBaseType<T>::value; 1176 1177 /// A "type list" that contains all types. 1178 /// 1179 /// Useful for matchers like \c anything and \c unless. 1180 using AllNodeBaseTypes = 1181 TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc, QualType, 1182 Type, TypeLoc, CXXCtorInitializer, Attr>; 1183 1184 /// Helper meta-function to extract the argument out of a function of 1185 /// type void(Arg). 1186 /// 1187 /// See AST_POLYMORPHIC_SUPPORTED_TYPES for details. 1188 template <class T> struct ExtractFunctionArgMeta; 1189 template <class T> struct ExtractFunctionArgMeta<void(T)> { 1190 using type = T; 1191 }; 1192 1193 template <class T, class Tuple, std::size_t... I> 1194 constexpr T *new_from_tuple_impl(Tuple &&t, std::index_sequence<I...>) { 1195 return new T(std::get<I>(std::forward<Tuple>(t))...); 1196 } 1197 1198 template <class T, class Tuple> constexpr T *new_from_tuple(Tuple &&t) { 1199 return new_from_tuple_impl<T>( 1200 std::forward<Tuple>(t), 1201 std::make_index_sequence< 1202 std::tuple_size<std::remove_reference_t<Tuple>>::value>{}); 1203 } 1204 1205 /// Default type lists for ArgumentAdaptingMatcher matchers. 1206 using AdaptativeDefaultFromTypes = AllNodeBaseTypes; 1207 using AdaptativeDefaultToTypes = 1208 TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc, TypeLoc, 1209 QualType, Attr>; 1210 1211 /// All types that are supported by HasDeclarationMatcher above. 1212 using HasDeclarationSupportedTypes = 1213 TypeList<CallExpr, CXXConstructExpr, CXXNewExpr, DeclRefExpr, EnumType, 1214 ElaboratedType, InjectedClassNameType, LabelStmt, AddrLabelExpr, 1215 MemberExpr, QualType, RecordType, TagType, 1216 TemplateSpecializationType, TemplateTypeParmType, TypedefType, 1217 UnresolvedUsingType, ObjCIvarRefExpr, ObjCInterfaceDecl>; 1218 1219 /// A Matcher that allows binding the node it matches to an id. 1220 /// 1221 /// BindableMatcher provides a \a bind() method that allows binding the 1222 /// matched node to an id if the match was successful. 1223 template <typename T> class BindableMatcher : public Matcher<T> { 1224 public: 1225 explicit BindableMatcher(const Matcher<T> &M) : Matcher<T>(M) {} 1226 explicit BindableMatcher(MatcherInterface<T> *Implementation) 1227 : Matcher<T>(Implementation) {} 1228 1229 /// Returns a matcher that will bind the matched node on a match. 1230 /// 1231 /// The returned matcher is equivalent to this matcher, but will 1232 /// bind the matched node on a match. 1233 Matcher<T> bind(StringRef ID) const { 1234 return DynTypedMatcher(*this) 1235 .tryBind(ID) 1236 ->template unconditionalConvertTo<T>(); 1237 } 1238 1239 /// Same as Matcher<T>'s conversion operator, but enables binding on 1240 /// the returned matcher. 1241 operator DynTypedMatcher() const { 1242 DynTypedMatcher Result = static_cast<const Matcher<T> &>(*this); 1243 Result.setAllowBind(true); 1244 return Result; 1245 } 1246 }; 1247 1248 /// Matches any instance of the given NodeType. 1249 /// 1250 /// This is useful when a matcher syntactically requires a child matcher, 1251 /// but the context doesn't care. See for example: anything(). 1252 class TrueMatcher { 1253 public: 1254 using ReturnTypes = AllNodeBaseTypes; 1255 1256 template <typename T> operator Matcher<T>() const { 1257 return DynTypedMatcher::trueMatcher(ASTNodeKind::getFromNodeKind<T>()) 1258 .template unconditionalConvertTo<T>(); 1259 } 1260 }; 1261 1262 /// Creates a Matcher<T> that matches if all inner matchers match. 1263 template <typename T> 1264 BindableMatcher<T> 1265 makeAllOfComposite(ArrayRef<const Matcher<T> *> InnerMatchers) { 1266 // For the size() == 0 case, we return a "true" matcher. 1267 if (InnerMatchers.empty()) { 1268 return BindableMatcher<T>(TrueMatcher()); 1269 } 1270 // For the size() == 1 case, we simply return that one matcher. 1271 // No need to wrap it in a variadic operation. 1272 if (InnerMatchers.size() == 1) { 1273 return BindableMatcher<T>(*InnerMatchers[0]); 1274 } 1275 1276 using PI = llvm::pointee_iterator<const Matcher<T> *const *>; 1277 1278 std::vector<DynTypedMatcher> DynMatchers(PI(InnerMatchers.begin()), 1279 PI(InnerMatchers.end())); 1280 return BindableMatcher<T>( 1281 DynTypedMatcher::constructVariadic(DynTypedMatcher::VO_AllOf, 1282 ASTNodeKind::getFromNodeKind<T>(), 1283 std::move(DynMatchers)) 1284 .template unconditionalConvertTo<T>()); 1285 } 1286 1287 /// Creates a Matcher<T> that matches if 1288 /// T is dyn_cast'able into InnerT and all inner matchers match. 1289 /// 1290 /// Returns BindableMatcher, as matchers that use dyn_cast have 1291 /// the same object both to match on and to run submatchers on, 1292 /// so there is no ambiguity with what gets bound. 1293 template <typename T, typename InnerT> 1294 BindableMatcher<T> 1295 makeDynCastAllOfComposite(ArrayRef<const Matcher<InnerT> *> InnerMatchers) { 1296 return BindableMatcher<T>( 1297 makeAllOfComposite(InnerMatchers).template dynCastTo<T>()); 1298 } 1299 1300 /// A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a 1301 /// variadic functor that takes a number of Matcher<TargetT> and returns a 1302 /// Matcher<SourceT> that matches TargetT nodes that are matched by all of the 1303 /// given matchers, if SourceT can be dynamically casted into TargetT. 1304 /// 1305 /// For example: 1306 /// const VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl> record; 1307 /// Creates a functor record(...) that creates a Matcher<Decl> given 1308 /// a variable number of arguments of type Matcher<CXXRecordDecl>. 1309 /// The returned matcher matches if the given Decl can by dynamically 1310 /// casted to CXXRecordDecl and all given matchers match. 1311 template <typename SourceT, typename TargetT> 1312 class VariadicDynCastAllOfMatcher 1313 : public VariadicFunction<BindableMatcher<SourceT>, Matcher<TargetT>, 1314 makeDynCastAllOfComposite<SourceT, TargetT>> { 1315 public: 1316 VariadicDynCastAllOfMatcher() {} 1317 }; 1318 1319 /// A \c VariadicAllOfMatcher<T> object is a variadic functor that takes 1320 /// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T 1321 /// nodes that are matched by all of the given matchers. 1322 /// 1323 /// For example: 1324 /// const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier; 1325 /// Creates a functor nestedNameSpecifier(...) that creates a 1326 /// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type 1327 /// \c Matcher<NestedNameSpecifier>. 1328 /// The returned matcher matches if all given matchers match. 1329 template <typename T> 1330 class VariadicAllOfMatcher 1331 : public VariadicFunction<BindableMatcher<T>, Matcher<T>, 1332 makeAllOfComposite<T>> { 1333 public: 1334 VariadicAllOfMatcher() {} 1335 }; 1336 1337 /// VariadicOperatorMatcher related types. 1338 /// @{ 1339 1340 /// Polymorphic matcher object that uses a \c 1341 /// DynTypedMatcher::VariadicOperator operator. 1342 /// 1343 /// Input matchers can have any type (including other polymorphic matcher 1344 /// types), and the actual Matcher<T> is generated on demand with an implicit 1345 /// conversion operator. 1346 template <typename... Ps> class VariadicOperatorMatcher { 1347 public: 1348 VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op, Ps &&... Params) 1349 : Op(Op), Params(std::forward<Ps>(Params)...) {} 1350 1351 template <typename T> operator Matcher<T>() const & { 1352 return DynTypedMatcher::constructVariadic( 1353 Op, ASTNodeKind::getFromNodeKind<T>(), 1354 getMatchers<T>(std::index_sequence_for<Ps...>())) 1355 .template unconditionalConvertTo<T>(); 1356 } 1357 1358 template <typename T> operator Matcher<T>() && { 1359 return DynTypedMatcher::constructVariadic( 1360 Op, ASTNodeKind::getFromNodeKind<T>(), 1361 getMatchers<T>(std::index_sequence_for<Ps...>())) 1362 .template unconditionalConvertTo<T>(); 1363 } 1364 1365 private: 1366 // Helper method to unpack the tuple into a vector. 1367 template <typename T, std::size_t... Is> 1368 std::vector<DynTypedMatcher> getMatchers(std::index_sequence<Is...>) const & { 1369 return {Matcher<T>(std::get<Is>(Params))...}; 1370 } 1371 1372 template <typename T, std::size_t... Is> 1373 std::vector<DynTypedMatcher> getMatchers(std::index_sequence<Is...>) && { 1374 return {Matcher<T>(std::get<Is>(std::move(Params)))...}; 1375 } 1376 1377 const DynTypedMatcher::VariadicOperator Op; 1378 std::tuple<Ps...> Params; 1379 }; 1380 1381 /// Overloaded function object to generate VariadicOperatorMatcher 1382 /// objects from arbitrary matchers. 1383 template <unsigned MinCount, unsigned MaxCount> 1384 struct VariadicOperatorMatcherFunc { 1385 DynTypedMatcher::VariadicOperator Op; 1386 1387 template <typename... Ms> 1388 VariadicOperatorMatcher<Ms...> operator()(Ms &&... Ps) const { 1389 static_assert(MinCount <= sizeof...(Ms) && sizeof...(Ms) <= MaxCount, 1390 "invalid number of parameters for variadic matcher"); 1391 return VariadicOperatorMatcher<Ms...>(Op, std::forward<Ms>(Ps)...); 1392 } 1393 }; 1394 1395 template <typename T, bool IsBaseOf, typename Head, typename Tail> 1396 struct GetCladeImpl { 1397 using Type = Head; 1398 }; 1399 template <typename T, typename Head, typename Tail> 1400 struct GetCladeImpl<T, false, Head, Tail> 1401 : GetCladeImpl<T, std::is_base_of<typename Tail::head, T>::value, 1402 typename Tail::head, typename Tail::tail> {}; 1403 1404 template <typename T, typename... U> 1405 struct GetClade : GetCladeImpl<T, false, T, AllNodeBaseTypes> {}; 1406 1407 template <typename CladeType, typename... MatcherTypes> 1408 struct MapAnyOfMatcherImpl { 1409 1410 template <typename... InnerMatchers> 1411 BindableMatcher<CladeType> 1412 operator()(InnerMatchers &&... InnerMatcher) const { 1413 return VariadicAllOfMatcher<CladeType>()(std::apply( 1414 internal::VariadicOperatorMatcherFunc< 1415 0, std::numeric_limits<unsigned>::max()>{ 1416 internal::DynTypedMatcher::VO_AnyOf}, 1417 std::apply( 1418 [&](auto... Matcher) { 1419 return std::make_tuple(Matcher(InnerMatcher...)...); 1420 }, 1421 std::tuple< 1422 VariadicDynCastAllOfMatcher<CladeType, MatcherTypes>...>()))); 1423 } 1424 }; 1425 1426 template <typename... MatcherTypes> 1427 using MapAnyOfMatcher = 1428 MapAnyOfMatcherImpl<typename GetClade<MatcherTypes...>::Type, 1429 MatcherTypes...>; 1430 1431 template <typename... MatcherTypes> struct MapAnyOfHelper { 1432 using CladeType = typename GetClade<MatcherTypes...>::Type; 1433 1434 MapAnyOfMatcher<MatcherTypes...> with; 1435 1436 operator BindableMatcher<CladeType>() const { return with(); } 1437 1438 Matcher<CladeType> bind(StringRef ID) const { return with().bind(ID); } 1439 }; 1440 1441 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT, 1442 typename T, typename ToTypes> 1443 class ArgumentAdaptingMatcherFuncAdaptor { 1444 public: 1445 explicit ArgumentAdaptingMatcherFuncAdaptor(const Matcher<T> &InnerMatcher) 1446 : InnerMatcher(InnerMatcher) {} 1447 1448 using ReturnTypes = ToTypes; 1449 1450 template <typename To> operator Matcher<To>() const & { 1451 return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher)); 1452 } 1453 1454 template <typename To> operator Matcher<To>() && { 1455 return Matcher<To>(new ArgumentAdapterT<To, T>(std::move(InnerMatcher))); 1456 } 1457 1458 private: 1459 Matcher<T> InnerMatcher; 1460 }; 1461 1462 /// Converts a \c Matcher<T> to a matcher of desired type \c To by 1463 /// "adapting" a \c To into a \c T. 1464 /// 1465 /// The \c ArgumentAdapterT argument specifies how the adaptation is done. 1466 /// 1467 /// For example: 1468 /// \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher); 1469 /// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher 1470 /// that is convertible into any matcher of type \c To by constructing 1471 /// \c HasMatcher<To, T>(InnerMatcher). 1472 /// 1473 /// If a matcher does not need knowledge about the inner type, prefer to use 1474 /// PolymorphicMatcher. 1475 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT, 1476 typename FromTypes = AdaptativeDefaultFromTypes, 1477 typename ToTypes = AdaptativeDefaultToTypes> 1478 struct ArgumentAdaptingMatcherFunc { 1479 template <typename T> 1480 static ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes> 1481 create(const Matcher<T> &InnerMatcher) { 1482 return ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>( 1483 InnerMatcher); 1484 } 1485 1486 template <typename T> 1487 ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes> 1488 operator()(const Matcher<T> &InnerMatcher) const { 1489 return create(InnerMatcher); 1490 } 1491 1492 template <typename... T> 1493 ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, 1494 typename GetClade<T...>::Type, ToTypes> 1495 operator()(const MapAnyOfHelper<T...> &InnerMatcher) const { 1496 return create(InnerMatcher.with()); 1497 } 1498 }; 1499 1500 template <typename T> class TraversalMatcher : public MatcherInterface<T> { 1501 DynTypedMatcher InnerMatcher; 1502 clang::TraversalKind Traversal; 1503 1504 public: 1505 explicit TraversalMatcher(clang::TraversalKind TK, 1506 const Matcher<T> &InnerMatcher) 1507 : InnerMatcher(InnerMatcher), Traversal(TK) {} 1508 1509 bool matches(const T &Node, ASTMatchFinder *Finder, 1510 BoundNodesTreeBuilder *Builder) const override { 1511 return this->InnerMatcher.matches(DynTypedNode::create(Node), Finder, 1512 Builder); 1513 } 1514 1515 std::optional<clang::TraversalKind> TraversalKind() const override { 1516 if (auto NestedKind = this->InnerMatcher.getTraversalKind()) 1517 return NestedKind; 1518 return Traversal; 1519 } 1520 }; 1521 1522 template <typename MatcherType> class TraversalWrapper { 1523 public: 1524 TraversalWrapper(TraversalKind TK, const MatcherType &InnerMatcher) 1525 : TK(TK), InnerMatcher(InnerMatcher) {} 1526 1527 template <typename T> operator Matcher<T>() const & { 1528 return internal::DynTypedMatcher::constructRestrictedWrapper( 1529 new internal::TraversalMatcher<T>(TK, InnerMatcher), 1530 ASTNodeKind::getFromNodeKind<T>()) 1531 .template unconditionalConvertTo<T>(); 1532 } 1533 1534 template <typename T> operator Matcher<T>() && { 1535 return internal::DynTypedMatcher::constructRestrictedWrapper( 1536 new internal::TraversalMatcher<T>(TK, std::move(InnerMatcher)), 1537 ASTNodeKind::getFromNodeKind<T>()) 1538 .template unconditionalConvertTo<T>(); 1539 } 1540 1541 private: 1542 TraversalKind TK; 1543 MatcherType InnerMatcher; 1544 }; 1545 1546 /// A PolymorphicMatcher<MatcherT, P1, ..., PN> object can be 1547 /// created from N parameters p1, ..., pN (of type P1, ..., PN) and 1548 /// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN) 1549 /// can be constructed. 1550 /// 1551 /// For example: 1552 /// - PolymorphicMatcher<IsDefinitionMatcher>() 1553 /// creates an object that can be used as a Matcher<T> for any type T 1554 /// where an IsDefinitionMatcher<T>() can be constructed. 1555 /// - PolymorphicMatcher<ValueEqualsMatcher, int>(42) 1556 /// creates an object that can be used as a Matcher<T> for any type T 1557 /// where a ValueEqualsMatcher<T, int>(42) can be constructed. 1558 template <template <typename T, typename... Params> class MatcherT, 1559 typename ReturnTypesF, typename... ParamTypes> 1560 class PolymorphicMatcher { 1561 public: 1562 PolymorphicMatcher(const ParamTypes &... Params) : Params(Params...) {} 1563 1564 using ReturnTypes = typename ExtractFunctionArgMeta<ReturnTypesF>::type; 1565 1566 template <typename T> operator Matcher<T>() const & { 1567 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value, 1568 "right polymorphic conversion"); 1569 return Matcher<T>(new_from_tuple<MatcherT<T, ParamTypes...>>(Params)); 1570 } 1571 1572 template <typename T> operator Matcher<T>() && { 1573 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value, 1574 "right polymorphic conversion"); 1575 return Matcher<T>( 1576 new_from_tuple<MatcherT<T, ParamTypes...>>(std::move(Params))); 1577 } 1578 1579 private: 1580 std::tuple<ParamTypes...> Params; 1581 }; 1582 1583 /// Matches nodes of type T that have child nodes of type ChildT for 1584 /// which a specified child matcher matches. 1585 /// 1586 /// ChildT must be an AST base type. 1587 template <typename T, typename ChildT> 1588 class HasMatcher : public MatcherInterface<T> { 1589 DynTypedMatcher InnerMatcher; 1590 1591 public: 1592 explicit HasMatcher(const Matcher<ChildT> &InnerMatcher) 1593 : InnerMatcher(InnerMatcher) {} 1594 1595 bool matches(const T &Node, ASTMatchFinder *Finder, 1596 BoundNodesTreeBuilder *Builder) const override { 1597 return Finder->matchesChildOf(Node, this->InnerMatcher, Builder, 1598 ASTMatchFinder::BK_First); 1599 } 1600 }; 1601 1602 /// Matches nodes of type T that have child nodes of type ChildT for 1603 /// which a specified child matcher matches. ChildT must be an AST base 1604 /// type. 1605 /// As opposed to the HasMatcher, the ForEachMatcher will produce a match 1606 /// for each child that matches. 1607 template <typename T, typename ChildT> 1608 class ForEachMatcher : public MatcherInterface<T> { 1609 static_assert(IsBaseType<ChildT>::value, 1610 "for each only accepts base type matcher"); 1611 1612 DynTypedMatcher InnerMatcher; 1613 1614 public: 1615 explicit ForEachMatcher(const Matcher<ChildT> &InnerMatcher) 1616 : InnerMatcher(InnerMatcher) {} 1617 1618 bool matches(const T &Node, ASTMatchFinder *Finder, 1619 BoundNodesTreeBuilder *Builder) const override { 1620 return Finder->matchesChildOf( 1621 Node, this->InnerMatcher, Builder, 1622 ASTMatchFinder::BK_All); 1623 } 1624 }; 1625 1626 /// @} 1627 1628 template <typename T> 1629 inline Matcher<T> DynTypedMatcher::unconditionalConvertTo() const { 1630 return Matcher<T>(*this); 1631 } 1632 1633 /// Matches nodes of type T that have at least one descendant node of 1634 /// type DescendantT for which the given inner matcher matches. 1635 /// 1636 /// DescendantT must be an AST base type. 1637 template <typename T, typename DescendantT> 1638 class HasDescendantMatcher : public MatcherInterface<T> { 1639 static_assert(IsBaseType<DescendantT>::value, 1640 "has descendant only accepts base type matcher"); 1641 1642 DynTypedMatcher DescendantMatcher; 1643 1644 public: 1645 explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher) 1646 : DescendantMatcher(DescendantMatcher) {} 1647 1648 bool matches(const T &Node, ASTMatchFinder *Finder, 1649 BoundNodesTreeBuilder *Builder) const override { 1650 return Finder->matchesDescendantOf(Node, this->DescendantMatcher, Builder, 1651 ASTMatchFinder::BK_First); 1652 } 1653 }; 1654 1655 /// Matches nodes of type \c T that have a parent node of type \c ParentT 1656 /// for which the given inner matcher matches. 1657 /// 1658 /// \c ParentT must be an AST base type. 1659 template <typename T, typename ParentT> 1660 class HasParentMatcher : public MatcherInterface<T> { 1661 static_assert(IsBaseType<ParentT>::value, 1662 "has parent only accepts base type matcher"); 1663 1664 DynTypedMatcher ParentMatcher; 1665 1666 public: 1667 explicit HasParentMatcher(const Matcher<ParentT> &ParentMatcher) 1668 : ParentMatcher(ParentMatcher) {} 1669 1670 bool matches(const T &Node, ASTMatchFinder *Finder, 1671 BoundNodesTreeBuilder *Builder) const override { 1672 return Finder->matchesAncestorOf(Node, this->ParentMatcher, Builder, 1673 ASTMatchFinder::AMM_ParentOnly); 1674 } 1675 }; 1676 1677 /// Matches nodes of type \c T that have at least one ancestor node of 1678 /// type \c AncestorT for which the given inner matcher matches. 1679 /// 1680 /// \c AncestorT must be an AST base type. 1681 template <typename T, typename AncestorT> 1682 class HasAncestorMatcher : public MatcherInterface<T> { 1683 static_assert(IsBaseType<AncestorT>::value, 1684 "has ancestor only accepts base type matcher"); 1685 1686 DynTypedMatcher AncestorMatcher; 1687 1688 public: 1689 explicit HasAncestorMatcher(const Matcher<AncestorT> &AncestorMatcher) 1690 : AncestorMatcher(AncestorMatcher) {} 1691 1692 bool matches(const T &Node, ASTMatchFinder *Finder, 1693 BoundNodesTreeBuilder *Builder) const override { 1694 return Finder->matchesAncestorOf(Node, this->AncestorMatcher, Builder, 1695 ASTMatchFinder::AMM_All); 1696 } 1697 }; 1698 1699 /// Matches nodes of type T that have at least one descendant node of 1700 /// type DescendantT for which the given inner matcher matches. 1701 /// 1702 /// DescendantT must be an AST base type. 1703 /// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match 1704 /// for each descendant node that matches instead of only for the first. 1705 template <typename T, typename DescendantT> 1706 class ForEachDescendantMatcher : public MatcherInterface<T> { 1707 static_assert(IsBaseType<DescendantT>::value, 1708 "for each descendant only accepts base type matcher"); 1709 1710 DynTypedMatcher DescendantMatcher; 1711 1712 public: 1713 explicit ForEachDescendantMatcher( 1714 const Matcher<DescendantT> &DescendantMatcher) 1715 : DescendantMatcher(DescendantMatcher) {} 1716 1717 bool matches(const T &Node, ASTMatchFinder *Finder, 1718 BoundNodesTreeBuilder *Builder) const override { 1719 return Finder->matchesDescendantOf(Node, this->DescendantMatcher, Builder, 1720 ASTMatchFinder::BK_All); 1721 } 1722 }; 1723 1724 /// Matches on nodes that have a getValue() method if getValue() equals 1725 /// the value the ValueEqualsMatcher was constructed with. 1726 template <typename T, typename ValueT> 1727 class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> { 1728 static_assert(std::is_base_of<CharacterLiteral, T>::value || 1729 std::is_base_of<CXXBoolLiteralExpr, T>::value || 1730 std::is_base_of<FloatingLiteral, T>::value || 1731 std::is_base_of<IntegerLiteral, T>::value || 1732 std::is_base_of<FixedPointLiteral, T>::value, 1733 "the node must have a getValue method"); 1734 1735 public: 1736 explicit ValueEqualsMatcher(const ValueT &ExpectedValue) 1737 : ExpectedValue(ExpectedValue) {} 1738 1739 bool matchesNode(const T &Node) const override { 1740 return Node.getValue() == ExpectedValue; 1741 } 1742 1743 private: 1744 ValueT ExpectedValue; 1745 }; 1746 1747 /// Template specializations to easily write matchers for floating point 1748 /// literals. 1749 template <> 1750 inline bool ValueEqualsMatcher<FloatingLiteral, double>::matchesNode( 1751 const FloatingLiteral &Node) const { 1752 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle()) 1753 return Node.getValue().convertToFloat() == ExpectedValue; 1754 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble()) 1755 return Node.getValue().convertToDouble() == ExpectedValue; 1756 return false; 1757 } 1758 template <> 1759 inline bool ValueEqualsMatcher<FloatingLiteral, float>::matchesNode( 1760 const FloatingLiteral &Node) const { 1761 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle()) 1762 return Node.getValue().convertToFloat() == ExpectedValue; 1763 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble()) 1764 return Node.getValue().convertToDouble() == ExpectedValue; 1765 return false; 1766 } 1767 template <> 1768 inline bool ValueEqualsMatcher<FloatingLiteral, llvm::APFloat>::matchesNode( 1769 const FloatingLiteral &Node) const { 1770 return ExpectedValue.compare(Node.getValue()) == llvm::APFloat::cmpEqual; 1771 } 1772 1773 /// Matches nodes of type \c TLoc for which the inner 1774 /// \c Matcher<T> matches. 1775 template <typename TLoc, typename T> 1776 class LocMatcher : public MatcherInterface<TLoc> { 1777 DynTypedMatcher InnerMatcher; 1778 1779 public: 1780 explicit LocMatcher(const Matcher<T> &InnerMatcher) 1781 : InnerMatcher(InnerMatcher) {} 1782 1783 bool matches(const TLoc &Node, ASTMatchFinder *Finder, 1784 BoundNodesTreeBuilder *Builder) const override { 1785 if (!Node) 1786 return false; 1787 return this->InnerMatcher.matches(extract(Node), Finder, Builder); 1788 } 1789 1790 private: 1791 static DynTypedNode extract(const NestedNameSpecifierLoc &Loc) { 1792 return DynTypedNode::create(*Loc.getNestedNameSpecifier()); 1793 } 1794 }; 1795 1796 /// Matches \c TypeLocs based on an inner matcher matching a certain 1797 /// \c QualType. 1798 /// 1799 /// Used to implement the \c loc() matcher. 1800 class TypeLocTypeMatcher : public MatcherInterface<TypeLoc> { 1801 Matcher<QualType> InnerMatcher; 1802 1803 public: 1804 explicit TypeLocTypeMatcher(const Matcher<QualType> &InnerMatcher) 1805 : InnerMatcher(InnerMatcher) {} 1806 1807 bool matches(const TypeLoc &Node, ASTMatchFinder *Finder, 1808 BoundNodesTreeBuilder *Builder) const override { 1809 if (!Node) 1810 return false; 1811 return this->InnerMatcher.matches(Node.getType(), Finder, Builder); 1812 } 1813 }; 1814 1815 /// Matches nodes of type \c T for which the inner matcher matches on a 1816 /// another node of type \c T that can be reached using a given traverse 1817 /// function. 1818 template <typename T> class TypeTraverseMatcher : public MatcherInterface<T> { 1819 DynTypedMatcher InnerMatcher; 1820 1821 public: 1822 explicit TypeTraverseMatcher(const Matcher<QualType> &InnerMatcher, 1823 QualType (T::*TraverseFunction)() const) 1824 : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {} 1825 1826 bool matches(const T &Node, ASTMatchFinder *Finder, 1827 BoundNodesTreeBuilder *Builder) const override { 1828 QualType NextNode = (Node.*TraverseFunction)(); 1829 if (NextNode.isNull()) 1830 return false; 1831 return this->InnerMatcher.matches(DynTypedNode::create(NextNode), Finder, 1832 Builder); 1833 } 1834 1835 private: 1836 QualType (T::*TraverseFunction)() const; 1837 }; 1838 1839 /// Matches nodes of type \c T in a ..Loc hierarchy, for which the inner 1840 /// matcher matches on a another node of type \c T that can be reached using a 1841 /// given traverse function. 1842 template <typename T> 1843 class TypeLocTraverseMatcher : public MatcherInterface<T> { 1844 DynTypedMatcher InnerMatcher; 1845 1846 public: 1847 explicit TypeLocTraverseMatcher(const Matcher<TypeLoc> &InnerMatcher, 1848 TypeLoc (T::*TraverseFunction)() const) 1849 : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {} 1850 1851 bool matches(const T &Node, ASTMatchFinder *Finder, 1852 BoundNodesTreeBuilder *Builder) const override { 1853 TypeLoc NextNode = (Node.*TraverseFunction)(); 1854 if (!NextNode) 1855 return false; 1856 return this->InnerMatcher.matches(DynTypedNode::create(NextNode), Finder, 1857 Builder); 1858 } 1859 1860 private: 1861 TypeLoc (T::*TraverseFunction)() const; 1862 }; 1863 1864 /// Converts a \c Matcher<InnerT> to a \c Matcher<OuterT>, where 1865 /// \c OuterT is any type that is supported by \c Getter. 1866 /// 1867 /// \code Getter<OuterT>::value() \endcode returns a 1868 /// \code InnerTBase (OuterT::*)() \endcode, which is used to adapt a \c OuterT 1869 /// object into a \c InnerT 1870 template <typename InnerTBase, 1871 template <typename OuterT> class Getter, 1872 template <typename OuterT> class MatcherImpl, 1873 typename ReturnTypesF> 1874 class TypeTraversePolymorphicMatcher { 1875 private: 1876 using Self = TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl, 1877 ReturnTypesF>; 1878 1879 static Self create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers); 1880 1881 public: 1882 using ReturnTypes = typename ExtractFunctionArgMeta<ReturnTypesF>::type; 1883 1884 explicit TypeTraversePolymorphicMatcher( 1885 ArrayRef<const Matcher<InnerTBase> *> InnerMatchers) 1886 : InnerMatcher(makeAllOfComposite(InnerMatchers)) {} 1887 1888 template <typename OuterT> operator Matcher<OuterT>() const { 1889 return Matcher<OuterT>( 1890 new MatcherImpl<OuterT>(InnerMatcher, Getter<OuterT>::value())); 1891 } 1892 1893 struct Func 1894 : public VariadicFunction<Self, Matcher<InnerTBase>, &Self::create> { 1895 Func() {} 1896 }; 1897 1898 private: 1899 Matcher<InnerTBase> InnerMatcher; 1900 }; 1901 1902 /// A simple memoizer of T(*)() functions. 1903 /// 1904 /// It will call the passed 'Func' template parameter at most once. 1905 /// Used to support AST_MATCHER_FUNCTION() macro. 1906 template <typename Matcher, Matcher (*Func)()> class MemoizedMatcher { 1907 struct Wrapper { 1908 Wrapper() : M(Func()) {} 1909 1910 Matcher M; 1911 }; 1912 1913 public: 1914 static const Matcher &getInstance() { 1915 static llvm::ManagedStatic<Wrapper> Instance; 1916 return Instance->M; 1917 } 1918 }; 1919 1920 // Define the create() method out of line to silence a GCC warning about 1921 // the struct "Func" having greater visibility than its base, which comes from 1922 // using the flag -fvisibility-inlines-hidden. 1923 template <typename InnerTBase, template <typename OuterT> class Getter, 1924 template <typename OuterT> class MatcherImpl, typename ReturnTypesF> 1925 TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl, ReturnTypesF> 1926 TypeTraversePolymorphicMatcher< 1927 InnerTBase, Getter, MatcherImpl, 1928 ReturnTypesF>::create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers) { 1929 return Self(InnerMatchers); 1930 } 1931 1932 // FIXME: unify ClassTemplateSpecializationDecl and TemplateSpecializationType's 1933 // APIs for accessing the template argument list. 1934 inline ArrayRef<TemplateArgument> 1935 getTemplateSpecializationArgs(const ClassTemplateSpecializationDecl &D) { 1936 return D.getTemplateArgs().asArray(); 1937 } 1938 1939 inline ArrayRef<TemplateArgument> 1940 getTemplateSpecializationArgs(const VarTemplateSpecializationDecl &D) { 1941 return D.getTemplateArgs().asArray(); 1942 } 1943 1944 inline ArrayRef<TemplateArgument> 1945 getTemplateSpecializationArgs(const TemplateSpecializationType &T) { 1946 return T.template_arguments(); 1947 } 1948 1949 inline ArrayRef<TemplateArgument> 1950 getTemplateSpecializationArgs(const FunctionDecl &FD) { 1951 if (const auto* TemplateArgs = FD.getTemplateSpecializationArgs()) 1952 return TemplateArgs->asArray(); 1953 return {}; 1954 } 1955 1956 inline ArrayRef<TemplateArgumentLoc> 1957 getTemplateArgsWritten(const ClassTemplateSpecializationDecl &D) { 1958 if (const ASTTemplateArgumentListInfo *Args = D.getTemplateArgsAsWritten()) 1959 return Args->arguments(); 1960 return {}; 1961 } 1962 1963 inline ArrayRef<TemplateArgumentLoc> 1964 getTemplateArgsWritten(const VarTemplateSpecializationDecl &D) { 1965 if (const ASTTemplateArgumentListInfo *Args = D.getTemplateArgsAsWritten()) 1966 return Args->arguments(); 1967 return {}; 1968 } 1969 1970 inline ArrayRef<TemplateArgumentLoc> 1971 getTemplateArgsWritten(const FunctionDecl &FD) { 1972 if (const auto *Args = FD.getTemplateSpecializationArgsAsWritten()) 1973 return Args->arguments(); 1974 return {}; 1975 } 1976 1977 inline ArrayRef<TemplateArgumentLoc> 1978 getTemplateArgsWritten(const DeclRefExpr &DRE) { 1979 if (const auto *Args = DRE.getTemplateArgs()) 1980 return {Args, DRE.getNumTemplateArgs()}; 1981 return {}; 1982 } 1983 1984 inline SmallVector<TemplateArgumentLoc> 1985 getTemplateArgsWritten(const TemplateSpecializationTypeLoc &T) { 1986 SmallVector<TemplateArgumentLoc> Args; 1987 if (!T.isNull()) { 1988 Args.reserve(T.getNumArgs()); 1989 for (unsigned I = 0; I < T.getNumArgs(); ++I) 1990 Args.emplace_back(T.getArgLoc(I)); 1991 } 1992 return Args; 1993 } 1994 1995 struct NotEqualsBoundNodePredicate { 1996 bool operator()(const internal::BoundNodesMap &Nodes) const { 1997 return Nodes.getNode(ID) != Node; 1998 } 1999 2000 std::string ID; 2001 DynTypedNode Node; 2002 }; 2003 2004 template <typename Ty, typename Enable = void> struct GetBodyMatcher { 2005 static const Stmt *get(const Ty &Node) { return Node.getBody(); } 2006 }; 2007 2008 template <typename Ty> 2009 struct GetBodyMatcher< 2010 Ty, std::enable_if_t<std::is_base_of<FunctionDecl, Ty>::value>> { 2011 static const Stmt *get(const Ty &Node) { 2012 return Node.doesThisDeclarationHaveABody() ? Node.getBody() : nullptr; 2013 } 2014 }; 2015 2016 template <typename NodeType> 2017 inline std::optional<BinaryOperatorKind> 2018 equivalentBinaryOperator(const NodeType &Node) { 2019 return Node.getOpcode(); 2020 } 2021 2022 template <> 2023 inline std::optional<BinaryOperatorKind> 2024 equivalentBinaryOperator<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) { 2025 if (Node.getNumArgs() != 2) 2026 return std::nullopt; 2027 switch (Node.getOperator()) { 2028 default: 2029 return std::nullopt; 2030 case OO_ArrowStar: 2031 return BO_PtrMemI; 2032 case OO_Star: 2033 return BO_Mul; 2034 case OO_Slash: 2035 return BO_Div; 2036 case OO_Percent: 2037 return BO_Rem; 2038 case OO_Plus: 2039 return BO_Add; 2040 case OO_Minus: 2041 return BO_Sub; 2042 case OO_LessLess: 2043 return BO_Shl; 2044 case OO_GreaterGreater: 2045 return BO_Shr; 2046 case OO_Spaceship: 2047 return BO_Cmp; 2048 case OO_Less: 2049 return BO_LT; 2050 case OO_Greater: 2051 return BO_GT; 2052 case OO_LessEqual: 2053 return BO_LE; 2054 case OO_GreaterEqual: 2055 return BO_GE; 2056 case OO_EqualEqual: 2057 return BO_EQ; 2058 case OO_ExclaimEqual: 2059 return BO_NE; 2060 case OO_Amp: 2061 return BO_And; 2062 case OO_Caret: 2063 return BO_Xor; 2064 case OO_Pipe: 2065 return BO_Or; 2066 case OO_AmpAmp: 2067 return BO_LAnd; 2068 case OO_PipePipe: 2069 return BO_LOr; 2070 case OO_Equal: 2071 return BO_Assign; 2072 case OO_StarEqual: 2073 return BO_MulAssign; 2074 case OO_SlashEqual: 2075 return BO_DivAssign; 2076 case OO_PercentEqual: 2077 return BO_RemAssign; 2078 case OO_PlusEqual: 2079 return BO_AddAssign; 2080 case OO_MinusEqual: 2081 return BO_SubAssign; 2082 case OO_LessLessEqual: 2083 return BO_ShlAssign; 2084 case OO_GreaterGreaterEqual: 2085 return BO_ShrAssign; 2086 case OO_AmpEqual: 2087 return BO_AndAssign; 2088 case OO_CaretEqual: 2089 return BO_XorAssign; 2090 case OO_PipeEqual: 2091 return BO_OrAssign; 2092 case OO_Comma: 2093 return BO_Comma; 2094 } 2095 } 2096 2097 template <typename NodeType> 2098 inline std::optional<UnaryOperatorKind> 2099 equivalentUnaryOperator(const NodeType &Node) { 2100 return Node.getOpcode(); 2101 } 2102 2103 template <> 2104 inline std::optional<UnaryOperatorKind> 2105 equivalentUnaryOperator<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) { 2106 if (Node.getNumArgs() != 1 && Node.getOperator() != OO_PlusPlus && 2107 Node.getOperator() != OO_MinusMinus) 2108 return std::nullopt; 2109 switch (Node.getOperator()) { 2110 default: 2111 return std::nullopt; 2112 case OO_Plus: 2113 return UO_Plus; 2114 case OO_Minus: 2115 return UO_Minus; 2116 case OO_Amp: 2117 return UO_AddrOf; 2118 case OO_Star: 2119 return UO_Deref; 2120 case OO_Tilde: 2121 return UO_Not; 2122 case OO_Exclaim: 2123 return UO_LNot; 2124 case OO_PlusPlus: { 2125 const auto *FD = Node.getDirectCallee(); 2126 if (!FD) 2127 return std::nullopt; 2128 return FD->getNumParams() > 0 ? UO_PostInc : UO_PreInc; 2129 } 2130 case OO_MinusMinus: { 2131 const auto *FD = Node.getDirectCallee(); 2132 if (!FD) 2133 return std::nullopt; 2134 return FD->getNumParams() > 0 ? UO_PostDec : UO_PreDec; 2135 } 2136 case OO_Coawait: 2137 return UO_Coawait; 2138 } 2139 } 2140 2141 template <typename NodeType> inline const Expr *getLHS(const NodeType &Node) { 2142 return Node.getLHS(); 2143 } 2144 template <> 2145 inline const Expr * 2146 getLHS<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) { 2147 if (!internal::equivalentBinaryOperator(Node)) 2148 return nullptr; 2149 return Node.getArg(0); 2150 } 2151 template <typename NodeType> inline const Expr *getRHS(const NodeType &Node) { 2152 return Node.getRHS(); 2153 } 2154 template <> 2155 inline const Expr * 2156 getRHS<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) { 2157 if (!internal::equivalentBinaryOperator(Node)) 2158 return nullptr; 2159 return Node.getArg(1); 2160 } 2161 template <typename NodeType> 2162 inline const Expr *getSubExpr(const NodeType &Node) { 2163 return Node.getSubExpr(); 2164 } 2165 template <> 2166 inline const Expr * 2167 getSubExpr<CXXOperatorCallExpr>(const CXXOperatorCallExpr &Node) { 2168 if (!internal::equivalentUnaryOperator(Node) && 2169 Node.getOperator() != OO_Arrow) { 2170 return nullptr; 2171 } 2172 return Node.getArg(0); 2173 } 2174 2175 template <typename Ty> 2176 struct HasSizeMatcher { 2177 static bool hasSize(const Ty &Node, unsigned int N) { 2178 return Node.getSize() == N; 2179 } 2180 }; 2181 2182 template <> 2183 inline bool HasSizeMatcher<StringLiteral>::hasSize( 2184 const StringLiteral &Node, unsigned int N) { 2185 return Node.getLength() == N; 2186 } 2187 2188 template <typename Ty> 2189 struct GetSourceExpressionMatcher { 2190 static const Expr *get(const Ty &Node) { 2191 return Node.getSubExpr(); 2192 } 2193 }; 2194 2195 template <> 2196 inline const Expr *GetSourceExpressionMatcher<OpaqueValueExpr>::get( 2197 const OpaqueValueExpr &Node) { 2198 return Node.getSourceExpr(); 2199 } 2200 2201 template <typename Ty> 2202 struct CompoundStmtMatcher { 2203 static const CompoundStmt *get(const Ty &Node) { 2204 return &Node; 2205 } 2206 }; 2207 2208 template <> 2209 inline const CompoundStmt * 2210 CompoundStmtMatcher<StmtExpr>::get(const StmtExpr &Node) { 2211 return Node.getSubStmt(); 2212 } 2213 2214 /// If \p Loc is (transitively) expanded from macro \p MacroName, returns the 2215 /// location (in the chain of expansions) at which \p MacroName was 2216 /// expanded. Since the macro may have been expanded inside a series of 2217 /// expansions, that location may itself be a MacroID. 2218 std::optional<SourceLocation> getExpansionLocOfMacro(StringRef MacroName, 2219 SourceLocation Loc, 2220 const ASTContext &Context); 2221 2222 inline std::optional<StringRef> getOpName(const UnaryOperator &Node) { 2223 return Node.getOpcodeStr(Node.getOpcode()); 2224 } 2225 inline std::optional<StringRef> getOpName(const BinaryOperator &Node) { 2226 return Node.getOpcodeStr(); 2227 } 2228 inline StringRef getOpName(const CXXRewrittenBinaryOperator &Node) { 2229 return Node.getOpcodeStr(); 2230 } 2231 inline std::optional<StringRef> getOpName(const CXXOperatorCallExpr &Node) { 2232 if (const char *Str = getOperatorSpelling(Node.getOperator())) 2233 return Str; 2234 return std::nullopt; 2235 } 2236 inline StringRef getOpName(const CXXFoldExpr &Node) { 2237 return BinaryOperator::getOpcodeStr(Node.getOperator()); 2238 } 2239 2240 /// Matches overloaded operators with a specific name. 2241 /// 2242 /// The type argument ArgT is not used by this matcher but is used by 2243 /// PolymorphicMatcher and should be std::vector<std::string>>. 2244 template <typename T, typename ArgT = std::vector<std::string>> 2245 class HasAnyOperatorNameMatcher : public SingleNodeMatcherInterface<T> { 2246 static_assert(std::is_same<T, BinaryOperator>::value || 2247 std::is_same<T, CXXOperatorCallExpr>::value || 2248 std::is_same<T, CXXRewrittenBinaryOperator>::value || 2249 std::is_same<T, UnaryOperator>::value, 2250 "Matcher only supports `BinaryOperator`, `UnaryOperator`, " 2251 "`CXXOperatorCallExpr` and `CXXRewrittenBinaryOperator`"); 2252 static_assert(std::is_same<ArgT, std::vector<std::string>>::value, 2253 "Matcher ArgT must be std::vector<std::string>"); 2254 2255 public: 2256 explicit HasAnyOperatorNameMatcher(std::vector<std::string> Names) 2257 : SingleNodeMatcherInterface<T>(), Names(std::move(Names)) {} 2258 2259 bool matchesNode(const T &Node) const override { 2260 std::optional<StringRef> OptOpName = getOpName(Node); 2261 return OptOpName && llvm::is_contained(Names, *OptOpName); 2262 } 2263 2264 private: 2265 static std::optional<StringRef> getOpName(const UnaryOperator &Node) { 2266 return Node.getOpcodeStr(Node.getOpcode()); 2267 } 2268 static std::optional<StringRef> getOpName(const BinaryOperator &Node) { 2269 return Node.getOpcodeStr(); 2270 } 2271 static StringRef getOpName(const CXXRewrittenBinaryOperator &Node) { 2272 return Node.getOpcodeStr(); 2273 } 2274 static std::optional<StringRef> getOpName(const CXXOperatorCallExpr &Node) { 2275 if (const char *Str = getOperatorSpelling(Node.getOperator())) 2276 return Str; 2277 return std::nullopt; 2278 } 2279 2280 std::vector<std::string> Names; 2281 }; 2282 2283 using HasOpNameMatcher = 2284 PolymorphicMatcher<HasAnyOperatorNameMatcher, 2285 void( 2286 TypeList<BinaryOperator, CXXOperatorCallExpr, 2287 CXXRewrittenBinaryOperator, UnaryOperator>), 2288 std::vector<std::string>>; 2289 2290 HasOpNameMatcher hasAnyOperatorNameFunc(ArrayRef<const StringRef *> NameRefs); 2291 2292 using HasOverloadOpNameMatcher = 2293 PolymorphicMatcher<HasOverloadedOperatorNameMatcher, 2294 void(TypeList<CXXOperatorCallExpr, FunctionDecl>), 2295 std::vector<std::string>>; 2296 2297 HasOverloadOpNameMatcher 2298 hasAnyOverloadedOperatorNameFunc(ArrayRef<const StringRef *> NameRefs); 2299 2300 /// Returns true if \p Node has a base specifier matching \p BaseSpec. 2301 /// 2302 /// A class is not considered to be derived from itself. 2303 bool matchesAnyBase(const CXXRecordDecl &Node, 2304 const Matcher<CXXBaseSpecifier> &BaseSpecMatcher, 2305 ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder); 2306 2307 std::shared_ptr<llvm::Regex> createAndVerifyRegex(StringRef Regex, 2308 llvm::Regex::RegexFlags Flags, 2309 StringRef MatcherID); 2310 2311 inline bool 2312 MatchTemplateArgLocAt(const DeclRefExpr &Node, unsigned int Index, 2313 internal::Matcher<TemplateArgumentLoc> InnerMatcher, 2314 internal::ASTMatchFinder *Finder, 2315 internal::BoundNodesTreeBuilder *Builder) { 2316 llvm::ArrayRef<TemplateArgumentLoc> ArgLocs = Node.template_arguments(); 2317 return Index < ArgLocs.size() && 2318 InnerMatcher.matches(ArgLocs[Index], Finder, Builder); 2319 } 2320 2321 inline bool 2322 MatchTemplateArgLocAt(const TemplateSpecializationTypeLoc &Node, 2323 unsigned int Index, 2324 internal::Matcher<TemplateArgumentLoc> InnerMatcher, 2325 internal::ASTMatchFinder *Finder, 2326 internal::BoundNodesTreeBuilder *Builder) { 2327 return !Node.isNull() && Index < Node.getNumArgs() && 2328 InnerMatcher.matches(Node.getArgLoc(Index), Finder, Builder); 2329 } 2330 2331 inline std::string getDependentName(const DependentScopeDeclRefExpr &node) { 2332 return node.getDeclName().getAsString(); 2333 } 2334 2335 inline std::string getDependentName(const DependentNameType &node) { 2336 return node.getIdentifier()->getName().str(); 2337 } 2338 2339 } // namespace internal 2340 2341 } // namespace ast_matchers 2342 2343 } // namespace clang 2344 2345 #endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERSINTERNAL_H 2346