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     bool ScopedTraversal = TraversingTemplateInstantiationNotSpelledInSource;
504 
505     if (const auto *CTSD = Node.get<ClassTemplateSpecializationDecl>()) {
506       int SK = CTSD->getSpecializationKind();
507       if (SK == TSK_ExplicitInstantiationDeclaration ||
508           SK == TSK_ExplicitInstantiationDefinition)
509         ScopedTraversal = true;
510     }
511 
512     TemplateInstantiationNotSpelledInSourceScope RAII(this, ScopedTraversal);
513 
514     MatchChildASTVisitor Visitor(
515       &Matcher, this, Builder, MaxDepth, Traversal, Bind);
516     return Visitor.findMatch(Node);
517   }
518 
519   bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
520                           const Matcher<NamedDecl> &Base,
521                           BoundNodesTreeBuilder *Builder,
522                           bool Directly) override;
523 
524   bool objcClassIsDerivedFrom(const ObjCInterfaceDecl *Declaration,
525                               const Matcher<NamedDecl> &Base,
526                               BoundNodesTreeBuilder *Builder,
527                               bool Directly) override;
528 
529   // Implements ASTMatchFinder::matchesChildOf.
530   bool matchesChildOf(const DynTypedNode &Node, ASTContext &Ctx,
531                       const DynTypedMatcher &Matcher,
532                       BoundNodesTreeBuilder *Builder, TraversalKind Traversal,
533                       BindKind Bind) override {
534     if (ResultCache.size() > MaxMemoizationEntries)
535       ResultCache.clear();
536     return memoizedMatchesRecursively(Node, Ctx, Matcher, Builder, 1, Traversal,
537                                       Bind);
538   }
539   // Implements ASTMatchFinder::matchesDescendantOf.
540   bool matchesDescendantOf(const DynTypedNode &Node, ASTContext &Ctx,
541                            const DynTypedMatcher &Matcher,
542                            BoundNodesTreeBuilder *Builder,
543                            BindKind Bind) override {
544     if (ResultCache.size() > MaxMemoizationEntries)
545       ResultCache.clear();
546     return memoizedMatchesRecursively(Node, Ctx, Matcher, Builder, INT_MAX,
547                                       TraversalKind::TK_AsIs, Bind);
548   }
549   // Implements ASTMatchFinder::matchesAncestorOf.
550   bool matchesAncestorOf(const DynTypedNode &Node, ASTContext &Ctx,
551                          const DynTypedMatcher &Matcher,
552                          BoundNodesTreeBuilder *Builder,
553                          AncestorMatchMode MatchMode) override {
554     // Reset the cache outside of the recursive call to make sure we
555     // don't invalidate any iterators.
556     if (ResultCache.size() > MaxMemoizationEntries)
557       ResultCache.clear();
558     if (MatchMode == AncestorMatchMode::AMM_ParentOnly)
559       return matchesParentOf(Node, Matcher, Builder);
560     return matchesAnyAncestorOf(Node, Ctx, Matcher, Builder);
561   }
562 
563   // Matches all registered matchers on the given node and calls the
564   // result callback for every node that matches.
565   void match(const DynTypedNode &Node) {
566     // FIXME: Improve this with a switch or a visitor pattern.
567     if (auto *N = Node.get<Decl>()) {
568       match(*N);
569     } else if (auto *N = Node.get<Stmt>()) {
570       match(*N);
571     } else if (auto *N = Node.get<Type>()) {
572       match(*N);
573     } else if (auto *N = Node.get<QualType>()) {
574       match(*N);
575     } else if (auto *N = Node.get<NestedNameSpecifier>()) {
576       match(*N);
577     } else if (auto *N = Node.get<NestedNameSpecifierLoc>()) {
578       match(*N);
579     } else if (auto *N = Node.get<TypeLoc>()) {
580       match(*N);
581     } else if (auto *N = Node.get<CXXCtorInitializer>()) {
582       match(*N);
583     } else if (auto *N = Node.get<TemplateArgumentLoc>()) {
584       match(*N);
585     }
586   }
587 
588   template <typename T> void match(const T &Node) {
589     matchDispatch(&Node);
590   }
591 
592   // Implements ASTMatchFinder::getASTContext.
593   ASTContext &getASTContext() const override { return *ActiveASTContext; }
594 
595   bool shouldVisitTemplateInstantiations() const { return true; }
596   bool shouldVisitImplicitCode() const { return true; }
597 
598   bool IsMatchingInTemplateInstantiationNotSpelledInSource() const override {
599     return TraversingTemplateInstantiationNotSpelledInSource;
600   }
601 
602   bool TraverseTemplateInstantiations(ClassTemplateDecl *D) {
603     TemplateInstantiationNotSpelledInSourceScope RAII(this, true);
604     return RecursiveASTVisitor<MatchASTVisitor>::TraverseTemplateInstantiations(
605         D);
606   }
607 
608   bool TraverseTemplateInstantiations(VarTemplateDecl *D) {
609     TemplateInstantiationNotSpelledInSourceScope RAII(this, true);
610     return RecursiveASTVisitor<MatchASTVisitor>::TraverseTemplateInstantiations(
611         D);
612   }
613 
614   bool TraverseTemplateInstantiations(FunctionTemplateDecl *D) {
615     TemplateInstantiationNotSpelledInSourceScope RAII(this, true);
616     return RecursiveASTVisitor<MatchASTVisitor>::TraverseTemplateInstantiations(
617         D);
618   }
619 
620 private:
621   bool TraversingTemplateInstantiationNotSpelledInSource = false;
622 
623   struct TemplateInstantiationNotSpelledInSourceScope {
624     TemplateInstantiationNotSpelledInSourceScope(MatchASTVisitor *V, bool B)
625         : MV(V), MB(V->TraversingTemplateInstantiationNotSpelledInSource) {
626       V->TraversingTemplateInstantiationNotSpelledInSource = B;
627     }
628     ~TemplateInstantiationNotSpelledInSourceScope() {
629       MV->TraversingTemplateInstantiationNotSpelledInSource = MB;
630     }
631 
632   private:
633     MatchASTVisitor *MV;
634     bool MB;
635   };
636 
637   class TimeBucketRegion {
638   public:
639     TimeBucketRegion() : Bucket(nullptr) {}
640     ~TimeBucketRegion() { setBucket(nullptr); }
641 
642     /// Start timing for \p NewBucket.
643     ///
644     /// If there was a bucket already set, it will finish the timing for that
645     /// other bucket.
646     /// \p NewBucket will be timed until the next call to \c setBucket() or
647     /// until the \c TimeBucketRegion is destroyed.
648     /// If \p NewBucket is the same as the currently timed bucket, this call
649     /// does nothing.
650     void setBucket(llvm::TimeRecord *NewBucket) {
651       if (Bucket != NewBucket) {
652         auto Now = llvm::TimeRecord::getCurrentTime(true);
653         if (Bucket)
654           *Bucket += Now;
655         if (NewBucket)
656           *NewBucket -= Now;
657         Bucket = NewBucket;
658       }
659     }
660 
661   private:
662     llvm::TimeRecord *Bucket;
663   };
664 
665   /// Runs all the \p Matchers on \p Node.
666   ///
667   /// Used by \c matchDispatch() below.
668   template <typename T, typename MC>
669   void matchWithoutFilter(const T &Node, const MC &Matchers) {
670     const bool EnableCheckProfiling = Options.CheckProfiling.hasValue();
671     TimeBucketRegion Timer;
672     for (const auto &MP : Matchers) {
673       if (EnableCheckProfiling)
674         Timer.setBucket(&TimeByBucket[MP.second->getID()]);
675       BoundNodesTreeBuilder Builder;
676       if (MP.first.matches(Node, this, &Builder)) {
677         MatchVisitor Visitor(ActiveASTContext, MP.second);
678         Builder.visitMatches(&Visitor);
679       }
680     }
681   }
682 
683   void matchWithFilter(const DynTypedNode &DynNode) {
684     auto Kind = DynNode.getNodeKind();
685     auto it = MatcherFiltersMap.find(Kind);
686     const auto &Filter =
687         it != MatcherFiltersMap.end() ? it->second : getFilterForKind(Kind);
688 
689     if (Filter.empty())
690       return;
691 
692     const bool EnableCheckProfiling = Options.CheckProfiling.hasValue();
693     TimeBucketRegion Timer;
694     auto &Matchers = this->Matchers->DeclOrStmt;
695     for (unsigned short I : Filter) {
696       auto &MP = Matchers[I];
697       if (EnableCheckProfiling)
698         Timer.setBucket(&TimeByBucket[MP.second->getID()]);
699       BoundNodesTreeBuilder Builder;
700       if (MP.first.matches(DynNode, this, &Builder)) {
701         MatchVisitor Visitor(ActiveASTContext, MP.second);
702         Builder.visitMatches(&Visitor);
703       }
704     }
705   }
706 
707   const std::vector<unsigned short> &getFilterForKind(ASTNodeKind Kind) {
708     auto &Filter = MatcherFiltersMap[Kind];
709     auto &Matchers = this->Matchers->DeclOrStmt;
710     assert((Matchers.size() < USHRT_MAX) && "Too many matchers.");
711     for (unsigned I = 0, E = Matchers.size(); I != E; ++I) {
712       if (Matchers[I].first.canMatchNodesOfKind(Kind)) {
713         Filter.push_back(I);
714       }
715     }
716     return Filter;
717   }
718 
719   /// @{
720   /// Overloads to pair the different node types to their matchers.
721   void matchDispatch(const Decl *Node) {
722     return matchWithFilter(DynTypedNode::create(*Node));
723   }
724   void matchDispatch(const Stmt *Node) {
725     return matchWithFilter(DynTypedNode::create(*Node));
726   }
727 
728   void matchDispatch(const Type *Node) {
729     matchWithoutFilter(QualType(Node, 0), Matchers->Type);
730   }
731   void matchDispatch(const TypeLoc *Node) {
732     matchWithoutFilter(*Node, Matchers->TypeLoc);
733   }
734   void matchDispatch(const QualType *Node) {
735     matchWithoutFilter(*Node, Matchers->Type);
736   }
737   void matchDispatch(const NestedNameSpecifier *Node) {
738     matchWithoutFilter(*Node, Matchers->NestedNameSpecifier);
739   }
740   void matchDispatch(const NestedNameSpecifierLoc *Node) {
741     matchWithoutFilter(*Node, Matchers->NestedNameSpecifierLoc);
742   }
743   void matchDispatch(const CXXCtorInitializer *Node) {
744     matchWithoutFilter(*Node, Matchers->CtorInit);
745   }
746   void matchDispatch(const TemplateArgumentLoc *Node) {
747     matchWithoutFilter(*Node, Matchers->TemplateArgumentLoc);
748   }
749   void matchDispatch(const void *) { /* Do nothing. */ }
750   /// @}
751 
752   // Returns whether a direct parent of \p Node matches \p Matcher.
753   // Unlike matchesAnyAncestorOf there's no memoization: it doesn't save much.
754   bool matchesParentOf(const DynTypedNode &Node, const DynTypedMatcher &Matcher,
755                        BoundNodesTreeBuilder *Builder) {
756     for (const auto &Parent : ActiveASTContext->getParents(Node)) {
757       BoundNodesTreeBuilder BuilderCopy = *Builder;
758       if (Matcher.matches(Parent, this, &BuilderCopy)) {
759         *Builder = std::move(BuilderCopy);
760         return true;
761       }
762     }
763     return false;
764   }
765 
766   // Returns whether an ancestor of \p Node matches \p Matcher.
767   //
768   // The order of matching (which can lead to different nodes being bound in
769   // case there are multiple matches) is breadth first search.
770   //
771   // To allow memoization in the very common case of having deeply nested
772   // expressions inside a template function, we first walk up the AST, memoizing
773   // the result of the match along the way, as long as there is only a single
774   // parent.
775   //
776   // Once there are multiple parents, the breadth first search order does not
777   // allow simple memoization on the ancestors. Thus, we only memoize as long
778   // as there is a single parent.
779   //
780   // We avoid a recursive implementation to prevent excessive stack use on
781   // very deep ASTs (similarly to RecursiveASTVisitor's data recursion).
782   bool matchesAnyAncestorOf(DynTypedNode Node, ASTContext &Ctx,
783                             const DynTypedMatcher &Matcher,
784                             BoundNodesTreeBuilder *Builder) {
785 
786     // Memoization keys that can be updated with the result.
787     // These are the memoizable nodes in the chain of unique parents, which
788     // terminates when a node has multiple parents, or matches, or is the root.
789     std::vector<MatchKey> Keys;
790     // When returning, update the memoization cache.
791     auto Finish = [&](bool Matched) {
792       for (const auto &Key : Keys) {
793         MemoizedMatchResult &CachedResult = ResultCache[Key];
794         CachedResult.ResultOfMatch = Matched;
795         CachedResult.Nodes = *Builder;
796       }
797       return Matched;
798     };
799 
800     // Loop while there's a single parent and we want to attempt memoization.
801     DynTypedNodeList Parents{ArrayRef<DynTypedNode>()}; // after loop: size != 1
802     for (;;) {
803       // A cache key only makes sense if memoization is possible.
804       if (Builder->isComparable()) {
805         Keys.emplace_back();
806         Keys.back().MatcherID = Matcher.getID();
807         Keys.back().Node = Node;
808         Keys.back().BoundNodes = *Builder;
809         Keys.back().Traversal = Ctx.getParentMapContext().getTraversalKind();
810         Keys.back().Type = MatchType::Ancestors;
811 
812         // Check the cache.
813         MemoizationMap::iterator I = ResultCache.find(Keys.back());
814         if (I != ResultCache.end()) {
815           Keys.pop_back(); // Don't populate the cache for the matching node!
816           *Builder = I->second.Nodes;
817           return Finish(I->second.ResultOfMatch);
818         }
819       }
820 
821       Parents = ActiveASTContext->getParents(Node);
822       // Either no parents or multiple parents: leave chain+memoize mode and
823       // enter bfs+forgetful mode.
824       if (Parents.size() != 1)
825         break;
826 
827       // Check the next parent.
828       Node = *Parents.begin();
829       BoundNodesTreeBuilder BuilderCopy = *Builder;
830       if (Matcher.matches(Node, this, &BuilderCopy)) {
831         *Builder = std::move(BuilderCopy);
832         return Finish(true);
833       }
834     }
835     // We reached the end of the chain.
836 
837     if (Parents.empty()) {
838       // Nodes may have no parents if:
839       //  a) the node is the TranslationUnitDecl
840       //  b) we have a limited traversal scope that excludes the parent edges
841       //  c) there is a bug in the AST, and the node is not reachable
842       // Usually the traversal scope is the whole AST, which precludes b.
843       // Bugs are common enough that it's worthwhile asserting when we can.
844 #ifndef NDEBUG
845       if (!Node.get<TranslationUnitDecl>() &&
846           /* Traversal scope is full AST if any of the bounds are the TU */
847           llvm::any_of(ActiveASTContext->getTraversalScope(), [](Decl *D) {
848             return D->getKind() == Decl::TranslationUnit;
849           })) {
850         llvm::errs() << "Tried to match orphan node:\n";
851         Node.dump(llvm::errs(), *ActiveASTContext);
852         llvm_unreachable("Parent map should be complete!");
853       }
854 #endif
855     } else {
856       assert(Parents.size() > 1);
857       // BFS starting from the parents not yet considered.
858       // Memoization of newly visited nodes is not possible (but we still update
859       // results for the elements in the chain we found above).
860       std::deque<DynTypedNode> Queue(Parents.begin(), Parents.end());
861       llvm::DenseSet<const void *> Visited;
862       while (!Queue.empty()) {
863         BoundNodesTreeBuilder BuilderCopy = *Builder;
864         if (Matcher.matches(Queue.front(), this, &BuilderCopy)) {
865           *Builder = std::move(BuilderCopy);
866           return Finish(true);
867         }
868         for (const auto &Parent : ActiveASTContext->getParents(Queue.front())) {
869           // Make sure we do not visit the same node twice.
870           // Otherwise, we'll visit the common ancestors as often as there
871           // are splits on the way down.
872           if (Visited.insert(Parent.getMemoizationData()).second)
873             Queue.push_back(Parent);
874         }
875         Queue.pop_front();
876       }
877     }
878     return Finish(false);
879   }
880 
881   // Implements a BoundNodesTree::Visitor that calls a MatchCallback with
882   // the aggregated bound nodes for each match.
883   class MatchVisitor : public BoundNodesTreeBuilder::Visitor {
884   public:
885     MatchVisitor(ASTContext* Context,
886                  MatchFinder::MatchCallback* Callback)
887       : Context(Context),
888         Callback(Callback) {}
889 
890     void visitMatch(const BoundNodes& BoundNodesView) override {
891       Callback->run(MatchFinder::MatchResult(BoundNodesView, Context));
892     }
893 
894   private:
895     ASTContext* Context;
896     MatchFinder::MatchCallback* Callback;
897   };
898 
899   // Returns true if 'TypeNode' has an alias that matches the given matcher.
900   bool typeHasMatchingAlias(const Type *TypeNode,
901                             const Matcher<NamedDecl> &Matcher,
902                             BoundNodesTreeBuilder *Builder) {
903     const Type *const CanonicalType =
904       ActiveASTContext->getCanonicalType(TypeNode);
905     auto Aliases = TypeAliases.find(CanonicalType);
906     if (Aliases == TypeAliases.end())
907       return false;
908     for (const TypedefNameDecl *Alias : Aliases->second) {
909       BoundNodesTreeBuilder Result(*Builder);
910       if (Matcher.matches(*Alias, this, &Result)) {
911         *Builder = std::move(Result);
912         return true;
913       }
914     }
915     return false;
916   }
917 
918   bool
919   objcClassHasMatchingCompatibilityAlias(const ObjCInterfaceDecl *InterfaceDecl,
920                                          const Matcher<NamedDecl> &Matcher,
921                                          BoundNodesTreeBuilder *Builder) {
922     auto Aliases = CompatibleAliases.find(InterfaceDecl);
923     if (Aliases == CompatibleAliases.end())
924       return false;
925     for (const ObjCCompatibleAliasDecl *Alias : Aliases->second) {
926       BoundNodesTreeBuilder Result(*Builder);
927       if (Matcher.matches(*Alias, this, &Result)) {
928         *Builder = std::move(Result);
929         return true;
930       }
931     }
932     return false;
933   }
934 
935   /// Bucket to record map.
936   ///
937   /// Used to get the appropriate bucket for each matcher.
938   llvm::StringMap<llvm::TimeRecord> TimeByBucket;
939 
940   const MatchFinder::MatchersByType *Matchers;
941 
942   /// Filtered list of matcher indices for each matcher kind.
943   ///
944   /// \c Decl and \c Stmt toplevel matchers usually apply to a specific node
945   /// kind (and derived kinds) so it is a waste to try every matcher on every
946   /// node.
947   /// We precalculate a list of matchers that pass the toplevel restrict check.
948   llvm::DenseMap<ASTNodeKind, std::vector<unsigned short>> MatcherFiltersMap;
949 
950   const MatchFinder::MatchFinderOptions &Options;
951   ASTContext *ActiveASTContext;
952 
953   // Maps a canonical type to its TypedefDecls.
954   llvm::DenseMap<const Type*, std::set<const TypedefNameDecl*> > TypeAliases;
955 
956   // Maps an Objective-C interface to its ObjCCompatibleAliasDecls.
957   llvm::DenseMap<const ObjCInterfaceDecl *,
958                  llvm::SmallPtrSet<const ObjCCompatibleAliasDecl *, 2>>
959       CompatibleAliases;
960 
961   // Maps (matcher, node) -> the match result for memoization.
962   typedef std::map<MatchKey, MemoizedMatchResult> MemoizationMap;
963   MemoizationMap ResultCache;
964 };
965 
966 static CXXRecordDecl *
967 getAsCXXRecordDeclOrPrimaryTemplate(const Type *TypeNode) {
968   if (auto *RD = TypeNode->getAsCXXRecordDecl())
969     return RD;
970 
971   // Find the innermost TemplateSpecializationType that isn't an alias template.
972   auto *TemplateType = TypeNode->getAs<TemplateSpecializationType>();
973   while (TemplateType && TemplateType->isTypeAlias())
974     TemplateType =
975         TemplateType->getAliasedType()->getAs<TemplateSpecializationType>();
976 
977   // If this is the name of a (dependent) template specialization, use the
978   // definition of the template, even though it might be specialized later.
979   if (TemplateType)
980     if (auto *ClassTemplate = dyn_cast_or_null<ClassTemplateDecl>(
981           TemplateType->getTemplateName().getAsTemplateDecl()))
982       return ClassTemplate->getTemplatedDecl();
983 
984   return nullptr;
985 }
986 
987 // Returns true if the given C++ class is directly or indirectly derived
988 // from a base type with the given name.  A class is not considered to be
989 // derived from itself.
990 bool MatchASTVisitor::classIsDerivedFrom(const CXXRecordDecl *Declaration,
991                                          const Matcher<NamedDecl> &Base,
992                                          BoundNodesTreeBuilder *Builder,
993                                          bool Directly) {
994   if (!Declaration->hasDefinition())
995     return false;
996   for (const auto &It : Declaration->bases()) {
997     const Type *TypeNode = It.getType().getTypePtr();
998 
999     if (typeHasMatchingAlias(TypeNode, Base, Builder))
1000       return true;
1001 
1002     // FIXME: Going to the primary template here isn't really correct, but
1003     // unfortunately we accept a Decl matcher for the base class not a Type
1004     // matcher, so it's the best thing we can do with our current interface.
1005     CXXRecordDecl *ClassDecl = getAsCXXRecordDeclOrPrimaryTemplate(TypeNode);
1006     if (!ClassDecl)
1007       continue;
1008     if (ClassDecl == Declaration) {
1009       // This can happen for recursive template definitions.
1010       continue;
1011     }
1012     BoundNodesTreeBuilder Result(*Builder);
1013     if (Base.matches(*ClassDecl, this, &Result)) {
1014       *Builder = std::move(Result);
1015       return true;
1016     }
1017     if (!Directly && classIsDerivedFrom(ClassDecl, Base, Builder, Directly))
1018       return true;
1019   }
1020   return false;
1021 }
1022 
1023 // Returns true if the given Objective-C class is directly or indirectly
1024 // derived from a matching base class. A class is not considered to be derived
1025 // from itself.
1026 bool MatchASTVisitor::objcClassIsDerivedFrom(
1027     const ObjCInterfaceDecl *Declaration, const Matcher<NamedDecl> &Base,
1028     BoundNodesTreeBuilder *Builder, bool Directly) {
1029   // Check if any of the superclasses of the class match.
1030   for (const ObjCInterfaceDecl *ClassDecl = Declaration->getSuperClass();
1031        ClassDecl != nullptr; ClassDecl = ClassDecl->getSuperClass()) {
1032     // Check if there are any matching compatibility aliases.
1033     if (objcClassHasMatchingCompatibilityAlias(ClassDecl, Base, Builder))
1034       return true;
1035 
1036     // Check if there are any matching type aliases.
1037     const Type *TypeNode = ClassDecl->getTypeForDecl();
1038     if (typeHasMatchingAlias(TypeNode, Base, Builder))
1039       return true;
1040 
1041     if (Base.matches(*ClassDecl, this, Builder))
1042       return true;
1043 
1044     // Not `return false` as a temporary workaround for PR43879.
1045     if (Directly)
1046       break;
1047   }
1048 
1049   return false;
1050 }
1051 
1052 bool MatchASTVisitor::TraverseDecl(Decl *DeclNode) {
1053   if (!DeclNode) {
1054     return true;
1055   }
1056   match(*DeclNode);
1057   return RecursiveASTVisitor<MatchASTVisitor>::TraverseDecl(DeclNode);
1058 }
1059 
1060 bool MatchASTVisitor::TraverseStmt(Stmt *StmtNode, DataRecursionQueue *Queue) {
1061   if (!StmtNode) {
1062     return true;
1063   }
1064   match(*StmtNode);
1065   return RecursiveASTVisitor<MatchASTVisitor>::TraverseStmt(StmtNode, Queue);
1066 }
1067 
1068 bool MatchASTVisitor::TraverseType(QualType TypeNode) {
1069   match(TypeNode);
1070   return RecursiveASTVisitor<MatchASTVisitor>::TraverseType(TypeNode);
1071 }
1072 
1073 bool MatchASTVisitor::TraverseTypeLoc(TypeLoc TypeLocNode) {
1074   // The RecursiveASTVisitor only visits types if they're not within TypeLocs.
1075   // We still want to find those types via matchers, so we match them here. Note
1076   // that the TypeLocs are structurally a shadow-hierarchy to the expressed
1077   // type, so we visit all involved parts of a compound type when matching on
1078   // each TypeLoc.
1079   match(TypeLocNode);
1080   match(TypeLocNode.getType());
1081   return RecursiveASTVisitor<MatchASTVisitor>::TraverseTypeLoc(TypeLocNode);
1082 }
1083 
1084 bool MatchASTVisitor::TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
1085   match(*NNS);
1086   return RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifier(NNS);
1087 }
1088 
1089 bool MatchASTVisitor::TraverseNestedNameSpecifierLoc(
1090     NestedNameSpecifierLoc NNS) {
1091   if (!NNS)
1092     return true;
1093 
1094   match(NNS);
1095 
1096   // We only match the nested name specifier here (as opposed to traversing it)
1097   // because the traversal is already done in the parallel "Loc"-hierarchy.
1098   if (NNS.hasQualifier())
1099     match(*NNS.getNestedNameSpecifier());
1100   return
1101       RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifierLoc(NNS);
1102 }
1103 
1104 bool MatchASTVisitor::TraverseConstructorInitializer(
1105     CXXCtorInitializer *CtorInit) {
1106   if (!CtorInit)
1107     return true;
1108 
1109   match(*CtorInit);
1110 
1111   return RecursiveASTVisitor<MatchASTVisitor>::TraverseConstructorInitializer(
1112       CtorInit);
1113 }
1114 
1115 bool MatchASTVisitor::TraverseTemplateArgumentLoc(TemplateArgumentLoc Loc) {
1116   match(Loc);
1117   return RecursiveASTVisitor<MatchASTVisitor>::TraverseTemplateArgumentLoc(Loc);
1118 }
1119 
1120 class MatchASTConsumer : public ASTConsumer {
1121 public:
1122   MatchASTConsumer(MatchFinder *Finder,
1123                    MatchFinder::ParsingDoneTestCallback *ParsingDone)
1124       : Finder(Finder), ParsingDone(ParsingDone) {}
1125 
1126 private:
1127   void HandleTranslationUnit(ASTContext &Context) override {
1128     if (ParsingDone != nullptr) {
1129       ParsingDone->run();
1130     }
1131     Finder->matchAST(Context);
1132   }
1133 
1134   MatchFinder *Finder;
1135   MatchFinder::ParsingDoneTestCallback *ParsingDone;
1136 };
1137 
1138 } // end namespace
1139 } // end namespace internal
1140 
1141 MatchFinder::MatchResult::MatchResult(const BoundNodes &Nodes,
1142                                       ASTContext *Context)
1143   : Nodes(Nodes), Context(Context),
1144     SourceManager(&Context->getSourceManager()) {}
1145 
1146 MatchFinder::MatchCallback::~MatchCallback() {}
1147 MatchFinder::ParsingDoneTestCallback::~ParsingDoneTestCallback() {}
1148 
1149 MatchFinder::MatchFinder(MatchFinderOptions Options)
1150     : Options(std::move(Options)), ParsingDone(nullptr) {}
1151 
1152 MatchFinder::~MatchFinder() {}
1153 
1154 void MatchFinder::addMatcher(const DeclarationMatcher &NodeMatch,
1155                              MatchCallback *Action) {
1156   Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
1157   Matchers.AllCallbacks.insert(Action);
1158 }
1159 
1160 void MatchFinder::addMatcher(const TypeMatcher &NodeMatch,
1161                              MatchCallback *Action) {
1162   Matchers.Type.emplace_back(NodeMatch, Action);
1163   Matchers.AllCallbacks.insert(Action);
1164 }
1165 
1166 void MatchFinder::addMatcher(const StatementMatcher &NodeMatch,
1167                              MatchCallback *Action) {
1168   Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
1169   Matchers.AllCallbacks.insert(Action);
1170 }
1171 
1172 void MatchFinder::addMatcher(const NestedNameSpecifierMatcher &NodeMatch,
1173                              MatchCallback *Action) {
1174   Matchers.NestedNameSpecifier.emplace_back(NodeMatch, Action);
1175   Matchers.AllCallbacks.insert(Action);
1176 }
1177 
1178 void MatchFinder::addMatcher(const NestedNameSpecifierLocMatcher &NodeMatch,
1179                              MatchCallback *Action) {
1180   Matchers.NestedNameSpecifierLoc.emplace_back(NodeMatch, Action);
1181   Matchers.AllCallbacks.insert(Action);
1182 }
1183 
1184 void MatchFinder::addMatcher(const TypeLocMatcher &NodeMatch,
1185                              MatchCallback *Action) {
1186   Matchers.TypeLoc.emplace_back(NodeMatch, Action);
1187   Matchers.AllCallbacks.insert(Action);
1188 }
1189 
1190 void MatchFinder::addMatcher(const CXXCtorInitializerMatcher &NodeMatch,
1191                              MatchCallback *Action) {
1192   Matchers.CtorInit.emplace_back(NodeMatch, Action);
1193   Matchers.AllCallbacks.insert(Action);
1194 }
1195 
1196 void MatchFinder::addMatcher(const TemplateArgumentLocMatcher &NodeMatch,
1197                              MatchCallback *Action) {
1198   Matchers.TemplateArgumentLoc.emplace_back(NodeMatch, Action);
1199   Matchers.AllCallbacks.insert(Action);
1200 }
1201 
1202 bool MatchFinder::addDynamicMatcher(const internal::DynTypedMatcher &NodeMatch,
1203                                     MatchCallback *Action) {
1204   if (NodeMatch.canConvertTo<Decl>()) {
1205     addMatcher(NodeMatch.convertTo<Decl>(), Action);
1206     return true;
1207   } else if (NodeMatch.canConvertTo<QualType>()) {
1208     addMatcher(NodeMatch.convertTo<QualType>(), Action);
1209     return true;
1210   } else if (NodeMatch.canConvertTo<Stmt>()) {
1211     addMatcher(NodeMatch.convertTo<Stmt>(), Action);
1212     return true;
1213   } else if (NodeMatch.canConvertTo<NestedNameSpecifier>()) {
1214     addMatcher(NodeMatch.convertTo<NestedNameSpecifier>(), Action);
1215     return true;
1216   } else if (NodeMatch.canConvertTo<NestedNameSpecifierLoc>()) {
1217     addMatcher(NodeMatch.convertTo<NestedNameSpecifierLoc>(), Action);
1218     return true;
1219   } else if (NodeMatch.canConvertTo<TypeLoc>()) {
1220     addMatcher(NodeMatch.convertTo<TypeLoc>(), Action);
1221     return true;
1222   } else if (NodeMatch.canConvertTo<CXXCtorInitializer>()) {
1223     addMatcher(NodeMatch.convertTo<CXXCtorInitializer>(), Action);
1224     return true;
1225   } else if (NodeMatch.canConvertTo<TemplateArgumentLoc>()) {
1226     addMatcher(NodeMatch.convertTo<TemplateArgumentLoc>(), Action);
1227     return true;
1228   }
1229   return false;
1230 }
1231 
1232 std::unique_ptr<ASTConsumer> MatchFinder::newASTConsumer() {
1233   return std::make_unique<internal::MatchASTConsumer>(this, ParsingDone);
1234 }
1235 
1236 void MatchFinder::match(const clang::DynTypedNode &Node, ASTContext &Context) {
1237   internal::MatchASTVisitor Visitor(&Matchers, Options);
1238   Visitor.set_active_ast_context(&Context);
1239   Visitor.match(Node);
1240 }
1241 
1242 void MatchFinder::matchAST(ASTContext &Context) {
1243   internal::MatchASTVisitor Visitor(&Matchers, Options);
1244   Visitor.set_active_ast_context(&Context);
1245   Visitor.onStartOfTranslationUnit();
1246   Visitor.TraverseAST(Context);
1247   Visitor.onEndOfTranslationUnit();
1248 }
1249 
1250 void MatchFinder::registerTestCallbackAfterParsing(
1251     MatchFinder::ParsingDoneTestCallback *NewParsingDone) {
1252   ParsingDone = NewParsingDone;
1253 }
1254 
1255 StringRef MatchFinder::MatchCallback::getID() const { return "<unknown>"; }
1256 
1257 } // end namespace ast_matchers
1258 } // end namespace clang
1259