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