ASTMatchersInternal.h 81 KB

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