ASTMatchFinder.cpp 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694
  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. #include "clang/ASTMatchers/ASTMatchFinder.h"
  18. #include "clang/AST/ASTConsumer.h"
  19. #include "clang/AST/ASTContext.h"
  20. #include "clang/AST/RecursiveASTVisitor.h"
  21. #include "llvm/ADT/DenseMap.h"
  22. #include "llvm/ADT/StringMap.h"
  23. #include "llvm/Support/PrettyStackTrace.h"
  24. #include "llvm/Support/Timer.h"
  25. #include <deque>
  26. #include <memory>
  27. #include <set>
  28. namespace clang {
  29. namespace ast_matchers {
  30. namespace internal {
  31. namespace {
  32. typedef MatchFinder::MatchCallback MatchCallback;
  33. // The maximum number of memoization entries to store.
  34. // 10k has been experimentally found to give a good trade-off
  35. // of performance vs. memory consumption by running matcher
  36. // that match on every statement over a very large codebase.
  37. //
  38. // FIXME: Do some performance optimization in general and
  39. // revisit this number; also, put up micro-benchmarks that we can
  40. // optimize this on.
  41. static const unsigned MaxMemoizationEntries = 10000;
  42. enum class MatchType {
  43. Ancestors,
  44. Descendants,
  45. Child,
  46. };
  47. // We use memoization to avoid running the same matcher on the same
  48. // AST node twice. This struct is the key for looking up match
  49. // result. It consists of an ID of the MatcherInterface (for
  50. // identifying the matcher), a pointer to the AST node and the
  51. // bound nodes before the matcher was executed.
  52. //
  53. // We currently only memoize on nodes whose pointers identify the
  54. // nodes (\c Stmt and \c Decl, but not \c QualType or \c TypeLoc).
  55. // For \c QualType and \c TypeLoc it is possible to implement
  56. // generation of keys for each type.
  57. // FIXME: Benchmark whether memoization of non-pointer typed nodes
  58. // provides enough benefit for the additional amount of code.
  59. struct MatchKey {
  60. DynTypedMatcher::MatcherIDType MatcherID;
  61. DynTypedNode Node;
  62. BoundNodesTreeBuilder BoundNodes;
  63. TraversalKind Traversal = TK_AsIs;
  64. MatchType Type;
  65. bool operator<(const MatchKey &Other) const {
  66. return std::tie(Traversal, Type, MatcherID, Node, BoundNodes) <
  67. std::tie(Other.Traversal, Other.Type, Other.MatcherID, Other.Node,
  68. Other.BoundNodes);
  69. }
  70. };
  71. // Used to store the result of a match and possibly bound nodes.
  72. struct MemoizedMatchResult {
  73. bool ResultOfMatch;
  74. BoundNodesTreeBuilder Nodes;
  75. };
  76. // A RecursiveASTVisitor that traverses all children or all descendants of
  77. // a node.
  78. class MatchChildASTVisitor
  79. : public RecursiveASTVisitor<MatchChildASTVisitor> {
  80. public:
  81. typedef RecursiveASTVisitor<MatchChildASTVisitor> VisitorBase;
  82. // Creates an AST visitor that matches 'matcher' on all children or
  83. // descendants of a traversed node. max_depth is the maximum depth
  84. // to traverse: use 1 for matching the children and INT_MAX for
  85. // matching the descendants.
  86. MatchChildASTVisitor(const DynTypedMatcher *Matcher, ASTMatchFinder *Finder,
  87. BoundNodesTreeBuilder *Builder, int MaxDepth,
  88. bool IgnoreImplicitChildren,
  89. ASTMatchFinder::BindKind Bind)
  90. : Matcher(Matcher), Finder(Finder), Builder(Builder), CurrentDepth(0),
  91. MaxDepth(MaxDepth), IgnoreImplicitChildren(IgnoreImplicitChildren),
  92. Bind(Bind), Matches(false) {}
  93. // Returns true if a match is found in the subtree rooted at the
  94. // given AST node. This is done via a set of mutually recursive
  95. // functions. Here's how the recursion is done (the *wildcard can
  96. // actually be Decl, Stmt, or Type):
  97. //
  98. // - Traverse(node) calls BaseTraverse(node) when it needs
  99. // to visit the descendants of node.
  100. // - BaseTraverse(node) then calls (via VisitorBase::Traverse*(node))
  101. // Traverse*(c) for each child c of 'node'.
  102. // - Traverse*(c) in turn calls Traverse(c), completing the
  103. // recursion.
  104. bool findMatch(const DynTypedNode &DynNode) {
  105. reset();
  106. if (const Decl *D = DynNode.get<Decl>())
  107. traverse(*D);
  108. else if (const Stmt *S = DynNode.get<Stmt>())
  109. traverse(*S);
  110. else if (const NestedNameSpecifier *NNS =
  111. DynNode.get<NestedNameSpecifier>())
  112. traverse(*NNS);
  113. else if (const NestedNameSpecifierLoc *NNSLoc =
  114. DynNode.get<NestedNameSpecifierLoc>())
  115. traverse(*NNSLoc);
  116. else if (const QualType *Q = DynNode.get<QualType>())
  117. traverse(*Q);
  118. else if (const TypeLoc *T = DynNode.get<TypeLoc>())
  119. traverse(*T);
  120. else if (const auto *C = DynNode.get<CXXCtorInitializer>())
  121. traverse(*C);
  122. else if (const TemplateArgumentLoc *TALoc =
  123. DynNode.get<TemplateArgumentLoc>())
  124. traverse(*TALoc);
  125. else if (const Attr *A = DynNode.get<Attr>())
  126. traverse(*A);
  127. // FIXME: Add other base types after adding tests.
  128. // It's OK to always overwrite the bound nodes, as if there was
  129. // no match in this recursive branch, the result set is empty
  130. // anyway.
  131. *Builder = ResultBindings;
  132. return Matches;
  133. }
  134. // The following are overriding methods from the base visitor class.
  135. // They are public only to allow CRTP to work. They are *not *part
  136. // of the public API of this class.
  137. bool TraverseDecl(Decl *DeclNode) {
  138. if (DeclNode && DeclNode->isImplicit() &&
  139. Finder->isTraversalIgnoringImplicitNodes())
  140. return baseTraverse(*DeclNode);
  141. ScopedIncrement ScopedDepth(&CurrentDepth);
  142. return (DeclNode == nullptr) || traverse(*DeclNode);
  143. }
  144. Stmt *getStmtToTraverse(Stmt *StmtNode) {
  145. Stmt *StmtToTraverse = StmtNode;
  146. if (auto *ExprNode = dyn_cast_or_null<Expr>(StmtNode)) {
  147. auto *LambdaNode = dyn_cast_or_null<LambdaExpr>(StmtNode);
  148. if (LambdaNode && Finder->isTraversalIgnoringImplicitNodes())
  149. StmtToTraverse = LambdaNode;
  150. else
  151. StmtToTraverse =
  152. Finder->getASTContext().getParentMapContext().traverseIgnored(
  153. ExprNode);
  154. }
  155. return StmtToTraverse;
  156. }
  157. bool TraverseStmt(Stmt *StmtNode, DataRecursionQueue *Queue = nullptr) {
  158. // If we need to keep track of the depth, we can't perform data recursion.
  159. if (CurrentDepth == 0 || (CurrentDepth <= MaxDepth && MaxDepth < INT_MAX))
  160. Queue = nullptr;
  161. ScopedIncrement ScopedDepth(&CurrentDepth);
  162. Stmt *StmtToTraverse = getStmtToTraverse(StmtNode);
  163. if (!StmtToTraverse)
  164. return true;
  165. if (IgnoreImplicitChildren && isa<CXXDefaultArgExpr>(StmtNode))
  166. return true;
  167. if (!match(*StmtToTraverse))
  168. return false;
  169. return VisitorBase::TraverseStmt(StmtToTraverse, Queue);
  170. }
  171. // We assume that the QualType and the contained type are on the same
  172. // hierarchy level. Thus, we try to match either of them.
  173. bool TraverseType(QualType TypeNode) {
  174. if (TypeNode.isNull())
  175. return true;
  176. ScopedIncrement ScopedDepth(&CurrentDepth);
  177. // Match the Type.
  178. if (!match(*TypeNode))
  179. return false;
  180. // The QualType is matched inside traverse.
  181. return traverse(TypeNode);
  182. }
  183. // We assume that the TypeLoc, contained QualType and contained Type all are
  184. // on the same hierarchy level. Thus, we try to match all of them.
  185. bool TraverseTypeLoc(TypeLoc TypeLocNode) {
  186. if (TypeLocNode.isNull())
  187. return true;
  188. ScopedIncrement ScopedDepth(&CurrentDepth);
  189. // Match the Type.
  190. if (!match(*TypeLocNode.getType()))
  191. return false;
  192. // Match the QualType.
  193. if (!match(TypeLocNode.getType()))
  194. return false;
  195. // The TypeLoc is matched inside traverse.
  196. return traverse(TypeLocNode);
  197. }
  198. bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
  199. ScopedIncrement ScopedDepth(&CurrentDepth);
  200. return (NNS == nullptr) || traverse(*NNS);
  201. }
  202. bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
  203. if (!NNS)
  204. return true;
  205. ScopedIncrement ScopedDepth(&CurrentDepth);
  206. if (!match(*NNS.getNestedNameSpecifier()))
  207. return false;
  208. return traverse(NNS);
  209. }
  210. bool TraverseConstructorInitializer(CXXCtorInitializer *CtorInit) {
  211. if (!CtorInit)
  212. return true;
  213. ScopedIncrement ScopedDepth(&CurrentDepth);
  214. return traverse(*CtorInit);
  215. }
  216. bool TraverseTemplateArgumentLoc(TemplateArgumentLoc TAL) {
  217. ScopedIncrement ScopedDepth(&CurrentDepth);
  218. return traverse(TAL);
  219. }
  220. bool TraverseCXXForRangeStmt(CXXForRangeStmt *Node) {
  221. if (!Finder->isTraversalIgnoringImplicitNodes())
  222. return VisitorBase::TraverseCXXForRangeStmt(Node);
  223. if (!Node)
  224. return true;
  225. ScopedIncrement ScopedDepth(&CurrentDepth);
  226. if (auto *Init = Node->getInit())
  227. if (!traverse(*Init))
  228. return false;
  229. if (!match(*Node->getLoopVariable()))
  230. return false;
  231. if (match(*Node->getRangeInit()))
  232. if (!VisitorBase::TraverseStmt(Node->getRangeInit()))
  233. return false;
  234. if (!match(*Node->getBody()))
  235. return false;
  236. return VisitorBase::TraverseStmt(Node->getBody());
  237. }
  238. bool TraverseCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *Node) {
  239. if (!Finder->isTraversalIgnoringImplicitNodes())
  240. return VisitorBase::TraverseCXXRewrittenBinaryOperator(Node);
  241. if (!Node)
  242. return true;
  243. ScopedIncrement ScopedDepth(&CurrentDepth);
  244. return match(*Node->getLHS()) && match(*Node->getRHS());
  245. }
  246. bool TraverseAttr(Attr *A) {
  247. if (A == nullptr ||
  248. (A->isImplicit() &&
  249. Finder->getASTContext().getParentMapContext().getTraversalKind() ==
  250. TK_IgnoreUnlessSpelledInSource))
  251. return true;
  252. ScopedIncrement ScopedDepth(&CurrentDepth);
  253. return traverse(*A);
  254. }
  255. bool TraverseLambdaExpr(LambdaExpr *Node) {
  256. if (!Finder->isTraversalIgnoringImplicitNodes())
  257. return VisitorBase::TraverseLambdaExpr(Node);
  258. if (!Node)
  259. return true;
  260. ScopedIncrement ScopedDepth(&CurrentDepth);
  261. for (unsigned I = 0, N = Node->capture_size(); I != N; ++I) {
  262. const auto *C = Node->capture_begin() + I;
  263. if (!C->isExplicit())
  264. continue;
  265. if (Node->isInitCapture(C) && !match(*C->getCapturedVar()))
  266. return false;
  267. if (!match(*Node->capture_init_begin()[I]))
  268. return false;
  269. }
  270. if (const auto *TPL = Node->getTemplateParameterList()) {
  271. for (const auto *TP : *TPL) {
  272. if (!match(*TP))
  273. return false;
  274. }
  275. }
  276. for (const auto *P : Node->getCallOperator()->parameters()) {
  277. if (!match(*P))
  278. return false;
  279. }
  280. if (!match(*Node->getBody()))
  281. return false;
  282. return VisitorBase::TraverseStmt(Node->getBody());
  283. }
  284. bool shouldVisitTemplateInstantiations() const { return true; }
  285. bool shouldVisitImplicitCode() const { return !IgnoreImplicitChildren; }
  286. private:
  287. // Used for updating the depth during traversal.
  288. struct ScopedIncrement {
  289. explicit ScopedIncrement(int *Depth) : Depth(Depth) { ++(*Depth); }
  290. ~ScopedIncrement() { --(*Depth); }
  291. private:
  292. int *Depth;
  293. };
  294. // Resets the state of this object.
  295. void reset() {
  296. Matches = false;
  297. CurrentDepth = 0;
  298. }
  299. // Forwards the call to the corresponding Traverse*() method in the
  300. // base visitor class.
  301. bool baseTraverse(const Decl &DeclNode) {
  302. return VisitorBase::TraverseDecl(const_cast<Decl*>(&DeclNode));
  303. }
  304. bool baseTraverse(const Stmt &StmtNode) {
  305. return VisitorBase::TraverseStmt(const_cast<Stmt*>(&StmtNode));
  306. }
  307. bool baseTraverse(QualType TypeNode) {
  308. return VisitorBase::TraverseType(TypeNode);
  309. }
  310. bool baseTraverse(TypeLoc TypeLocNode) {
  311. return VisitorBase::TraverseTypeLoc(TypeLocNode);
  312. }
  313. bool baseTraverse(const NestedNameSpecifier &NNS) {
  314. return VisitorBase::TraverseNestedNameSpecifier(
  315. const_cast<NestedNameSpecifier*>(&NNS));
  316. }
  317. bool baseTraverse(NestedNameSpecifierLoc NNS) {
  318. return VisitorBase::TraverseNestedNameSpecifierLoc(NNS);
  319. }
  320. bool baseTraverse(const CXXCtorInitializer &CtorInit) {
  321. return VisitorBase::TraverseConstructorInitializer(
  322. const_cast<CXXCtorInitializer *>(&CtorInit));
  323. }
  324. bool baseTraverse(TemplateArgumentLoc TAL) {
  325. return VisitorBase::TraverseTemplateArgumentLoc(TAL);
  326. }
  327. bool baseTraverse(const Attr &AttrNode) {
  328. return VisitorBase::TraverseAttr(const_cast<Attr *>(&AttrNode));
  329. }
  330. // Sets 'Matched' to true if 'Matcher' matches 'Node' and:
  331. // 0 < CurrentDepth <= MaxDepth.
  332. //
  333. // Returns 'true' if traversal should continue after this function
  334. // returns, i.e. if no match is found or 'Bind' is 'BK_All'.
  335. template <typename T>
  336. bool match(const T &Node) {
  337. if (CurrentDepth == 0 || CurrentDepth > MaxDepth) {
  338. return true;
  339. }
  340. if (Bind != ASTMatchFinder::BK_All) {
  341. BoundNodesTreeBuilder RecursiveBuilder(*Builder);
  342. if (Matcher->matches(DynTypedNode::create(Node), Finder,
  343. &RecursiveBuilder)) {
  344. Matches = true;
  345. ResultBindings.addMatch(RecursiveBuilder);
  346. return false; // Abort as soon as a match is found.
  347. }
  348. } else {
  349. BoundNodesTreeBuilder RecursiveBuilder(*Builder);
  350. if (Matcher->matches(DynTypedNode::create(Node), Finder,
  351. &RecursiveBuilder)) {
  352. // After the first match the matcher succeeds.
  353. Matches = true;
  354. ResultBindings.addMatch(RecursiveBuilder);
  355. }
  356. }
  357. return true;
  358. }
  359. // Traverses the subtree rooted at 'Node'; returns true if the
  360. // traversal should continue after this function returns.
  361. template <typename T>
  362. bool traverse(const T &Node) {
  363. static_assert(IsBaseType<T>::value,
  364. "traverse can only be instantiated with base type");
  365. if (!match(Node))
  366. return false;
  367. return baseTraverse(Node);
  368. }
  369. const DynTypedMatcher *const Matcher;
  370. ASTMatchFinder *const Finder;
  371. BoundNodesTreeBuilder *const Builder;
  372. BoundNodesTreeBuilder ResultBindings;
  373. int CurrentDepth;
  374. const int MaxDepth;
  375. const bool IgnoreImplicitChildren;
  376. const ASTMatchFinder::BindKind Bind;
  377. bool Matches;
  378. };
  379. // Controls the outermost traversal of the AST and allows to match multiple
  380. // matchers.
  381. class MatchASTVisitor : public RecursiveASTVisitor<MatchASTVisitor>,
  382. public ASTMatchFinder {
  383. public:
  384. MatchASTVisitor(const MatchFinder::MatchersByType *Matchers,
  385. const MatchFinder::MatchFinderOptions &Options)
  386. : Matchers(Matchers), Options(Options), ActiveASTContext(nullptr) {}
  387. ~MatchASTVisitor() override {
  388. if (Options.CheckProfiling) {
  389. Options.CheckProfiling->Records = std::move(TimeByBucket);
  390. }
  391. }
  392. void onStartOfTranslationUnit() {
  393. const bool EnableCheckProfiling = Options.CheckProfiling.has_value();
  394. TimeBucketRegion Timer;
  395. for (MatchCallback *MC : Matchers->AllCallbacks) {
  396. if (EnableCheckProfiling)
  397. Timer.setBucket(&TimeByBucket[MC->getID()]);
  398. MC->onStartOfTranslationUnit();
  399. }
  400. }
  401. void onEndOfTranslationUnit() {
  402. const bool EnableCheckProfiling = Options.CheckProfiling.has_value();
  403. TimeBucketRegion Timer;
  404. for (MatchCallback *MC : Matchers->AllCallbacks) {
  405. if (EnableCheckProfiling)
  406. Timer.setBucket(&TimeByBucket[MC->getID()]);
  407. MC->onEndOfTranslationUnit();
  408. }
  409. }
  410. void set_active_ast_context(ASTContext *NewActiveASTContext) {
  411. ActiveASTContext = NewActiveASTContext;
  412. }
  413. // The following Visit*() and Traverse*() functions "override"
  414. // methods in RecursiveASTVisitor.
  415. bool VisitTypedefNameDecl(TypedefNameDecl *DeclNode) {
  416. // When we see 'typedef A B', we add name 'B' to the set of names
  417. // A's canonical type maps to. This is necessary for implementing
  418. // isDerivedFrom(x) properly, where x can be the name of the base
  419. // class or any of its aliases.
  420. //
  421. // In general, the is-alias-of (as defined by typedefs) relation
  422. // is tree-shaped, as you can typedef a type more than once. For
  423. // example,
  424. //
  425. // typedef A B;
  426. // typedef A C;
  427. // typedef C D;
  428. // typedef C E;
  429. //
  430. // gives you
  431. //
  432. // A
  433. // |- B
  434. // `- C
  435. // |- D
  436. // `- E
  437. //
  438. // It is wrong to assume that the relation is a chain. A correct
  439. // implementation of isDerivedFrom() needs to recognize that B and
  440. // E are aliases, even though neither is a typedef of the other.
  441. // Therefore, we cannot simply walk through one typedef chain to
  442. // find out whether the type name matches.
  443. const Type *TypeNode = DeclNode->getUnderlyingType().getTypePtr();
  444. const Type *CanonicalType = // root of the typedef tree
  445. ActiveASTContext->getCanonicalType(TypeNode);
  446. TypeAliases[CanonicalType].insert(DeclNode);
  447. return true;
  448. }
  449. bool VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
  450. const ObjCInterfaceDecl *InterfaceDecl = CAD->getClassInterface();
  451. CompatibleAliases[InterfaceDecl].insert(CAD);
  452. return true;
  453. }
  454. bool TraverseDecl(Decl *DeclNode);
  455. bool TraverseStmt(Stmt *StmtNode, DataRecursionQueue *Queue = nullptr);
  456. bool TraverseType(QualType TypeNode);
  457. bool TraverseTypeLoc(TypeLoc TypeNode);
  458. bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS);
  459. bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
  460. bool TraverseConstructorInitializer(CXXCtorInitializer *CtorInit);
  461. bool TraverseTemplateArgumentLoc(TemplateArgumentLoc TAL);
  462. bool TraverseAttr(Attr *AttrNode);
  463. bool dataTraverseNode(Stmt *S, DataRecursionQueue *Queue) {
  464. if (auto *RF = dyn_cast<CXXForRangeStmt>(S)) {
  465. {
  466. ASTNodeNotAsIsSourceScope RAII(this, true);
  467. TraverseStmt(RF->getInit());
  468. // Don't traverse under the loop variable
  469. match(*RF->getLoopVariable());
  470. TraverseStmt(RF->getRangeInit());
  471. }
  472. {
  473. ASTNodeNotSpelledInSourceScope RAII(this, true);
  474. for (auto *SubStmt : RF->children()) {
  475. if (SubStmt != RF->getBody())
  476. TraverseStmt(SubStmt);
  477. }
  478. }
  479. TraverseStmt(RF->getBody());
  480. return true;
  481. } else if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) {
  482. {
  483. ASTNodeNotAsIsSourceScope RAII(this, true);
  484. TraverseStmt(const_cast<Expr *>(RBO->getLHS()));
  485. TraverseStmt(const_cast<Expr *>(RBO->getRHS()));
  486. }
  487. {
  488. ASTNodeNotSpelledInSourceScope RAII(this, true);
  489. for (auto *SubStmt : RBO->children()) {
  490. TraverseStmt(SubStmt);
  491. }
  492. }
  493. return true;
  494. } else if (auto *LE = dyn_cast<LambdaExpr>(S)) {
  495. for (auto I : llvm::zip(LE->captures(), LE->capture_inits())) {
  496. auto C = std::get<0>(I);
  497. ASTNodeNotSpelledInSourceScope RAII(
  498. this, TraversingASTNodeNotSpelledInSource || !C.isExplicit());
  499. TraverseLambdaCapture(LE, &C, std::get<1>(I));
  500. }
  501. {
  502. ASTNodeNotSpelledInSourceScope RAII(this, true);
  503. TraverseDecl(LE->getLambdaClass());
  504. }
  505. {
  506. ASTNodeNotAsIsSourceScope RAII(this, true);
  507. // We need to poke around to find the bits that might be explicitly
  508. // written.
  509. TypeLoc TL = LE->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
  510. FunctionProtoTypeLoc Proto = TL.getAsAdjusted<FunctionProtoTypeLoc>();
  511. if (auto *TPL = LE->getTemplateParameterList()) {
  512. for (NamedDecl *D : *TPL) {
  513. TraverseDecl(D);
  514. }
  515. if (Expr *RequiresClause = TPL->getRequiresClause()) {
  516. TraverseStmt(RequiresClause);
  517. }
  518. }
  519. if (LE->hasExplicitParameters()) {
  520. // Visit parameters.
  521. for (ParmVarDecl *Param : Proto.getParams())
  522. TraverseDecl(Param);
  523. }
  524. const auto *T = Proto.getTypePtr();
  525. for (const auto &E : T->exceptions())
  526. TraverseType(E);
  527. if (Expr *NE = T->getNoexceptExpr())
  528. TraverseStmt(NE, Queue);
  529. if (LE->hasExplicitResultType())
  530. TraverseTypeLoc(Proto.getReturnLoc());
  531. TraverseStmt(LE->getTrailingRequiresClause());
  532. }
  533. TraverseStmt(LE->getBody());
  534. return true;
  535. }
  536. return RecursiveASTVisitor<MatchASTVisitor>::dataTraverseNode(S, Queue);
  537. }
  538. // Matches children or descendants of 'Node' with 'BaseMatcher'.
  539. bool memoizedMatchesRecursively(const DynTypedNode &Node, ASTContext &Ctx,
  540. const DynTypedMatcher &Matcher,
  541. BoundNodesTreeBuilder *Builder, int MaxDepth,
  542. BindKind Bind) {
  543. // For AST-nodes that don't have an identity, we can't memoize.
  544. if (!Node.getMemoizationData() || !Builder->isComparable())
  545. return matchesRecursively(Node, Matcher, Builder, MaxDepth, Bind);
  546. MatchKey Key;
  547. Key.MatcherID = Matcher.getID();
  548. Key.Node = Node;
  549. // Note that we key on the bindings *before* the match.
  550. Key.BoundNodes = *Builder;
  551. Key.Traversal = Ctx.getParentMapContext().getTraversalKind();
  552. // Memoize result even doing a single-level match, it might be expensive.
  553. Key.Type = MaxDepth == 1 ? MatchType::Child : MatchType::Descendants;
  554. MemoizationMap::iterator I = ResultCache.find(Key);
  555. if (I != ResultCache.end()) {
  556. *Builder = I->second.Nodes;
  557. return I->second.ResultOfMatch;
  558. }
  559. MemoizedMatchResult Result;
  560. Result.Nodes = *Builder;
  561. Result.ResultOfMatch =
  562. matchesRecursively(Node, Matcher, &Result.Nodes, MaxDepth, Bind);
  563. MemoizedMatchResult &CachedResult = ResultCache[Key];
  564. CachedResult = std::move(Result);
  565. *Builder = CachedResult.Nodes;
  566. return CachedResult.ResultOfMatch;
  567. }
  568. // Matches children or descendants of 'Node' with 'BaseMatcher'.
  569. bool matchesRecursively(const DynTypedNode &Node,
  570. const DynTypedMatcher &Matcher,
  571. BoundNodesTreeBuilder *Builder, int MaxDepth,
  572. BindKind Bind) {
  573. bool ScopedTraversal = TraversingASTNodeNotSpelledInSource ||
  574. TraversingASTChildrenNotSpelledInSource;
  575. bool IgnoreImplicitChildren = false;
  576. if (isTraversalIgnoringImplicitNodes()) {
  577. IgnoreImplicitChildren = true;
  578. }
  579. ASTNodeNotSpelledInSourceScope RAII(this, ScopedTraversal);
  580. MatchChildASTVisitor Visitor(&Matcher, this, Builder, MaxDepth,
  581. IgnoreImplicitChildren, Bind);
  582. return Visitor.findMatch(Node);
  583. }
  584. bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
  585. const Matcher<NamedDecl> &Base,
  586. BoundNodesTreeBuilder *Builder,
  587. bool Directly) override;
  588. bool objcClassIsDerivedFrom(const ObjCInterfaceDecl *Declaration,
  589. const Matcher<NamedDecl> &Base,
  590. BoundNodesTreeBuilder *Builder,
  591. bool Directly) override;
  592. // Implements ASTMatchFinder::matchesChildOf.
  593. bool matchesChildOf(const DynTypedNode &Node, ASTContext &Ctx,
  594. const DynTypedMatcher &Matcher,
  595. BoundNodesTreeBuilder *Builder, BindKind Bind) override {
  596. if (ResultCache.size() > MaxMemoizationEntries)
  597. ResultCache.clear();
  598. return memoizedMatchesRecursively(Node, Ctx, Matcher, Builder, 1, Bind);
  599. }
  600. // Implements ASTMatchFinder::matchesDescendantOf.
  601. bool matchesDescendantOf(const DynTypedNode &Node, ASTContext &Ctx,
  602. const DynTypedMatcher &Matcher,
  603. BoundNodesTreeBuilder *Builder,
  604. BindKind Bind) override {
  605. if (ResultCache.size() > MaxMemoizationEntries)
  606. ResultCache.clear();
  607. return memoizedMatchesRecursively(Node, Ctx, Matcher, Builder, INT_MAX,
  608. Bind);
  609. }
  610. // Implements ASTMatchFinder::matchesAncestorOf.
  611. bool matchesAncestorOf(const DynTypedNode &Node, ASTContext &Ctx,
  612. const DynTypedMatcher &Matcher,
  613. BoundNodesTreeBuilder *Builder,
  614. AncestorMatchMode MatchMode) override {
  615. // Reset the cache outside of the recursive call to make sure we
  616. // don't invalidate any iterators.
  617. if (ResultCache.size() > MaxMemoizationEntries)
  618. ResultCache.clear();
  619. if (MatchMode == AncestorMatchMode::AMM_ParentOnly)
  620. return matchesParentOf(Node, Matcher, Builder);
  621. return matchesAnyAncestorOf(Node, Ctx, Matcher, Builder);
  622. }
  623. // Matches all registered matchers on the given node and calls the
  624. // result callback for every node that matches.
  625. void match(const DynTypedNode &Node) {
  626. // FIXME: Improve this with a switch or a visitor pattern.
  627. if (auto *N = Node.get<Decl>()) {
  628. match(*N);
  629. } else if (auto *N = Node.get<Stmt>()) {
  630. match(*N);
  631. } else if (auto *N = Node.get<Type>()) {
  632. match(*N);
  633. } else if (auto *N = Node.get<QualType>()) {
  634. match(*N);
  635. } else if (auto *N = Node.get<NestedNameSpecifier>()) {
  636. match(*N);
  637. } else if (auto *N = Node.get<NestedNameSpecifierLoc>()) {
  638. match(*N);
  639. } else if (auto *N = Node.get<TypeLoc>()) {
  640. match(*N);
  641. } else if (auto *N = Node.get<CXXCtorInitializer>()) {
  642. match(*N);
  643. } else if (auto *N = Node.get<TemplateArgumentLoc>()) {
  644. match(*N);
  645. } else if (auto *N = Node.get<Attr>()) {
  646. match(*N);
  647. }
  648. }
  649. template <typename T> void match(const T &Node) {
  650. matchDispatch(&Node);
  651. }
  652. // Implements ASTMatchFinder::getASTContext.
  653. ASTContext &getASTContext() const override { return *ActiveASTContext; }
  654. bool shouldVisitTemplateInstantiations() const { return true; }
  655. bool shouldVisitImplicitCode() const { return true; }
  656. // We visit the lambda body explicitly, so instruct the RAV
  657. // to not visit it on our behalf too.
  658. bool shouldVisitLambdaBody() const { return false; }
  659. bool IsMatchingInASTNodeNotSpelledInSource() const override {
  660. return TraversingASTNodeNotSpelledInSource;
  661. }
  662. bool isMatchingChildrenNotSpelledInSource() const override {
  663. return TraversingASTChildrenNotSpelledInSource;
  664. }
  665. void setMatchingChildrenNotSpelledInSource(bool Set) override {
  666. TraversingASTChildrenNotSpelledInSource = Set;
  667. }
  668. bool IsMatchingInASTNodeNotAsIs() const override {
  669. return TraversingASTNodeNotAsIs;
  670. }
  671. bool TraverseTemplateInstantiations(ClassTemplateDecl *D) {
  672. ASTNodeNotSpelledInSourceScope RAII(this, true);
  673. return RecursiveASTVisitor<MatchASTVisitor>::TraverseTemplateInstantiations(
  674. D);
  675. }
  676. bool TraverseTemplateInstantiations(VarTemplateDecl *D) {
  677. ASTNodeNotSpelledInSourceScope RAII(this, true);
  678. return RecursiveASTVisitor<MatchASTVisitor>::TraverseTemplateInstantiations(
  679. D);
  680. }
  681. bool TraverseTemplateInstantiations(FunctionTemplateDecl *D) {
  682. ASTNodeNotSpelledInSourceScope RAII(this, true);
  683. return RecursiveASTVisitor<MatchASTVisitor>::TraverseTemplateInstantiations(
  684. D);
  685. }
  686. private:
  687. bool TraversingASTNodeNotSpelledInSource = false;
  688. bool TraversingASTNodeNotAsIs = false;
  689. bool TraversingASTChildrenNotSpelledInSource = false;
  690. class CurMatchData {
  691. // We don't have enough free low bits in 32bit builds to discriminate 8 pointer
  692. // types in PointerUnion. so split the union in 2 using a free bit from the
  693. // callback pointer.
  694. #define CMD_TYPES_0 \
  695. const QualType *, const TypeLoc *, const NestedNameSpecifier *, \
  696. const NestedNameSpecifierLoc *
  697. #define CMD_TYPES_1 \
  698. const CXXCtorInitializer *, const TemplateArgumentLoc *, const Attr *, \
  699. const DynTypedNode *
  700. #define IMPL(Index) \
  701. template <typename NodeType> \
  702. std::enable_if_t< \
  703. llvm::is_one_of<const NodeType *, CMD_TYPES_##Index>::value> \
  704. SetCallbackAndRawNode(const MatchCallback *CB, const NodeType &N) { \
  705. assertEmpty(); \
  706. Callback.setPointerAndInt(CB, Index); \
  707. Node##Index = &N; \
  708. } \
  709. \
  710. template <typename T> \
  711. std::enable_if_t<llvm::is_one_of<const T *, CMD_TYPES_##Index>::value, \
  712. const T *> \
  713. getNode() const { \
  714. assertHoldsState(); \
  715. return Callback.getInt() == (Index) ? Node##Index.dyn_cast<const T *>() \
  716. : nullptr; \
  717. }
  718. public:
  719. CurMatchData() : Node0(nullptr) {}
  720. IMPL(0)
  721. IMPL(1)
  722. const MatchCallback *getCallback() const { return Callback.getPointer(); }
  723. void SetBoundNodes(const BoundNodes &BN) {
  724. assertHoldsState();
  725. BNodes = &BN;
  726. }
  727. void clearBoundNodes() {
  728. assertHoldsState();
  729. BNodes = nullptr;
  730. }
  731. const BoundNodes *getBoundNodes() const {
  732. assertHoldsState();
  733. return BNodes;
  734. }
  735. void reset() {
  736. assertHoldsState();
  737. Callback.setPointerAndInt(nullptr, 0);
  738. Node0 = nullptr;
  739. }
  740. private:
  741. void assertHoldsState() const {
  742. assert(Callback.getPointer() != nullptr && !Node0.isNull());
  743. }
  744. void assertEmpty() const {
  745. assert(Callback.getPointer() == nullptr && Node0.isNull() &&
  746. BNodes == nullptr);
  747. }
  748. llvm::PointerIntPair<const MatchCallback *, 1> Callback;
  749. union {
  750. llvm::PointerUnion<CMD_TYPES_0> Node0;
  751. llvm::PointerUnion<CMD_TYPES_1> Node1;
  752. };
  753. const BoundNodes *BNodes = nullptr;
  754. #undef CMD_TYPES_0
  755. #undef CMD_TYPES_1
  756. #undef IMPL
  757. } CurMatchState;
  758. struct CurMatchRAII {
  759. template <typename NodeType>
  760. CurMatchRAII(MatchASTVisitor &MV, const MatchCallback *CB,
  761. const NodeType &NT)
  762. : MV(MV) {
  763. MV.CurMatchState.SetCallbackAndRawNode(CB, NT);
  764. }
  765. ~CurMatchRAII() { MV.CurMatchState.reset(); }
  766. private:
  767. MatchASTVisitor &MV;
  768. };
  769. public:
  770. class TraceReporter : llvm::PrettyStackTraceEntry {
  771. static void dumpNode(const ASTContext &Ctx, const DynTypedNode &Node,
  772. raw_ostream &OS) {
  773. if (const auto *D = Node.get<Decl>()) {
  774. OS << D->getDeclKindName() << "Decl ";
  775. if (const auto *ND = dyn_cast<NamedDecl>(D)) {
  776. ND->printQualifiedName(OS);
  777. OS << " : ";
  778. } else
  779. OS << ": ";
  780. D->getSourceRange().print(OS, Ctx.getSourceManager());
  781. } else if (const auto *S = Node.get<Stmt>()) {
  782. OS << S->getStmtClassName() << " : ";
  783. S->getSourceRange().print(OS, Ctx.getSourceManager());
  784. } else if (const auto *T = Node.get<Type>()) {
  785. OS << T->getTypeClassName() << "Type : ";
  786. QualType(T, 0).print(OS, Ctx.getPrintingPolicy());
  787. } else if (const auto *QT = Node.get<QualType>()) {
  788. OS << "QualType : ";
  789. QT->print(OS, Ctx.getPrintingPolicy());
  790. } else {
  791. OS << Node.getNodeKind().asStringRef() << " : ";
  792. Node.getSourceRange().print(OS, Ctx.getSourceManager());
  793. }
  794. }
  795. static void dumpNodeFromState(const ASTContext &Ctx,
  796. const CurMatchData &State, raw_ostream &OS) {
  797. if (const DynTypedNode *MatchNode = State.getNode<DynTypedNode>()) {
  798. dumpNode(Ctx, *MatchNode, OS);
  799. } else if (const auto *QT = State.getNode<QualType>()) {
  800. dumpNode(Ctx, DynTypedNode::create(*QT), OS);
  801. } else if (const auto *TL = State.getNode<TypeLoc>()) {
  802. dumpNode(Ctx, DynTypedNode::create(*TL), OS);
  803. } else if (const auto *NNS = State.getNode<NestedNameSpecifier>()) {
  804. dumpNode(Ctx, DynTypedNode::create(*NNS), OS);
  805. } else if (const auto *NNSL = State.getNode<NestedNameSpecifierLoc>()) {
  806. dumpNode(Ctx, DynTypedNode::create(*NNSL), OS);
  807. } else if (const auto *CtorInit = State.getNode<CXXCtorInitializer>()) {
  808. dumpNode(Ctx, DynTypedNode::create(*CtorInit), OS);
  809. } else if (const auto *TAL = State.getNode<TemplateArgumentLoc>()) {
  810. dumpNode(Ctx, DynTypedNode::create(*TAL), OS);
  811. } else if (const auto *At = State.getNode<Attr>()) {
  812. dumpNode(Ctx, DynTypedNode::create(*At), OS);
  813. }
  814. }
  815. public:
  816. TraceReporter(const MatchASTVisitor &MV) : MV(MV) {}
  817. void print(raw_ostream &OS) const override {
  818. const CurMatchData &State = MV.CurMatchState;
  819. const MatchCallback *CB = State.getCallback();
  820. if (!CB) {
  821. OS << "ASTMatcher: Not currently matching\n";
  822. return;
  823. }
  824. assert(MV.ActiveASTContext &&
  825. "ActiveASTContext should be set if there is a matched callback");
  826. ASTContext &Ctx = MV.getASTContext();
  827. if (const BoundNodes *Nodes = State.getBoundNodes()) {
  828. OS << "ASTMatcher: Processing '" << CB->getID() << "' against:\n\t";
  829. dumpNodeFromState(Ctx, State, OS);
  830. const BoundNodes::IDToNodeMap &Map = Nodes->getMap();
  831. if (Map.empty()) {
  832. OS << "\nNo bound nodes\n";
  833. return;
  834. }
  835. OS << "\n--- Bound Nodes Begin ---\n";
  836. for (const auto &Item : Map) {
  837. OS << " " << Item.first << " - { ";
  838. dumpNode(Ctx, Item.second, OS);
  839. OS << " }\n";
  840. }
  841. OS << "--- Bound Nodes End ---\n";
  842. } else {
  843. OS << "ASTMatcher: Matching '" << CB->getID() << "' against:\n\t";
  844. dumpNodeFromState(Ctx, State, OS);
  845. OS << '\n';
  846. }
  847. }
  848. private:
  849. const MatchASTVisitor &MV;
  850. };
  851. private:
  852. struct ASTNodeNotSpelledInSourceScope {
  853. ASTNodeNotSpelledInSourceScope(MatchASTVisitor *V, bool B)
  854. : MV(V), MB(V->TraversingASTNodeNotSpelledInSource) {
  855. V->TraversingASTNodeNotSpelledInSource = B;
  856. }
  857. ~ASTNodeNotSpelledInSourceScope() {
  858. MV->TraversingASTNodeNotSpelledInSource = MB;
  859. }
  860. private:
  861. MatchASTVisitor *MV;
  862. bool MB;
  863. };
  864. struct ASTNodeNotAsIsSourceScope {
  865. ASTNodeNotAsIsSourceScope(MatchASTVisitor *V, bool B)
  866. : MV(V), MB(V->TraversingASTNodeNotAsIs) {
  867. V->TraversingASTNodeNotAsIs = B;
  868. }
  869. ~ASTNodeNotAsIsSourceScope() { MV->TraversingASTNodeNotAsIs = MB; }
  870. private:
  871. MatchASTVisitor *MV;
  872. bool MB;
  873. };
  874. class TimeBucketRegion {
  875. public:
  876. TimeBucketRegion() : Bucket(nullptr) {}
  877. ~TimeBucketRegion() { setBucket(nullptr); }
  878. /// Start timing for \p NewBucket.
  879. ///
  880. /// If there was a bucket already set, it will finish the timing for that
  881. /// other bucket.
  882. /// \p NewBucket will be timed until the next call to \c setBucket() or
  883. /// until the \c TimeBucketRegion is destroyed.
  884. /// If \p NewBucket is the same as the currently timed bucket, this call
  885. /// does nothing.
  886. void setBucket(llvm::TimeRecord *NewBucket) {
  887. if (Bucket != NewBucket) {
  888. auto Now = llvm::TimeRecord::getCurrentTime(true);
  889. if (Bucket)
  890. *Bucket += Now;
  891. if (NewBucket)
  892. *NewBucket -= Now;
  893. Bucket = NewBucket;
  894. }
  895. }
  896. private:
  897. llvm::TimeRecord *Bucket;
  898. };
  899. /// Runs all the \p Matchers on \p Node.
  900. ///
  901. /// Used by \c matchDispatch() below.
  902. template <typename T, typename MC>
  903. void matchWithoutFilter(const T &Node, const MC &Matchers) {
  904. const bool EnableCheckProfiling = Options.CheckProfiling.has_value();
  905. TimeBucketRegion Timer;
  906. for (const auto &MP : Matchers) {
  907. if (EnableCheckProfiling)
  908. Timer.setBucket(&TimeByBucket[MP.second->getID()]);
  909. BoundNodesTreeBuilder Builder;
  910. CurMatchRAII RAII(*this, MP.second, Node);
  911. if (MP.first.matches(Node, this, &Builder)) {
  912. MatchVisitor Visitor(*this, ActiveASTContext, MP.second);
  913. Builder.visitMatches(&Visitor);
  914. }
  915. }
  916. }
  917. void matchWithFilter(const DynTypedNode &DynNode) {
  918. auto Kind = DynNode.getNodeKind();
  919. auto it = MatcherFiltersMap.find(Kind);
  920. const auto &Filter =
  921. it != MatcherFiltersMap.end() ? it->second : getFilterForKind(Kind);
  922. if (Filter.empty())
  923. return;
  924. const bool EnableCheckProfiling = Options.CheckProfiling.has_value();
  925. TimeBucketRegion Timer;
  926. auto &Matchers = this->Matchers->DeclOrStmt;
  927. for (unsigned short I : Filter) {
  928. auto &MP = Matchers[I];
  929. if (EnableCheckProfiling)
  930. Timer.setBucket(&TimeByBucket[MP.second->getID()]);
  931. BoundNodesTreeBuilder Builder;
  932. {
  933. TraversalKindScope RAII(getASTContext(), MP.first.getTraversalKind());
  934. if (getASTContext().getParentMapContext().traverseIgnored(DynNode) !=
  935. DynNode)
  936. continue;
  937. }
  938. CurMatchRAII RAII(*this, MP.second, DynNode);
  939. if (MP.first.matches(DynNode, this, &Builder)) {
  940. MatchVisitor Visitor(*this, ActiveASTContext, MP.second);
  941. Builder.visitMatches(&Visitor);
  942. }
  943. }
  944. }
  945. const std::vector<unsigned short> &getFilterForKind(ASTNodeKind Kind) {
  946. auto &Filter = MatcherFiltersMap[Kind];
  947. auto &Matchers = this->Matchers->DeclOrStmt;
  948. assert((Matchers.size() < USHRT_MAX) && "Too many matchers.");
  949. for (unsigned I = 0, E = Matchers.size(); I != E; ++I) {
  950. if (Matchers[I].first.canMatchNodesOfKind(Kind)) {
  951. Filter.push_back(I);
  952. }
  953. }
  954. return Filter;
  955. }
  956. /// @{
  957. /// Overloads to pair the different node types to their matchers.
  958. void matchDispatch(const Decl *Node) {
  959. return matchWithFilter(DynTypedNode::create(*Node));
  960. }
  961. void matchDispatch(const Stmt *Node) {
  962. return matchWithFilter(DynTypedNode::create(*Node));
  963. }
  964. void matchDispatch(const Type *Node) {
  965. matchWithoutFilter(QualType(Node, 0), Matchers->Type);
  966. }
  967. void matchDispatch(const TypeLoc *Node) {
  968. matchWithoutFilter(*Node, Matchers->TypeLoc);
  969. }
  970. void matchDispatch(const QualType *Node) {
  971. matchWithoutFilter(*Node, Matchers->Type);
  972. }
  973. void matchDispatch(const NestedNameSpecifier *Node) {
  974. matchWithoutFilter(*Node, Matchers->NestedNameSpecifier);
  975. }
  976. void matchDispatch(const NestedNameSpecifierLoc *Node) {
  977. matchWithoutFilter(*Node, Matchers->NestedNameSpecifierLoc);
  978. }
  979. void matchDispatch(const CXXCtorInitializer *Node) {
  980. matchWithoutFilter(*Node, Matchers->CtorInit);
  981. }
  982. void matchDispatch(const TemplateArgumentLoc *Node) {
  983. matchWithoutFilter(*Node, Matchers->TemplateArgumentLoc);
  984. }
  985. void matchDispatch(const Attr *Node) {
  986. matchWithoutFilter(*Node, Matchers->Attr);
  987. }
  988. void matchDispatch(const void *) { /* Do nothing. */ }
  989. /// @}
  990. // Returns whether a direct parent of \p Node matches \p Matcher.
  991. // Unlike matchesAnyAncestorOf there's no memoization: it doesn't save much.
  992. bool matchesParentOf(const DynTypedNode &Node, const DynTypedMatcher &Matcher,
  993. BoundNodesTreeBuilder *Builder) {
  994. for (const auto &Parent : ActiveASTContext->getParents(Node)) {
  995. BoundNodesTreeBuilder BuilderCopy = *Builder;
  996. if (Matcher.matches(Parent, this, &BuilderCopy)) {
  997. *Builder = std::move(BuilderCopy);
  998. return true;
  999. }
  1000. }
  1001. return false;
  1002. }
  1003. // Returns whether an ancestor of \p Node matches \p Matcher.
  1004. //
  1005. // The order of matching (which can lead to different nodes being bound in
  1006. // case there are multiple matches) is breadth first search.
  1007. //
  1008. // To allow memoization in the very common case of having deeply nested
  1009. // expressions inside a template function, we first walk up the AST, memoizing
  1010. // the result of the match along the way, as long as there is only a single
  1011. // parent.
  1012. //
  1013. // Once there are multiple parents, the breadth first search order does not
  1014. // allow simple memoization on the ancestors. Thus, we only memoize as long
  1015. // as there is a single parent.
  1016. //
  1017. // We avoid a recursive implementation to prevent excessive stack use on
  1018. // very deep ASTs (similarly to RecursiveASTVisitor's data recursion).
  1019. bool matchesAnyAncestorOf(DynTypedNode Node, ASTContext &Ctx,
  1020. const DynTypedMatcher &Matcher,
  1021. BoundNodesTreeBuilder *Builder) {
  1022. // Memoization keys that can be updated with the result.
  1023. // These are the memoizable nodes in the chain of unique parents, which
  1024. // terminates when a node has multiple parents, or matches, or is the root.
  1025. std::vector<MatchKey> Keys;
  1026. // When returning, update the memoization cache.
  1027. auto Finish = [&](bool Matched) {
  1028. for (const auto &Key : Keys) {
  1029. MemoizedMatchResult &CachedResult = ResultCache[Key];
  1030. CachedResult.ResultOfMatch = Matched;
  1031. CachedResult.Nodes = *Builder;
  1032. }
  1033. return Matched;
  1034. };
  1035. // Loop while there's a single parent and we want to attempt memoization.
  1036. DynTypedNodeList Parents{ArrayRef<DynTypedNode>()}; // after loop: size != 1
  1037. for (;;) {
  1038. // A cache key only makes sense if memoization is possible.
  1039. if (Builder->isComparable()) {
  1040. Keys.emplace_back();
  1041. Keys.back().MatcherID = Matcher.getID();
  1042. Keys.back().Node = Node;
  1043. Keys.back().BoundNodes = *Builder;
  1044. Keys.back().Traversal = Ctx.getParentMapContext().getTraversalKind();
  1045. Keys.back().Type = MatchType::Ancestors;
  1046. // Check the cache.
  1047. MemoizationMap::iterator I = ResultCache.find(Keys.back());
  1048. if (I != ResultCache.end()) {
  1049. Keys.pop_back(); // Don't populate the cache for the matching node!
  1050. *Builder = I->second.Nodes;
  1051. return Finish(I->second.ResultOfMatch);
  1052. }
  1053. }
  1054. Parents = ActiveASTContext->getParents(Node);
  1055. // Either no parents or multiple parents: leave chain+memoize mode and
  1056. // enter bfs+forgetful mode.
  1057. if (Parents.size() != 1)
  1058. break;
  1059. // Check the next parent.
  1060. Node = *Parents.begin();
  1061. BoundNodesTreeBuilder BuilderCopy = *Builder;
  1062. if (Matcher.matches(Node, this, &BuilderCopy)) {
  1063. *Builder = std::move(BuilderCopy);
  1064. return Finish(true);
  1065. }
  1066. }
  1067. // We reached the end of the chain.
  1068. if (Parents.empty()) {
  1069. // Nodes may have no parents if:
  1070. // a) the node is the TranslationUnitDecl
  1071. // b) we have a limited traversal scope that excludes the parent edges
  1072. // c) there is a bug in the AST, and the node is not reachable
  1073. // Usually the traversal scope is the whole AST, which precludes b.
  1074. // Bugs are common enough that it's worthwhile asserting when we can.
  1075. #ifndef NDEBUG
  1076. if (!Node.get<TranslationUnitDecl>() &&
  1077. /* Traversal scope is full AST if any of the bounds are the TU */
  1078. llvm::any_of(ActiveASTContext->getTraversalScope(), [](Decl *D) {
  1079. return D->getKind() == Decl::TranslationUnit;
  1080. })) {
  1081. llvm::errs() << "Tried to match orphan node:\n";
  1082. Node.dump(llvm::errs(), *ActiveASTContext);
  1083. llvm_unreachable("Parent map should be complete!");
  1084. }
  1085. #endif
  1086. } else {
  1087. assert(Parents.size() > 1);
  1088. // BFS starting from the parents not yet considered.
  1089. // Memoization of newly visited nodes is not possible (but we still update
  1090. // results for the elements in the chain we found above).
  1091. std::deque<DynTypedNode> Queue(Parents.begin(), Parents.end());
  1092. llvm::DenseSet<const void *> Visited;
  1093. while (!Queue.empty()) {
  1094. BoundNodesTreeBuilder BuilderCopy = *Builder;
  1095. if (Matcher.matches(Queue.front(), this, &BuilderCopy)) {
  1096. *Builder = std::move(BuilderCopy);
  1097. return Finish(true);
  1098. }
  1099. for (const auto &Parent : ActiveASTContext->getParents(Queue.front())) {
  1100. // Make sure we do not visit the same node twice.
  1101. // Otherwise, we'll visit the common ancestors as often as there
  1102. // are splits on the way down.
  1103. if (Visited.insert(Parent.getMemoizationData()).second)
  1104. Queue.push_back(Parent);
  1105. }
  1106. Queue.pop_front();
  1107. }
  1108. }
  1109. return Finish(false);
  1110. }
  1111. // Implements a BoundNodesTree::Visitor that calls a MatchCallback with
  1112. // the aggregated bound nodes for each match.
  1113. class MatchVisitor : public BoundNodesTreeBuilder::Visitor {
  1114. struct CurBoundScope {
  1115. CurBoundScope(MatchASTVisitor::CurMatchData &State, const BoundNodes &BN)
  1116. : State(State) {
  1117. State.SetBoundNodes(BN);
  1118. }
  1119. ~CurBoundScope() { State.clearBoundNodes(); }
  1120. private:
  1121. MatchASTVisitor::CurMatchData &State;
  1122. };
  1123. public:
  1124. MatchVisitor(MatchASTVisitor &MV, ASTContext *Context,
  1125. MatchFinder::MatchCallback *Callback)
  1126. : State(MV.CurMatchState), Context(Context), Callback(Callback) {}
  1127. void visitMatch(const BoundNodes& BoundNodesView) override {
  1128. TraversalKindScope RAII(*Context, Callback->getCheckTraversalKind());
  1129. CurBoundScope RAII2(State, BoundNodesView);
  1130. Callback->run(MatchFinder::MatchResult(BoundNodesView, Context));
  1131. }
  1132. private:
  1133. MatchASTVisitor::CurMatchData &State;
  1134. ASTContext* Context;
  1135. MatchFinder::MatchCallback* Callback;
  1136. };
  1137. // Returns true if 'TypeNode' has an alias that matches the given matcher.
  1138. bool typeHasMatchingAlias(const Type *TypeNode,
  1139. const Matcher<NamedDecl> &Matcher,
  1140. BoundNodesTreeBuilder *Builder) {
  1141. const Type *const CanonicalType =
  1142. ActiveASTContext->getCanonicalType(TypeNode);
  1143. auto Aliases = TypeAliases.find(CanonicalType);
  1144. if (Aliases == TypeAliases.end())
  1145. return false;
  1146. for (const TypedefNameDecl *Alias : Aliases->second) {
  1147. BoundNodesTreeBuilder Result(*Builder);
  1148. if (Matcher.matches(*Alias, this, &Result)) {
  1149. *Builder = std::move(Result);
  1150. return true;
  1151. }
  1152. }
  1153. return false;
  1154. }
  1155. bool
  1156. objcClassHasMatchingCompatibilityAlias(const ObjCInterfaceDecl *InterfaceDecl,
  1157. const Matcher<NamedDecl> &Matcher,
  1158. BoundNodesTreeBuilder *Builder) {
  1159. auto Aliases = CompatibleAliases.find(InterfaceDecl);
  1160. if (Aliases == CompatibleAliases.end())
  1161. return false;
  1162. for (const ObjCCompatibleAliasDecl *Alias : Aliases->second) {
  1163. BoundNodesTreeBuilder Result(*Builder);
  1164. if (Matcher.matches(*Alias, this, &Result)) {
  1165. *Builder = std::move(Result);
  1166. return true;
  1167. }
  1168. }
  1169. return false;
  1170. }
  1171. /// Bucket to record map.
  1172. ///
  1173. /// Used to get the appropriate bucket for each matcher.
  1174. llvm::StringMap<llvm::TimeRecord> TimeByBucket;
  1175. const MatchFinder::MatchersByType *Matchers;
  1176. /// Filtered list of matcher indices for each matcher kind.
  1177. ///
  1178. /// \c Decl and \c Stmt toplevel matchers usually apply to a specific node
  1179. /// kind (and derived kinds) so it is a waste to try every matcher on every
  1180. /// node.
  1181. /// We precalculate a list of matchers that pass the toplevel restrict check.
  1182. llvm::DenseMap<ASTNodeKind, std::vector<unsigned short>> MatcherFiltersMap;
  1183. const MatchFinder::MatchFinderOptions &Options;
  1184. ASTContext *ActiveASTContext;
  1185. // Maps a canonical type to its TypedefDecls.
  1186. llvm::DenseMap<const Type*, std::set<const TypedefNameDecl*> > TypeAliases;
  1187. // Maps an Objective-C interface to its ObjCCompatibleAliasDecls.
  1188. llvm::DenseMap<const ObjCInterfaceDecl *,
  1189. llvm::SmallPtrSet<const ObjCCompatibleAliasDecl *, 2>>
  1190. CompatibleAliases;
  1191. // Maps (matcher, node) -> the match result for memoization.
  1192. typedef std::map<MatchKey, MemoizedMatchResult> MemoizationMap;
  1193. MemoizationMap ResultCache;
  1194. };
  1195. static CXXRecordDecl *
  1196. getAsCXXRecordDeclOrPrimaryTemplate(const Type *TypeNode) {
  1197. if (auto *RD = TypeNode->getAsCXXRecordDecl())
  1198. return RD;
  1199. // Find the innermost TemplateSpecializationType that isn't an alias template.
  1200. auto *TemplateType = TypeNode->getAs<TemplateSpecializationType>();
  1201. while (TemplateType && TemplateType->isTypeAlias())
  1202. TemplateType =
  1203. TemplateType->getAliasedType()->getAs<TemplateSpecializationType>();
  1204. // If this is the name of a (dependent) template specialization, use the
  1205. // definition of the template, even though it might be specialized later.
  1206. if (TemplateType)
  1207. if (auto *ClassTemplate = dyn_cast_or_null<ClassTemplateDecl>(
  1208. TemplateType->getTemplateName().getAsTemplateDecl()))
  1209. return ClassTemplate->getTemplatedDecl();
  1210. return nullptr;
  1211. }
  1212. // Returns true if the given C++ class is directly or indirectly derived
  1213. // from a base type with the given name. A class is not considered to be
  1214. // derived from itself.
  1215. bool MatchASTVisitor::classIsDerivedFrom(const CXXRecordDecl *Declaration,
  1216. const Matcher<NamedDecl> &Base,
  1217. BoundNodesTreeBuilder *Builder,
  1218. bool Directly) {
  1219. if (!Declaration->hasDefinition())
  1220. return false;
  1221. for (const auto &It : Declaration->bases()) {
  1222. const Type *TypeNode = It.getType().getTypePtr();
  1223. if (typeHasMatchingAlias(TypeNode, Base, Builder))
  1224. return true;
  1225. // FIXME: Going to the primary template here isn't really correct, but
  1226. // unfortunately we accept a Decl matcher for the base class not a Type
  1227. // matcher, so it's the best thing we can do with our current interface.
  1228. CXXRecordDecl *ClassDecl = getAsCXXRecordDeclOrPrimaryTemplate(TypeNode);
  1229. if (!ClassDecl)
  1230. continue;
  1231. if (ClassDecl == Declaration) {
  1232. // This can happen for recursive template definitions.
  1233. continue;
  1234. }
  1235. BoundNodesTreeBuilder Result(*Builder);
  1236. if (Base.matches(*ClassDecl, this, &Result)) {
  1237. *Builder = std::move(Result);
  1238. return true;
  1239. }
  1240. if (!Directly && classIsDerivedFrom(ClassDecl, Base, Builder, Directly))
  1241. return true;
  1242. }
  1243. return false;
  1244. }
  1245. // Returns true if the given Objective-C class is directly or indirectly
  1246. // derived from a matching base class. A class is not considered to be derived
  1247. // from itself.
  1248. bool MatchASTVisitor::objcClassIsDerivedFrom(
  1249. const ObjCInterfaceDecl *Declaration, const Matcher<NamedDecl> &Base,
  1250. BoundNodesTreeBuilder *Builder, bool Directly) {
  1251. // Check if any of the superclasses of the class match.
  1252. for (const ObjCInterfaceDecl *ClassDecl = Declaration->getSuperClass();
  1253. ClassDecl != nullptr; ClassDecl = ClassDecl->getSuperClass()) {
  1254. // Check if there are any matching compatibility aliases.
  1255. if (objcClassHasMatchingCompatibilityAlias(ClassDecl, Base, Builder))
  1256. return true;
  1257. // Check if there are any matching type aliases.
  1258. const Type *TypeNode = ClassDecl->getTypeForDecl();
  1259. if (typeHasMatchingAlias(TypeNode, Base, Builder))
  1260. return true;
  1261. if (Base.matches(*ClassDecl, this, Builder))
  1262. return true;
  1263. // Not `return false` as a temporary workaround for PR43879.
  1264. if (Directly)
  1265. break;
  1266. }
  1267. return false;
  1268. }
  1269. bool MatchASTVisitor::TraverseDecl(Decl *DeclNode) {
  1270. if (!DeclNode) {
  1271. return true;
  1272. }
  1273. bool ScopedTraversal =
  1274. TraversingASTNodeNotSpelledInSource || DeclNode->isImplicit();
  1275. bool ScopedChildren = TraversingASTChildrenNotSpelledInSource;
  1276. if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DeclNode)) {
  1277. auto SK = CTSD->getSpecializationKind();
  1278. if (SK == TSK_ExplicitInstantiationDeclaration ||
  1279. SK == TSK_ExplicitInstantiationDefinition)
  1280. ScopedChildren = true;
  1281. } else if (const auto *FD = dyn_cast<FunctionDecl>(DeclNode)) {
  1282. if (FD->isDefaulted())
  1283. ScopedChildren = true;
  1284. if (FD->isTemplateInstantiation())
  1285. ScopedTraversal = true;
  1286. } else if (isa<BindingDecl>(DeclNode)) {
  1287. ScopedChildren = true;
  1288. }
  1289. ASTNodeNotSpelledInSourceScope RAII1(this, ScopedTraversal);
  1290. ASTChildrenNotSpelledInSourceScope RAII2(this, ScopedChildren);
  1291. match(*DeclNode);
  1292. return RecursiveASTVisitor<MatchASTVisitor>::TraverseDecl(DeclNode);
  1293. }
  1294. bool MatchASTVisitor::TraverseStmt(Stmt *StmtNode, DataRecursionQueue *Queue) {
  1295. if (!StmtNode) {
  1296. return true;
  1297. }
  1298. bool ScopedTraversal = TraversingASTNodeNotSpelledInSource ||
  1299. TraversingASTChildrenNotSpelledInSource;
  1300. ASTNodeNotSpelledInSourceScope RAII(this, ScopedTraversal);
  1301. match(*StmtNode);
  1302. return RecursiveASTVisitor<MatchASTVisitor>::TraverseStmt(StmtNode, Queue);
  1303. }
  1304. bool MatchASTVisitor::TraverseType(QualType TypeNode) {
  1305. match(TypeNode);
  1306. return RecursiveASTVisitor<MatchASTVisitor>::TraverseType(TypeNode);
  1307. }
  1308. bool MatchASTVisitor::TraverseTypeLoc(TypeLoc TypeLocNode) {
  1309. // The RecursiveASTVisitor only visits types if they're not within TypeLocs.
  1310. // We still want to find those types via matchers, so we match them here. Note
  1311. // that the TypeLocs are structurally a shadow-hierarchy to the expressed
  1312. // type, so we visit all involved parts of a compound type when matching on
  1313. // each TypeLoc.
  1314. match(TypeLocNode);
  1315. match(TypeLocNode.getType());
  1316. return RecursiveASTVisitor<MatchASTVisitor>::TraverseTypeLoc(TypeLocNode);
  1317. }
  1318. bool MatchASTVisitor::TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) {
  1319. match(*NNS);
  1320. return RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifier(NNS);
  1321. }
  1322. bool MatchASTVisitor::TraverseNestedNameSpecifierLoc(
  1323. NestedNameSpecifierLoc NNS) {
  1324. if (!NNS)
  1325. return true;
  1326. match(NNS);
  1327. // We only match the nested name specifier here (as opposed to traversing it)
  1328. // because the traversal is already done in the parallel "Loc"-hierarchy.
  1329. if (NNS.hasQualifier())
  1330. match(*NNS.getNestedNameSpecifier());
  1331. return
  1332. RecursiveASTVisitor<MatchASTVisitor>::TraverseNestedNameSpecifierLoc(NNS);
  1333. }
  1334. bool MatchASTVisitor::TraverseConstructorInitializer(
  1335. CXXCtorInitializer *CtorInit) {
  1336. if (!CtorInit)
  1337. return true;
  1338. bool ScopedTraversal = TraversingASTNodeNotSpelledInSource ||
  1339. TraversingASTChildrenNotSpelledInSource;
  1340. if (!CtorInit->isWritten())
  1341. ScopedTraversal = true;
  1342. ASTNodeNotSpelledInSourceScope RAII1(this, ScopedTraversal);
  1343. match(*CtorInit);
  1344. return RecursiveASTVisitor<MatchASTVisitor>::TraverseConstructorInitializer(
  1345. CtorInit);
  1346. }
  1347. bool MatchASTVisitor::TraverseTemplateArgumentLoc(TemplateArgumentLoc Loc) {
  1348. match(Loc);
  1349. return RecursiveASTVisitor<MatchASTVisitor>::TraverseTemplateArgumentLoc(Loc);
  1350. }
  1351. bool MatchASTVisitor::TraverseAttr(Attr *AttrNode) {
  1352. match(*AttrNode);
  1353. return RecursiveASTVisitor<MatchASTVisitor>::TraverseAttr(AttrNode);
  1354. }
  1355. class MatchASTConsumer : public ASTConsumer {
  1356. public:
  1357. MatchASTConsumer(MatchFinder *Finder,
  1358. MatchFinder::ParsingDoneTestCallback *ParsingDone)
  1359. : Finder(Finder), ParsingDone(ParsingDone) {}
  1360. private:
  1361. void HandleTranslationUnit(ASTContext &Context) override {
  1362. if (ParsingDone != nullptr) {
  1363. ParsingDone->run();
  1364. }
  1365. Finder->matchAST(Context);
  1366. }
  1367. MatchFinder *Finder;
  1368. MatchFinder::ParsingDoneTestCallback *ParsingDone;
  1369. };
  1370. } // end namespace
  1371. } // end namespace internal
  1372. MatchFinder::MatchResult::MatchResult(const BoundNodes &Nodes,
  1373. ASTContext *Context)
  1374. : Nodes(Nodes), Context(Context),
  1375. SourceManager(&Context->getSourceManager()) {}
  1376. MatchFinder::MatchCallback::~MatchCallback() {}
  1377. MatchFinder::ParsingDoneTestCallback::~ParsingDoneTestCallback() {}
  1378. MatchFinder::MatchFinder(MatchFinderOptions Options)
  1379. : Options(std::move(Options)), ParsingDone(nullptr) {}
  1380. MatchFinder::~MatchFinder() {}
  1381. void MatchFinder::addMatcher(const DeclarationMatcher &NodeMatch,
  1382. MatchCallback *Action) {
  1383. std::optional<TraversalKind> TK;
  1384. if (Action)
  1385. TK = Action->getCheckTraversalKind();
  1386. if (TK)
  1387. Matchers.DeclOrStmt.emplace_back(traverse(*TK, NodeMatch), Action);
  1388. else
  1389. Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
  1390. Matchers.AllCallbacks.insert(Action);
  1391. }
  1392. void MatchFinder::addMatcher(const TypeMatcher &NodeMatch,
  1393. MatchCallback *Action) {
  1394. Matchers.Type.emplace_back(NodeMatch, Action);
  1395. Matchers.AllCallbacks.insert(Action);
  1396. }
  1397. void MatchFinder::addMatcher(const StatementMatcher &NodeMatch,
  1398. MatchCallback *Action) {
  1399. std::optional<TraversalKind> TK;
  1400. if (Action)
  1401. TK = Action->getCheckTraversalKind();
  1402. if (TK)
  1403. Matchers.DeclOrStmt.emplace_back(traverse(*TK, NodeMatch), Action);
  1404. else
  1405. Matchers.DeclOrStmt.emplace_back(NodeMatch, Action);
  1406. Matchers.AllCallbacks.insert(Action);
  1407. }
  1408. void MatchFinder::addMatcher(const NestedNameSpecifierMatcher &NodeMatch,
  1409. MatchCallback *Action) {
  1410. Matchers.NestedNameSpecifier.emplace_back(NodeMatch, Action);
  1411. Matchers.AllCallbacks.insert(Action);
  1412. }
  1413. void MatchFinder::addMatcher(const NestedNameSpecifierLocMatcher &NodeMatch,
  1414. MatchCallback *Action) {
  1415. Matchers.NestedNameSpecifierLoc.emplace_back(NodeMatch, Action);
  1416. Matchers.AllCallbacks.insert(Action);
  1417. }
  1418. void MatchFinder::addMatcher(const TypeLocMatcher &NodeMatch,
  1419. MatchCallback *Action) {
  1420. Matchers.TypeLoc.emplace_back(NodeMatch, Action);
  1421. Matchers.AllCallbacks.insert(Action);
  1422. }
  1423. void MatchFinder::addMatcher(const CXXCtorInitializerMatcher &NodeMatch,
  1424. MatchCallback *Action) {
  1425. Matchers.CtorInit.emplace_back(NodeMatch, Action);
  1426. Matchers.AllCallbacks.insert(Action);
  1427. }
  1428. void MatchFinder::addMatcher(const TemplateArgumentLocMatcher &NodeMatch,
  1429. MatchCallback *Action) {
  1430. Matchers.TemplateArgumentLoc.emplace_back(NodeMatch, Action);
  1431. Matchers.AllCallbacks.insert(Action);
  1432. }
  1433. void MatchFinder::addMatcher(const AttrMatcher &AttrMatch,
  1434. MatchCallback *Action) {
  1435. Matchers.Attr.emplace_back(AttrMatch, Action);
  1436. Matchers.AllCallbacks.insert(Action);
  1437. }
  1438. bool MatchFinder::addDynamicMatcher(const internal::DynTypedMatcher &NodeMatch,
  1439. MatchCallback *Action) {
  1440. if (NodeMatch.canConvertTo<Decl>()) {
  1441. addMatcher(NodeMatch.convertTo<Decl>(), Action);
  1442. return true;
  1443. } else if (NodeMatch.canConvertTo<QualType>()) {
  1444. addMatcher(NodeMatch.convertTo<QualType>(), Action);
  1445. return true;
  1446. } else if (NodeMatch.canConvertTo<Stmt>()) {
  1447. addMatcher(NodeMatch.convertTo<Stmt>(), Action);
  1448. return true;
  1449. } else if (NodeMatch.canConvertTo<NestedNameSpecifier>()) {
  1450. addMatcher(NodeMatch.convertTo<NestedNameSpecifier>(), Action);
  1451. return true;
  1452. } else if (NodeMatch.canConvertTo<NestedNameSpecifierLoc>()) {
  1453. addMatcher(NodeMatch.convertTo<NestedNameSpecifierLoc>(), Action);
  1454. return true;
  1455. } else if (NodeMatch.canConvertTo<TypeLoc>()) {
  1456. addMatcher(NodeMatch.convertTo<TypeLoc>(), Action);
  1457. return true;
  1458. } else if (NodeMatch.canConvertTo<CXXCtorInitializer>()) {
  1459. addMatcher(NodeMatch.convertTo<CXXCtorInitializer>(), Action);
  1460. return true;
  1461. } else if (NodeMatch.canConvertTo<TemplateArgumentLoc>()) {
  1462. addMatcher(NodeMatch.convertTo<TemplateArgumentLoc>(), Action);
  1463. return true;
  1464. } else if (NodeMatch.canConvertTo<Attr>()) {
  1465. addMatcher(NodeMatch.convertTo<Attr>(), Action);
  1466. return true;
  1467. }
  1468. return false;
  1469. }
  1470. std::unique_ptr<ASTConsumer> MatchFinder::newASTConsumer() {
  1471. return std::make_unique<internal::MatchASTConsumer>(this, ParsingDone);
  1472. }
  1473. void MatchFinder::match(const clang::DynTypedNode &Node, ASTContext &Context) {
  1474. internal::MatchASTVisitor Visitor(&Matchers, Options);
  1475. Visitor.set_active_ast_context(&Context);
  1476. Visitor.match(Node);
  1477. }
  1478. void MatchFinder::matchAST(ASTContext &Context) {
  1479. internal::MatchASTVisitor Visitor(&Matchers, Options);
  1480. internal::MatchASTVisitor::TraceReporter StackTrace(Visitor);
  1481. Visitor.set_active_ast_context(&Context);
  1482. Visitor.onStartOfTranslationUnit();
  1483. Visitor.TraverseAST(Context);
  1484. Visitor.onEndOfTranslationUnit();
  1485. }
  1486. void MatchFinder::registerTestCallbackAfterParsing(
  1487. MatchFinder::ParsingDoneTestCallback *NewParsingDone) {
  1488. ParsingDone = NewParsingDone;
  1489. }
  1490. StringRef MatchFinder::MatchCallback::getID() const { return "<unknown>"; }
  1491. std::optional<TraversalKind>
  1492. MatchFinder::MatchCallback::getCheckTraversalKind() const {
  1493. return std::nullopt;
  1494. }
  1495. } // end namespace ast_matchers
  1496. } // end namespace clang