1 //===--- ASTMatchFinder.cpp - Structural query framework ------------------===// 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 an algorithm to efficiently search for matches on AST nodes. 10 // Uses memoization to support recursive matches like HasDescendant. 11 // 12 // The general idea is to visit all AST nodes with a RecursiveASTVisitor, 13 // calling the Matches(...) method of each matcher we are running on each 14 // AST node. The matcher can recurse via the ASTMatchFinder interface. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "clang/ASTMatchers/ASTMatchFinder.h" 19 #include "clang/AST/ASTConsumer.h" 20 #include "clang/AST/ASTContext.h" 21 #include "clang/AST/RecursiveASTVisitor.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/StringMap.h" 24 #include "llvm/Support/Timer.h" 25 #include <deque> 26 #include <memory> 27 #include <set> 28 29 namespace clang { 30 namespace ast_matchers { 31 namespace internal { 32 namespace { 33 34 typedef MatchFinder::MatchCallback MatchCallback; 35 36 // The maximum number of memoization entries to store. 37 // 10k has been experimentally found to give a good trade-off 38 // of performance vs. memory consumption by running matcher 39 // that match on every statement over a very large codebase. 40 // 41 // FIXME: Do some performance optimization in general and 42 // revisit this number; also, put up micro-benchmarks that we can 43 // optimize this on. 44 static const unsigned MaxMemoizationEntries = 10000; 45 46 enum class MatchType { 47 Ancestors, 48 49 Descendants, 50 Child, 51 }; 52 53 // We use memoization to avoid running the same matcher on the same 54 // AST node twice. This struct is the key for looking up match 55 // result. It consists of an ID of the MatcherInterface (for 56 // identifying the matcher), a pointer to the AST node and the 57 // bound nodes before the matcher was executed. 58 // 59 // We currently only memoize on nodes whose pointers identify the 60 // nodes (\c Stmt and \c Decl, but not \c QualType or \c TypeLoc). 61 // For \c QualType and \c TypeLoc it is possible to implement 62 // generation of keys for each type. 63 // FIXME: Benchmark whether memoization of non-pointer typed nodes 64 // provides enough benefit for the additional amount of code. 65 struct MatchKey { 66 DynTypedMatcher::MatcherIDType MatcherID; 67 DynTypedNode Node; 68 BoundNodesTreeBuilder BoundNodes; 69 TraversalKind Traversal = TK_AsIs; 70 MatchType Type; 71 72 bool operator<(const MatchKey &Other) const { 73 return std::tie(Traversal, Type, MatcherID, Node, BoundNodes) < 74 std::tie(Other.Traversal, Other.Type, Other.MatcherID, Other.Node, 75 Other.BoundNodes); 76 } 77 }; 78 79 // Used to store the result of a match and possibly bound nodes. 80 struct MemoizedMatchResult { 81 bool ResultOfMatch; 82 BoundNodesTreeBuilder Nodes; 83 }; 84 85 // A RecursiveASTVisitor that traverses all children or all descendants of 86 // a node. 87 class MatchChildASTVisitor 88 : public RecursiveASTVisitor<MatchChildASTVisitor> { 89 public: 90 typedef RecursiveASTVisitor<MatchChildASTVisitor> VisitorBase; 91 92 // Creates an AST visitor that matches 'matcher' on all children or 93 // descendants of a traversed node. max_depth is the maximum depth 94 // to traverse: use 1 for matching the children and INT_MAX for 95 // matching the descendants. 96 MatchChildASTVisitor(const DynTypedMatcher *Matcher, ASTMatchFinder *Finder, 97 BoundNodesTreeBuilder *Builder, int MaxDepth, 98 TraversalKind Traversal, ASTMatchFinder::BindKind Bind) 99 : Matcher(Matcher), Finder(Finder), Builder(Builder), CurrentDepth(0), 100 MaxDepth(MaxDepth), Traversal(Traversal), Bind(Bind), Matches(false) {} 101 102 // Returns true if a match is found in the subtree rooted at the 103 // given AST node. This is done via a set of mutually recursive 104 // functions. Here's how the recursion is done (the *wildcard can 105 // actually be Decl, Stmt, or Type): 106 // 107 // - Traverse(node) calls BaseTraverse(node) when it needs 108 // to visit the descendants of node. 109 // - BaseTraverse(node) then calls (via VisitorBase::Traverse*(node)) 110 // Traverse*(c) for each child c of 'node'. 111 // - Traverse*(c) in turn calls Traverse(c), completing the 112 // recursion. 113 bool findMatch(const DynTypedNode &DynNode) { 114 reset(); 115 if (const Decl *D = DynNode.get<Decl>()) 116 traverse(*D); 117 else if (const Stmt *S = DynNode.get<Stmt>()) 118 traverse(*S); 119 else if (const NestedNameSpecifier *NNS = 120 DynNode.get<NestedNameSpecifier>()) 121 traverse(*NNS); 122 else if (const NestedNameSpecifierLoc *NNSLoc = 123 DynNode.get<NestedNameSpecifierLoc>()) 124 traverse(*NNSLoc); 125 else if (const QualType *Q = DynNode.get<QualType>()) 126 traverse(*Q); 127 else if (const TypeLoc *T = DynNode.get<TypeLoc>()) 128 traverse(*T); 129 else if (const auto *C = DynNode.get<CXXCtorInitializer>()) 130 traverse(*C); 131 else if (const TemplateArgumentLoc *TALoc = 132 DynNode.get<TemplateArgumentLoc>()) 133 traverse(*TALoc); 134 // FIXME: Add other base types after adding tests. 135 136 // It's OK to always overwrite the bound nodes, as if there was 137 // no match in this recursive branch, the result set is empty 138 // anyway. 139 *Builder = ResultBindings; 140 141 return Matches; 142 } 143 144 // The following are overriding methods from the base visitor class. 145 // They are public only to allow CRTP to work. They are *not *part 146 // of the public API of this class. 147 bool TraverseDecl(Decl *DeclNode) { 148 ScopedIncrement ScopedDepth(&CurrentDepth); 149 return (DeclNode == nullptr) || traverse(*DeclNode); 150 } 151 152 Stmt *getStmtToTraverse(Stmt *StmtNode) { 153 Stmt *StmtToTraverse = StmtNode; 154 if (auto *ExprNode = dyn_cast_or_null<Expr>(StmtNode)) { 155 auto *LambdaNode = dyn_cast_or_null<LambdaExpr>(StmtNode); 156 if (LambdaNode && 157 Finder->getASTContext().getParentMapContext().getTraversalKind() == 158 TK_IgnoreUnlessSpelledInSource) 159 StmtToTraverse = LambdaNode; 160 else 161 StmtToTraverse = 162 Finder->getASTContext().getParentMapContext().traverseIgnored( 163 ExprNode); 164 } 165 if (Traversal == TraversalKind::TK_IgnoreImplicitCastsAndParentheses) { 166 if (Expr *ExprNode = dyn_cast_or_null<Expr>(StmtNode)) 167 StmtToTraverse = ExprNode->IgnoreParenImpCasts(); 168 } 169 return StmtToTraverse; 170 } 171 172 bool TraverseStmt(Stmt *StmtNode, DataRecursionQueue *Queue = nullptr) { 173 // If we need to keep track of the depth, we can't perform data recursion. 174 if (CurrentDepth == 0 || (CurrentDepth <= MaxDepth && MaxDepth < INT_MAX)) 175 Queue = nullptr; 176 177 ScopedIncrement ScopedDepth(&CurrentDepth); 178 Stmt *StmtToTraverse = getStmtToTraverse(StmtNode); 179 if (!StmtToTraverse) 180 return true; 181 if (!match(*StmtToTraverse)) 182 return false; 183 return VisitorBase::TraverseStmt(StmtToTraverse, Queue); 184 } 185 // We assume that the QualType and the contained type are on the same 186 // hierarchy level. Thus, we try to match either of them. 187 bool TraverseType(QualType TypeNode) { 188 if (TypeNode.isNull()) 189 return true; 190 ScopedIncrement ScopedDepth(&CurrentDepth); 191 // Match the Type. 192 if (!match(*TypeNode)) 193 return false; 194 // The QualType is matched inside traverse. 195 return traverse(TypeNode); 196 } 197 // We assume that the TypeLoc, contained QualType and contained Type all are 198 // on the same hierarchy level. Thus, we try to match all of them. 199 bool TraverseTypeLoc(TypeLoc TypeLocNode) { 200 if (TypeLocNode.isNull()) 201 return true; 202 ScopedIncrement ScopedDepth(&CurrentDepth); 203 // Match the Type. 204 if (!match(*TypeLocNode.getType())) 205 return false; 206 // Match the QualType. 207 if (!match(TypeLocNode.getType())) 208 return false; 209 // The TypeLoc is matched inside traverse. 210 return traverse(TypeLocNode); 211 } 212 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) { 213 ScopedIncrement ScopedDepth(&CurrentDepth); 214 return (NNS == nullptr) || traverse(*NNS); 215 } 216 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) { 217 if (!NNS) 218 return true; 219 ScopedIncrement ScopedDepth(&CurrentDepth); 220 if (!match(*NNS.getNestedNameSpecifier())) 221 return false; 222 return traverse(NNS); 223 } 224 bool TraverseConstructorInitializer(CXXCtorInitializer *CtorInit) { 225 if (!CtorInit) 226 return true; 227 ScopedIncrement ScopedDepth(&CurrentDepth); 228 return traverse(*CtorInit); 229 } 230 bool TraverseTemplateArgumentLoc(TemplateArgumentLoc TAL) { 231 ScopedIncrement ScopedDepth(&CurrentDepth); 232 return traverse(TAL); 233 } 234 bool TraverseLambdaExpr(LambdaExpr *Node) { 235 if (Finder->getASTContext().getParentMapContext().getTraversalKind() != 236 TK_IgnoreUnlessSpelledInSource) 237 return VisitorBase::TraverseLambdaExpr(Node); 238 if (!Node) 239 return true; 240 ScopedIncrement ScopedDepth(&CurrentDepth); 241 242 for (unsigned I = 0, N = Node->capture_size(); I != N; ++I) { 243 const auto *C = Node->capture_begin() + I; 244 if (!C->isExplicit()) 245 continue; 246 if (Node->isInitCapture(C) && !match(*C->getCapturedVar())) 247 return false; 248 if (!match(*Node->capture_init_begin()[I])) 249 return false; 250 } 251 252 if (const auto *TPL = Node->getTemplateParameterList()) { 253 for (const auto *TP : *TPL) { 254 if (!match(*TP)) 255 return false; 256 } 257 } 258 259 for (const auto *P : Node->getCallOperator()->parameters()) { 260 if (!match(*P)) 261 return false; 262 } 263 264 if (!match(*Node->getBody())) 265 return false; 266 267 return true; 268 } 269 270 bool shouldVisitTemplateInstantiations() const { return true; } 271 bool shouldVisitImplicitCode() const { return true; } 272 273 private: 274 // Used for updating the depth during traversal. 275 struct ScopedIncrement { 276 explicit ScopedIncrement(int *Depth) : Depth(Depth) { ++(*Depth); } 277 ~ScopedIncrement() { --(*Depth); } 278 279 private: 280 int *Depth; 281 }; 282 283 // Resets the state of this object. 284 void reset() { 285 Matches = false; 286 CurrentDepth = 0; 287 } 288 289 // Forwards the call to the corresponding Traverse*() method in the 290 // base visitor class. 291 bool baseTraverse(const Decl &DeclNode) { 292 return VisitorBase::TraverseDecl(const_cast<Decl*>(&DeclNode)); 293 } 294 bool baseTraverse(const Stmt &StmtNode) { 295 return VisitorBase::TraverseStmt(const_cast<Stmt*>(&StmtNode)); 296 } 297 bool baseTraverse(QualType TypeNode) { 298 return VisitorBase::TraverseType(TypeNode); 299 } 300 bool baseTraverse(TypeLoc TypeLocNode) { 301 return VisitorBase::TraverseTypeLoc(TypeLocNode); 302 } 303 bool baseTraverse(const NestedNameSpecifier &NNS) { 304 return VisitorBase::TraverseNestedNameSpecifier( 305 const_cast<NestedNameSpecifier*>(&NNS)); 306 } 307 bool baseTraverse(NestedNameSpecifierLoc NNS) { 308 return VisitorBase::TraverseNestedNameSpecifierLoc(NNS); 309 } 310 bool baseTraverse(const CXXCtorInitializer &CtorInit) { 311 return VisitorBase::TraverseConstructorInitializer( 312 const_cast<CXXCtorInitializer *>(&CtorInit)); 313 } 314 bool baseTraverse(TemplateArgumentLoc TAL) { 315 return VisitorBase::TraverseTemplateArgumentLoc(TAL); 316 } 317 318 // Sets 'Matched' to true if 'Matcher' matches 'Node' and: 319 // 0 < CurrentDepth <= MaxDepth. 320 // 321 // Returns 'true' if traversal should continue after this function 322 // returns, i.e. if no match is found or 'Bind' is 'BK_All'. 323 template <typename T> 324 bool match(const T &Node) { 325 if (CurrentDepth == 0 || CurrentDepth > MaxDepth) { 326 return true; 327 } 328 if (Bind != ASTMatchFinder::BK_All) { 329 BoundNodesTreeBuilder RecursiveBuilder(*Builder); 330 if (Matcher->matches(DynTypedNode::create(Node), Finder, 331 &RecursiveBuilder)) { 332 Matches = true; 333 ResultBindings.addMatch(RecursiveBuilder); 334 return false; // Abort as soon as a match is found. 335 } 336 } else { 337 BoundNodesTreeBuilder RecursiveBuilder(*Builder); 338 if (Matcher->matches(DynTypedNode::create(Node), Finder, 339 &RecursiveBuilder)) { 340 // After the first match the matcher succeeds. 341 Matches = true; 342 ResultBindings.addMatch(RecursiveBuilder); 343 } 344 } 345 return true; 346 } 347 348 // Traverses the subtree rooted at 'Node'; returns true if the 349 // traversal should continue after this function returns. 350 template <typename T> 351 bool traverse(const T &Node) { 352 static_assert(IsBaseType<T>::value, 353 "traverse can only be instantiated with base type"); 354 if (!match(Node)) 355 return false; 356 return baseTraverse(Node); 357 } 358 359 const DynTypedMatcher *const Matcher; 360 ASTMatchFinder *const Finder; 361 BoundNodesTreeBuilder *const Builder; 362 BoundNodesTreeBuilder ResultBindings; 363 int CurrentDepth; 364 const int MaxDepth; 365 const TraversalKind Traversal; 366 const ASTMatchFinder::BindKind Bind; 367 bool Matches; 368 }; 369 370 // Controls the outermost traversal of the AST and allows to match multiple 371 // matchers. 372 class MatchASTVisitor : public RecursiveASTVisitor<MatchASTVisitor>, 373 public ASTMatchFinder { 374 public: 375 MatchASTVisitor(const MatchFinder::MatchersByType *Matchers, 376 const MatchFinder::MatchFinderOptions &Options) 377 : Matchers(Matchers), Options(Options), ActiveASTContext(nullptr) {} 378 379 ~MatchASTVisitor() override { 380 if (Options.CheckProfiling) { 381 Options.CheckProfiling->Records = std::move(TimeByBucket); 382 } 383 } 384 385 void onStartOfTranslationUnit() { 386 const bool EnableCheckProfiling = Options.CheckProfiling.hasValue(); 387 TimeBucketRegion Timer; 388 for (MatchCallback *MC : Matchers->AllCallbacks) { 389 if (EnableCheckProfiling) 390 Timer.setBucket(&TimeByBucket[MC->getID()]); 391 MC->onStartOfTranslationUnit(); 392 } 393 } 394 395 void onEndOfTranslationUnit() { 396 const bool EnableCheckProfiling = Options.CheckProfiling.hasValue(); 397 TimeBucketRegion Timer; 398 for (MatchCallback *MC : Matchers->AllCallbacks) { 399 if (EnableCheckProfiling) 400 Timer.setBucket(&TimeByBucket[MC->getID()]); 401 MC->onEndOfTranslationUnit(); 402 } 403 } 404 405 void set_active_ast_context(ASTContext *NewActiveASTContext) { 406 ActiveASTContext = NewActiveASTContext; 407 } 408 409 // The following Visit*() and Traverse*() functions "override" 410 // methods in RecursiveASTVisitor. 411 412 bool VisitTypedefNameDecl(TypedefNameDecl *DeclNode) { 413 // When we see 'typedef A B', we add name 'B' to the set of names 414 // A's canonical type maps to. This is necessary for implementing 415 // isDerivedFrom(x) properly, where x can be the name of the base 416 // class or any of its aliases. 417 // 418 // In general, the is-alias-of (as defined by typedefs) relation 419 // is tree-shaped, as you can typedef a type more than once. For 420 // example, 421 // 422 // typedef A B; 423 // typedef A C; 424 // typedef C D; 425 // typedef C E; 426 // 427 // gives you 428 // 429 // A 430 // |- B 431 // `- C 432 // |- D 433 // `- E 434 // 435 // It is wrong to assume that the relation is a chain. A correct 436 // implementation of isDerivedFrom() needs to recognize that B and 437 // E are aliases, even though neither is a typedef of the other. 438 // Therefore, we cannot simply walk through one typedef chain to 439 // find out whether the type name matches. 440 const Type *TypeNode = DeclNode->getUnderlyingType().getTypePtr(); 441 const Type *CanonicalType = // root of the typedef tree 442 ActiveASTContext->getCanonicalType(TypeNode); 443 TypeAliases[CanonicalType].insert(DeclNode); 444 return true; 445 } 446 447 bool VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) { 448 const ObjCInterfaceDecl *InterfaceDecl = CAD->getClassInterface(); 449 CompatibleAliases[InterfaceDecl].insert(CAD); 450 return true; 451 } 452 453 bool TraverseDecl(Decl *DeclNode); 454 bool TraverseStmt(Stmt *StmtNode, DataRecursionQueue *Queue = nullptr); 455 bool TraverseType(QualType TypeNode); 456 bool TraverseTypeLoc(TypeLoc TypeNode); 457 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS); 458 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS); 459 bool TraverseConstructorInitializer(CXXCtorInitializer *CtorInit); 460 bool TraverseTemplateArgumentLoc(TemplateArgumentLoc TAL); 461 462 // Matches children or descendants of 'Node' with 'BaseMatcher'. 463 bool memoizedMatchesRecursively(const DynTypedNode &Node, ASTContext &Ctx, 464 const DynTypedMatcher &Matcher, 465 BoundNodesTreeBuilder *Builder, int MaxDepth, 466 TraversalKind Traversal, BindKind Bind) { 467 // For AST-nodes that don't have an identity, we can't memoize. 468 if (!Node.getMemoizationData() || !Builder->isComparable()) 469 return matchesRecursively(Node, Matcher, Builder, MaxDepth, Traversal, 470 Bind); 471 472 MatchKey Key; 473 Key.MatcherID = Matcher.getID(); 474 Key.Node = Node; 475 // Note that we key on the bindings *before* the match. 476 Key.BoundNodes = *Builder; 477 Key.Traversal = Ctx.getParentMapContext().getTraversalKind(); 478 // Memoize result even doing a single-level match, it might be expensive. 479 Key.Type = MaxDepth == 1 ? MatchType::Child : MatchType::Descendants; 480 MemoizationMap::iterator I = ResultCache.find(Key); 481 if (I != ResultCache.end()) { 482 *Builder = I->second.Nodes; 483 return I->second.ResultOfMatch; 484 } 485 486 MemoizedMatchResult Result; 487 Result.Nodes = *Builder; 488 Result.ResultOfMatch = matchesRecursively(Node, Matcher, &Result.Nodes, 489 MaxDepth, Traversal, Bind); 490 491 MemoizedMatchResult &CachedResult = ResultCache[Key]; 492 CachedResult = std::move(Result); 493 494 *Builder = CachedResult.Nodes; 495 return CachedResult.ResultOfMatch; 496 } 497 498 // Matches children or descendants of 'Node' with 'BaseMatcher'. 499 bool matchesRecursively(const DynTypedNode &Node, 500 const DynTypedMatcher &Matcher, 501 BoundNodesTreeBuilder *Builder, int MaxDepth, 502 TraversalKind Traversal, BindKind Bind) { 503 MatchChildASTVisitor Visitor( 504 &Matcher, this, Builder, MaxDepth, Traversal, Bind); 505 return Visitor.findMatch(Node); 506 } 507 508 bool classIsDerivedFrom(const CXXRecordDecl *Declaration, 509 const Matcher<NamedDecl> &Base, 510 BoundNodesTreeBuilder *Builder, 511 bool Directly) override; 512 513 bool objcClassIsDerivedFrom(const ObjCInterfaceDecl *Declaration, 514 const Matcher<NamedDecl> &Base, 515 BoundNodesTreeBuilder *Builder, 516 bool Directly) override; 517 518 // Implements ASTMatchFinder::matchesChildOf. 519 bool matchesChildOf(const DynTypedNode &Node, ASTContext &Ctx, 520 const DynTypedMatcher &Matcher, 521 BoundNodesTreeBuilder *Builder, TraversalKind Traversal, 522 BindKind Bind) override { 523 if (ResultCache.size() > MaxMemoizationEntries) 524 ResultCache.clear(); 525 return memoizedMatchesRecursively(Node, Ctx, Matcher, Builder, 1, Traversal, 526 Bind); 527 } 528 // Implements ASTMatchFinder::matchesDescendantOf. 529 bool matchesDescendantOf(const DynTypedNode &Node, ASTContext &Ctx, 530 const DynTypedMatcher &Matcher, 531 BoundNodesTreeBuilder *Builder, 532 BindKind Bind) override { 533 if (ResultCache.size() > MaxMemoizationEntries) 534 ResultCache.clear(); 535 return memoizedMatchesRecursively(Node, Ctx, Matcher, Builder, INT_MAX, 536 TraversalKind::TK_AsIs, Bind); 537 } 538 // Implements ASTMatchFinder::matchesAncestorOf. 539 bool matchesAncestorOf(const DynTypedNode &Node, ASTContext &Ctx, 540 const DynTypedMatcher &Matcher, 541 BoundNodesTreeBuilder *Builder, 542 AncestorMatchMode MatchMode) override { 543 // Reset the cache outside of the recursive call to make sure we 544 // don't invalidate any iterators. 545 if (ResultCache.size() > MaxMemoizationEntries) 546 ResultCache.clear(); 547 return memoizedMatchesAncestorOfRecursively(Node, Ctx, Matcher, Builder, 548 MatchMode); 549 } 550 551 // Matches all registered matchers on the given node and calls the 552 // result callback for every node that matches. 553 void match(const DynTypedNode &Node) { 554 // FIXME: Improve this with a switch or a visitor pattern. 555 if (auto *N = Node.get<Decl>()) { 556 match(*N); 557 } else if (auto *N = Node.get<Stmt>()) { 558 match(*N); 559 } else if (auto *N = Node.get<Type>()) { 560 match(*N); 561 } else if (auto *N = Node.get<QualType>()) { 562 match(*N); 563 } else if (auto *N = Node.get<NestedNameSpecifier>()) { 564 match(*N); 565 } else if (auto *N = Node.get<NestedNameSpecifierLoc>()) { 566 match(*N); 567 } else if (auto *N = Node.get<TypeLoc>()) { 568 match(*N); 569 } else if (auto *N = Node.get<CXXCtorInitializer>()) { 570 match(*N); 571 } else if (auto *N = Node.get<TemplateArgumentLoc>()) { 572 match(*N); 573 } 574 } 575 576 template <typename T> void match(const T &Node) { 577 matchDispatch(&Node); 578 } 579 580 // Implements ASTMatchFinder::getASTContext. 581 ASTContext &getASTContext() const override { return *ActiveASTContext; } 582 583 bool shouldVisitTemplateInstantiations() const { return true; } 584 bool shouldVisitImplicitCode() const { return true; } 585 586 private: 587 class TimeBucketRegion { 588 public: 589 TimeBucketRegion() : Bucket(nullptr) {} 590 ~TimeBucketRegion() { setBucket(nullptr); } 591 592 /// Start timing for \p NewBucket. 593 /// 594 /// If there was a bucket already set, it will finish the timing for that 595 /// other bucket. 596 /// \p NewBucket will be timed until the next call to \c setBucket() or 597 /// until the \c TimeBucketRegion is destroyed. 598 /// If \p NewBucket is the same as the currently timed bucket, this call 599 /// does nothing. 600 void setBucket(llvm::TimeRecord *NewBucket) { 601 if (Bucket != NewBucket) { 602 auto Now = llvm::TimeRecord::getCurrentTime(true); 603 if (Bucket) 604 *Bucket += Now; 605 if (NewBucket) 606 *NewBucket -= Now; 607 Bucket = NewBucket; 608 } 609 } 610 611 private: 612 llvm::TimeRecord *Bucket; 613 }; 614 615 /// Runs all the \p Matchers on \p Node. 616 /// 617 /// Used by \c matchDispatch() below. 618 template <typename T, typename MC> 619 void matchWithoutFilter(const T &Node, const MC &Matchers) { 620 const bool EnableCheckProfiling = Options.CheckProfiling.hasValue(); 621 TimeBucketRegion Timer; 622 for (const auto &MP : Matchers) { 623 if (EnableCheckProfiling) 624 Timer.setBucket(&TimeByBucket[MP.second->getID()]); 625 BoundNodesTreeBuilder Builder; 626 if (MP.first.matches(Node, this, &Builder)) { 627 MatchVisitor Visitor(ActiveASTContext, MP.second); 628 Builder.visitMatches(&Visitor); 629 } 630 } 631 } 632 633 void matchWithFilter(const DynTypedNode &DynNode) { 634 auto Kind = DynNode.getNodeKind(); 635 auto it = MatcherFiltersMap.find(Kind); 636 const auto &Filter = 637 it != MatcherFiltersMap.end() ? it->second : getFilterForKind(Kind); 638 639 if (Filter.empty()) 640 return; 641 642 const bool EnableCheckProfiling = Options.CheckProfiling.hasValue(); 643 TimeBucketRegion Timer; 644 auto &Matchers = this->Matchers->DeclOrStmt; 645 for (unsigned short I : Filter) { 646 auto &MP = Matchers[I]; 647 if (EnableCheckProfiling) 648 Timer.setBucket(&TimeByBucket[MP.second->getID()]); 649 BoundNodesTreeBuilder Builder; 650 if (MP.first.matches(DynNode, this, &Builder)) { 651 MatchVisitor Visitor(ActiveASTContext, MP.second); 652 Builder.visitMatches(&Visitor); 653 } 654 } 655 } 656 657 const std::vector<unsigned short> &getFilterForKind(ASTNodeKind Kind) { 658 auto &Filter = MatcherFiltersMap[Kind]; 659 auto &Matchers = this->Matchers->DeclOrStmt; 660 assert((Matchers.size() < USHRT_MAX) && "Too many matchers."); 661 for (unsigned I = 0, E = Matchers.size(); I != E; ++I) { 662 if (Matchers[I].first.canMatchNodesOfKind(Kind)) { 663 Filter.push_back(I); 664 } 665 } 666 return Filter; 667 } 668 669 /// @{ 670 /// Overloads to pair the different node types to their matchers. 671 void matchDispatch(const Decl *Node) { 672 return matchWithFilter(DynTypedNode::create(*Node)); 673 } 674 void matchDispatch(const Stmt *Node) { 675 return matchWithFilter(DynTypedNode::create(*Node)); 676 } 677 678 void matchDispatch(const Type *Node) { 679 matchWithoutFilter(QualType(Node, 0), Matchers->Type); 680 } 681 void matchDispatch(const TypeLoc *Node) { 682 matchWithoutFilter(*Node, Matchers->TypeLoc); 683 } 684 void matchDispatch(const QualType *Node) { 685 matchWithoutFilter(*Node, Matchers->Type); 686 } 687 void matchDispatch(const NestedNameSpecifier *Node) { 688 matchWithoutFilter(*Node, Matchers->NestedNameSpecifier); 689 } 690 void matchDispatch(const NestedNameSpecifierLoc *Node) { 691 matchWithoutFilter(*Node, Matchers->NestedNameSpecifierLoc); 692 } 693 void matchDispatch(const CXXCtorInitializer *Node) { 694 matchWithoutFilter(*Node, Matchers->CtorInit); 695 } 696 void matchDispatch(const TemplateArgumentLoc *Node) { 697 matchWithoutFilter(*Node, Matchers->TemplateArgumentLoc); 698 } 699 void matchDispatch(const void *) { /* Do nothing. */ } 700 /// @} 701 702 // Returns whether an ancestor of \p Node matches \p Matcher. 703 // 704 // The order of matching ((which can lead to different nodes being bound in 705 // case there are multiple matches) is breadth first search. 706 // 707 // To allow memoization in the very common case of having deeply nested 708 // expressions inside a template function, we first walk up the AST, memoizing 709 // the result of the match along the way, as long as there is only a single 710 // parent. 711 // 712 // Once there are multiple parents, the breadth first search order does not 713 // allow simple memoization on the ancestors. Thus, we only memoize as long 714 // as there is a single parent. 715 bool memoizedMatchesAncestorOfRecursively(const DynTypedNode &Node, 716 ASTContext &Ctx, 717 const DynTypedMatcher &Matcher, 718 BoundNodesTreeBuilder *Builder, 719 AncestorMatchMode MatchMode) { 720 // For AST-nodes that don't have an identity, we can't memoize. 721 // When doing a single-level match, we don't need to memoize because 722 // ParentMap (in ASTContext) already memoizes the result. 723 if (!Builder->isComparable() || 724 MatchMode == AncestorMatchMode::AMM_ParentOnly) 725 return matchesAncestorOfRecursively(Node, Ctx, Matcher, Builder, 726 MatchMode); 727 728 MatchKey Key; 729 Key.MatcherID = Matcher.getID(); 730 Key.Node = Node; 731 Key.BoundNodes = *Builder; 732 Key.Traversal = Ctx.getParentMapContext().getTraversalKind(); 733 Key.Type = MatchType::Ancestors; 734 735 // Note that we cannot use insert and reuse the iterator, as recursive 736 // calls to match might invalidate the result cache iterators. 737 MemoizationMap::iterator I = ResultCache.find(Key); 738 if (I != ResultCache.end()) { 739 *Builder = I->second.Nodes; 740 return I->second.ResultOfMatch; 741 } 742 743 MemoizedMatchResult Result; 744 Result.Nodes = *Builder; 745 Result.ResultOfMatch = matchesAncestorOfRecursively( 746 Node, Ctx, Matcher, &Result.Nodes, MatchMode); 747 748 MemoizedMatchResult &CachedResult = ResultCache[Key]; 749 CachedResult = std::move(Result); 750 751 *Builder = CachedResult.Nodes; 752 return CachedResult.ResultOfMatch; 753 } 754 755 bool matchesAncestorOfRecursively(const DynTypedNode &Node, ASTContext &Ctx, 756 const DynTypedMatcher &Matcher, 757 BoundNodesTreeBuilder *Builder, 758 AncestorMatchMode MatchMode) { 759 const auto &Parents = ActiveASTContext->getParents(Node); 760 if (Parents.empty()) { 761 // Nodes may have no parents if: 762 // a) the node is the TranslationUnitDecl 763 // b) we have a limited traversal scope that excludes the parent edges 764 // c) there is a bug in the AST, and the node is not reachable 765 // Usually the traversal scope is the whole AST, which precludes b. 766 // Bugs are common enough that it's worthwhile asserting when we can. 767 #ifndef NDEBUG 768 if (!Node.get<TranslationUnitDecl>() && 769 /* Traversal scope is full AST if any of the bounds are the TU */ 770 llvm::any_of(ActiveASTContext->getTraversalScope(), [](Decl *D) { 771 return D->getKind() == Decl::TranslationUnit; 772 })) { 773 llvm::errs() << "Tried to match orphan node:\n"; 774 Node.dump(llvm::errs(), *ActiveASTContext); 775 llvm_unreachable("Parent map should be complete!"); 776 } 777 #endif 778 return false; 779 } 780 if (Parents.size() == 1) { 781 // Only one parent - do recursive memoization. 782 const DynTypedNode Parent = Parents[0]; 783 BoundNodesTreeBuilder BuilderCopy = *Builder; 784 if (Matcher.matches(Parent, this, &BuilderCopy)) { 785 *Builder = std::move(BuilderCopy); 786 return true; 787 } 788 if (MatchMode != ASTMatchFinder::AMM_ParentOnly) { 789 return memoizedMatchesAncestorOfRecursively(Parent, Ctx, Matcher, 790 Builder, MatchMode); 791 // Once we get back from the recursive call, the result will be the 792 // same as the parent's result. 793 } 794 } else { 795 // Multiple parents - BFS over the rest of the nodes. 796 llvm::DenseSet<const void *> Visited; 797 std::deque<DynTypedNode> Queue(Parents.begin(), Parents.end()); 798 while (!Queue.empty()) { 799 BoundNodesTreeBuilder BuilderCopy = *Builder; 800 if (Matcher.matches(Queue.front(), this, &BuilderCopy)) { 801 *Builder = std::move(BuilderCopy); 802 return true; 803 } 804 if (MatchMode != ASTMatchFinder::AMM_ParentOnly) { 805 for (const auto &Parent : 806 ActiveASTContext->getParents(Queue.front())) { 807 // Make sure we do not visit the same node twice. 808 // Otherwise, we'll visit the common ancestors as often as there 809 // are splits on the way down. 810 if (Visited.insert(Parent.getMemoizationData()).second) 811 Queue.push_back(Parent); 812 } 813 } 814 Queue.pop_front(); 815 } 816 } 817 return false; 818 } 819 820 // Implements a BoundNodesTree::Visitor that calls a MatchCallback with 821 // the aggregated bound nodes for each match. 822 class MatchVisitor : public BoundNodesTreeBuilder::Visitor { 823 public: 824 MatchVisitor(ASTContext* Context, 825 MatchFinder::MatchCallback* Callback) 826 : Context(Context), 827 Callback(Callback) {} 828 829 void visitMatch(const BoundNodes& BoundNodesView) override { 830 Callback->run(MatchFinder::MatchResult(BoundNodesView, Context)); 831 } 832 833 private: 834 ASTContext* Context; 835 MatchFinder::MatchCallback* Callback; 836 }; 837 838 // Returns true if 'TypeNode' has an alias that matches the given matcher. 839 bool typeHasMatchingAlias(const Type *TypeNode, 840 const Matcher<NamedDecl> &Matcher, 841 BoundNodesTreeBuilder *Builder) { 842 const Type *const CanonicalType = 843 ActiveASTContext->getCanonicalType(TypeNode); 844 auto Aliases = TypeAliases.find(CanonicalType); 845 if (Aliases == TypeAliases.end()) 846 return false; 847 for (const TypedefNameDecl *Alias : Aliases->second) { 848 BoundNodesTreeBuilder Result(*Builder); 849 if (Matcher.matches(*Alias, this, &Result)) { 850 *Builder = std::move(Result); 851 return true; 852 } 853 } 854 return false; 855 } 856 857 bool 858 objcClassHasMatchingCompatibilityAlias(const ObjCInterfaceDecl *InterfaceDecl, 859 const Matcher<NamedDecl> &Matcher, 860 BoundNodesTreeBuilder *Builder) { 861 auto Aliases = CompatibleAliases.find(InterfaceDecl); 862 if (Aliases == CompatibleAliases.end()) 863 return false; 864 for (const ObjCCompatibleAliasDecl *Alias : Aliases->second) { 865 BoundNodesTreeBuilder Result(*Builder); 866 if (Matcher.matches(*Alias, this, &Result)) { 867 *Builder = std::move(Result); 868 return true; 869 } 870 } 871 return false; 872 } 873 874 /// Bucket to record map. 875 /// 876 /// Used to get the appropriate bucket for each matcher. 877 llvm::StringMap<llvm::TimeRecord> TimeByBucket; 878 879 const MatchFinder::MatchersByType *Matchers; 880 881 /// Filtered list of matcher indices for each matcher kind. 882 /// 883 /// \c Decl and \c Stmt toplevel matchers usually apply to a specific node 884 /// kind (and derived kinds) so it is a waste to try every matcher on every 885 /// node. 886 /// We precalculate a list of matchers that pass the toplevel restrict check. 887 llvm::DenseMap<ASTNodeKind, std::vector<unsigned short>> MatcherFiltersMap; 888 889 const MatchFinder::MatchFinderOptions &Options; 890 ASTContext *ActiveASTContext; 891 892 // Maps a canonical type to its TypedefDecls. 893 llvm::DenseMap<const Type*, std::set<const TypedefNameDecl*> > TypeAliases; 894 895 // Maps an Objective-C interface to its ObjCCompatibleAliasDecls. 896 llvm::DenseMap<const ObjCInterfaceDecl *, 897 llvm::SmallPtrSet<const ObjCCompatibleAliasDecl *, 2>> 898 CompatibleAliases; 899 900 // Maps (matcher, node) -> the match result for memoization. 901 typedef std::map<MatchKey, MemoizedMatchResult> MemoizationMap; 902 MemoizationMap ResultCache; 903 }; 904 905 static CXXRecordDecl * 906 getAsCXXRecordDeclOrPrimaryTemplate(const Type *TypeNode) { 907 if (auto *RD = TypeNode->getAsCXXRecordDecl()) 908 return RD; 909 910 // Find the innermost TemplateSpecializationType that isn't an alias template. 911 auto *TemplateType = TypeNode->getAs<TemplateSpecializationType>(); 912 while (TemplateType && TemplateType->isTypeAlias()) 913 TemplateType = 914 TemplateType->getAliasedType()->getAs<TemplateSpecializationType>(); 915 916 // If this is the name of a (dependent) template specialization, use the 917 // definition of the template, even though it might be specialized later. 918 if (TemplateType) 919 if (auto *ClassTemplate = dyn_cast_or_null<ClassTemplateDecl>( 920 TemplateType->getTemplateName().getAsTemplateDecl())) 921 return ClassTemplate->getTemplatedDecl(); 922 923 return nullptr; 924 } 925 926 // Returns true if the given C++ class is directly or indirectly derived 927 // from a base type with the given name. A class is not considered to be 928 // derived from itself. 929 bool MatchASTVisitor::classIsDerivedFrom(const CXXRecordDecl *Declaration, 930 const Matcher<NamedDecl> &Base, 931 BoundNodesTreeBuilder *Builder, 932 bool Directly) { 933 if (!Declaration->hasDefinition()) 934 return false; 935 for (const auto &It : Declaration->bases()) { 936 const Type *TypeNode = It.getType().getTypePtr(); 937 938 if (typeHasMatchingAlias(TypeNode, Base, Builder)) 939 return true; 940 941 // FIXME: Going to the primary template here isn't really correct, but 942 // unfortunately we accept a Decl matcher for the base class not a Type 943 // matcher, so it's the best thing we can do with our current interface. 944 CXXRecordDecl *ClassDecl = getAsCXXRecordDeclOrPrimaryTemplate(TypeNode); 945 if (!ClassDecl) 946 continue; 947 if (ClassDecl == Declaration) { 948 // This can happen for recursive template definitions. 949 continue; 950 } 951 BoundNodesTreeBuilder Result(*Builder); 952 if (Base.matches(*ClassDecl, this, &Result)) { 953 *Builder = std::move(Result); 954 return true; 955 } 956 if (!Directly && classIsDerivedFrom(ClassDecl, Base, Builder, Directly)) 957 return true; 958 } 959 return false; 960 } 961 962 // Returns true if the given Objective-C class is directly or indirectly 963 // derived from a matching base class. A class is not considered to be derived 964 // from itself. 965 bool MatchASTVisitor::objcClassIsDerivedFrom( 966 const ObjCInterfaceDecl *Declaration, const Matcher<NamedDecl> &Base, 967 BoundNodesTreeBuilder *Builder, bool Directly) { 968 // Check if any of the superclasses of the class match. 969 for (const ObjCInterfaceDecl *ClassDecl = Declaration->getSuperClass(); 970 ClassDecl != nullptr; ClassDecl = ClassDecl->getSuperClass()) { 971 // Check if there are any matching compatibility aliases. 972 if (objcClassHasMatchingCompatibilityAlias(ClassDecl, Base, Builder)) 973 return true; 974 975 // Check if there are any matching type aliases. 976 const Type *TypeNode = ClassDecl->getTypeForDecl(); 977 if (typeHasMatchingAlias(TypeNode, Base, Builder)) 978 return true; 979 980 if (Base.matches(*ClassDecl, this, Builder)) 981 return true; 982 983 // Not `return false` as a temporary workaround for PR43879. 984 if (Directly) 985 break; 986 } 987 988 return false; 989 } 990 991 bool MatchASTVisitor::TraverseDecl(Decl *DeclNode) { 992 if (!DeclNode) { 993 return true; 994 } 995 match(*DeclNode); 996 return RecursiveASTVisitor<MatchASTVisitor>::TraverseDecl(DeclNode); 997 } 998 999 bool MatchASTVisitor::TraverseStmt(Stmt *StmtNode, DataRecursionQueue *Queue) { 1000 if (!StmtNode) { 1001 return true; 1002 } 1003 match(*StmtNode); 1004 return RecursiveASTVisitor<MatchASTVisitor>::TraverseStmt(StmtNode, Queue); 1005 } 1006 1007 bool MatchASTVisitor::TraverseType(QualType TypeNode) { 1008 match(TypeNode); 1009 return RecursiveASTVisitor<MatchASTVisitor>::TraverseType(TypeNode); 1010 } 1011 1012 bool MatchASTVisitor::TraverseTypeLoc(TypeLoc TypeLocNode) { 1013 // The RecursiveASTVisitor only visits types if they're not within TypeLocs. 1014 // We still want to find those types via matchers, so we match them here. Note 1015 // that the TypeLocs are structurally a shadow-hierarchy to the expressed 1016 // type, so we visit all involved parts of a compound type when matching on 1017 // each TypeLoc. 1018 match(TypeLocNode); 1019 match(TypeLocNode.getType()); 1020 return RecursiveASTVisitor<MatchASTVisitor>::TraverseTypeLoc(TypeLocNode); 1021 } 1022 1023 bool MatchASTVisitor::TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) { 1024 match(*NNS); 1025 return RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifier(NNS); 1026 } 1027 1028 bool MatchASTVisitor::TraverseNestedNameSpecifierLoc( 1029 NestedNameSpecifierLoc NNS) { 1030 if (!NNS) 1031 return true; 1032 1033 match(NNS); 1034 1035 // We only match the nested name specifier here (as opposed to traversing it) 1036 // because the traversal is already done in the parallel "Loc"-hierarchy. 1037 if (NNS.hasQualifier()) 1038 match(*NNS.getNestedNameSpecifier()); 1039 return 1040 RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifierLoc(NNS); 1041 } 1042 1043 bool MatchASTVisitor::TraverseConstructorInitializer( 1044 CXXCtorInitializer *CtorInit) { 1045 if (!CtorInit) 1046 return true; 1047 1048 match(*CtorInit); 1049 1050 return RecursiveASTVisitor<MatchASTVisitor>::TraverseConstructorInitializer( 1051 CtorInit); 1052 } 1053 1054 bool MatchASTVisitor::TraverseTemplateArgumentLoc(TemplateArgumentLoc Loc) { 1055 match(Loc); 1056 return RecursiveASTVisitor<MatchASTVisitor>::TraverseTemplateArgumentLoc(Loc); 1057 } 1058 1059 class MatchASTConsumer : public ASTConsumer { 1060 public: 1061 MatchASTConsumer(MatchFinder *Finder, 1062 MatchFinder::ParsingDoneTestCallback *ParsingDone) 1063 : Finder(Finder), ParsingDone(ParsingDone) {} 1064 1065 private: 1066 void HandleTranslationUnit(ASTContext &Context) override { 1067 if (ParsingDone != nullptr) { 1068 ParsingDone->run(); 1069 } 1070 Finder->matchAST(Context); 1071 } 1072 1073 MatchFinder *Finder; 1074 MatchFinder::ParsingDoneTestCallback *ParsingDone; 1075 }; 1076 1077 } // end namespace 1078 } // end namespace internal 1079 1080 MatchFinder::MatchResult::MatchResult(const BoundNodes &Nodes, 1081 ASTContext *Context) 1082 : Nodes(Nodes), Context(Context), 1083 SourceManager(&Context->getSourceManager()) {} 1084 1085 MatchFinder::MatchCallback::~MatchCallback() {} 1086 MatchFinder::ParsingDoneTestCallback::~ParsingDoneTestCallback() {} 1087 1088 MatchFinder::MatchFinder(MatchFinderOptions Options) 1089 : Options(std::move(Options)), ParsingDone(nullptr) {} 1090 1091 MatchFinder::~MatchFinder() {} 1092 1093 void MatchFinder::addMatcher(const DeclarationMatcher &NodeMatch, 1094 MatchCallback *Action) { 1095 Matchers.DeclOrStmt.emplace_back(NodeMatch, Action); 1096 Matchers.AllCallbacks.insert(Action); 1097 } 1098 1099 void MatchFinder::addMatcher(const TypeMatcher &NodeMatch, 1100 MatchCallback *Action) { 1101 Matchers.Type.emplace_back(NodeMatch, Action); 1102 Matchers.AllCallbacks.insert(Action); 1103 } 1104 1105 void MatchFinder::addMatcher(const StatementMatcher &NodeMatch, 1106 MatchCallback *Action) { 1107 Matchers.DeclOrStmt.emplace_back(NodeMatch, Action); 1108 Matchers.AllCallbacks.insert(Action); 1109 } 1110 1111 void MatchFinder::addMatcher(const NestedNameSpecifierMatcher &NodeMatch, 1112 MatchCallback *Action) { 1113 Matchers.NestedNameSpecifier.emplace_back(NodeMatch, Action); 1114 Matchers.AllCallbacks.insert(Action); 1115 } 1116 1117 void MatchFinder::addMatcher(const NestedNameSpecifierLocMatcher &NodeMatch, 1118 MatchCallback *Action) { 1119 Matchers.NestedNameSpecifierLoc.emplace_back(NodeMatch, Action); 1120 Matchers.AllCallbacks.insert(Action); 1121 } 1122 1123 void MatchFinder::addMatcher(const TypeLocMatcher &NodeMatch, 1124 MatchCallback *Action) { 1125 Matchers.TypeLoc.emplace_back(NodeMatch, Action); 1126 Matchers.AllCallbacks.insert(Action); 1127 } 1128 1129 void MatchFinder::addMatcher(const CXXCtorInitializerMatcher &NodeMatch, 1130 MatchCallback *Action) { 1131 Matchers.CtorInit.emplace_back(NodeMatch, Action); 1132 Matchers.AllCallbacks.insert(Action); 1133 } 1134 1135 void MatchFinder::addMatcher(const TemplateArgumentLocMatcher &NodeMatch, 1136 MatchCallback *Action) { 1137 Matchers.TemplateArgumentLoc.emplace_back(NodeMatch, Action); 1138 Matchers.AllCallbacks.insert(Action); 1139 } 1140 1141 bool MatchFinder::addDynamicMatcher(const internal::DynTypedMatcher &NodeMatch, 1142 MatchCallback *Action) { 1143 if (NodeMatch.canConvertTo<Decl>()) { 1144 addMatcher(NodeMatch.convertTo<Decl>(), Action); 1145 return true; 1146 } else if (NodeMatch.canConvertTo<QualType>()) { 1147 addMatcher(NodeMatch.convertTo<QualType>(), Action); 1148 return true; 1149 } else if (NodeMatch.canConvertTo<Stmt>()) { 1150 addMatcher(NodeMatch.convertTo<Stmt>(), Action); 1151 return true; 1152 } else if (NodeMatch.canConvertTo<NestedNameSpecifier>()) { 1153 addMatcher(NodeMatch.convertTo<NestedNameSpecifier>(), Action); 1154 return true; 1155 } else if (NodeMatch.canConvertTo<NestedNameSpecifierLoc>()) { 1156 addMatcher(NodeMatch.convertTo<NestedNameSpecifierLoc>(), Action); 1157 return true; 1158 } else if (NodeMatch.canConvertTo<TypeLoc>()) { 1159 addMatcher(NodeMatch.convertTo<TypeLoc>(), Action); 1160 return true; 1161 } else if (NodeMatch.canConvertTo<CXXCtorInitializer>()) { 1162 addMatcher(NodeMatch.convertTo<CXXCtorInitializer>(), Action); 1163 return true; 1164 } else if (NodeMatch.canConvertTo<TemplateArgumentLoc>()) { 1165 addMatcher(NodeMatch.convertTo<TemplateArgumentLoc>(), Action); 1166 return true; 1167 } 1168 return false; 1169 } 1170 1171 std::unique_ptr<ASTConsumer> MatchFinder::newASTConsumer() { 1172 return std::make_unique<internal::MatchASTConsumer>(this, ParsingDone); 1173 } 1174 1175 void MatchFinder::match(const clang::DynTypedNode &Node, ASTContext &Context) { 1176 internal::MatchASTVisitor Visitor(&Matchers, Options); 1177 Visitor.set_active_ast_context(&Context); 1178 Visitor.match(Node); 1179 } 1180 1181 void MatchFinder::matchAST(ASTContext &Context) { 1182 internal::MatchASTVisitor Visitor(&Matchers, Options); 1183 Visitor.set_active_ast_context(&Context); 1184 Visitor.onStartOfTranslationUnit(); 1185 Visitor.TraverseAST(Context); 1186 Visitor.onEndOfTranslationUnit(); 1187 } 1188 1189 void MatchFinder::registerTestCallbackAfterParsing( 1190 MatchFinder::ParsingDoneTestCallback *NewParsingDone) { 1191 ParsingDone = NewParsingDone; 1192 } 1193 1194 StringRef MatchFinder::MatchCallback::getID() const { return "<unknown>"; } 1195 1196 } // end namespace ast_matchers 1197 } // end namespace clang 1198