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