ASTMatchersInternal.h 82 KB

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