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 {
operatorVariadicFunction94 ResultT operator()() const { return Func(None); }
95
96 template <typename... ArgsT>
operatorVariadicFunction97 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.
operatorVariadicFunction103 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.
ExecuteVariadicFunction113 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`.
getUnderlyingType(const Expr & Node)121 inline QualType getUnderlyingType(const Expr &Node) { return Node.getType(); }
122
getUnderlyingType(const ValueDecl & Node)123 inline QualType getUnderlyingType(const ValueDecl &Node) {
124 return Node.getType();
125 }
getUnderlyingType(const TypedefNameDecl & Node)126 inline QualType getUnderlyingType(const TypedefNameDecl &Node) {
127 return Node.getUnderlyingType();
128 }
getUnderlyingType(const FriendDecl & Node)129 inline QualType getUnderlyingType(const FriendDecl &Node) {
130 if (const TypeSourceInfo *TSI = Node.getFriendType())
131 return TSI->getType();
132 return QualType();
133 }
getUnderlyingType(const CXXBaseSpecifier & Node)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 *
getFunctionProtoType(const FunctionProtoType & Node)141 getFunctionProtoType(const FunctionProtoType &Node) {
142 return &Node;
143 }
144
getFunctionProtoType(const FunctionDecl & Node)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.
getAccessSpecifier(const Decl & Node)150 inline clang::AccessSpecifier getAccessSpecifier(const Decl &Node) {
151 return Node.getAccess();
152 }
153
getAccessSpecifier(const CXXBaseSpecifier & Node)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.
addNode(StringRef ID,const DynTypedNode & DynNode)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>
getNodeAs(StringRef ID)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
getNode(StringRef ID)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
getMap()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.
isComparable()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.
setBinding(StringRef Id,const DynTypedNode & DynNode)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>
removeBindings(const ExcludePredicate & Predicate)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.
isComparable()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
TraversalKind()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
dynMatches(const DynTypedNode & DynNode,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder)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.
matches(const T & Node,ASTMatchFinder *,BoundNodesTreeBuilder *)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>
DynTypedMatcher(MatcherInterface<T> * Implementation)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
setAllowBind(bool AB)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>;
getID()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.
getSupportedKind()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.
canConvertTo()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.
convertTo()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.
getTraversalKind()484 llvm::Optional<clang::TraversalKind> getTraversalKind() const {
485 return Implementation->TraversalKind();
486 }
487
488 private:
DynTypedMatcher(ASTNodeKind SupportedKind,ASTNodeKind RestrictKind,IntrusiveRefCntPtr<DynMatcherInterface> Implementation)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.
Matcher(MatcherInterface<T> * Implementation)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)
Implementation(new TypeToQualType<TypeT> (Other))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>
dynCastTo()545 Matcher<To> dynCastTo() const {
546 static_assert(std::is_base_of<To, T>::value, "Invalid dynCast call.");
547 return Matcher<To>(Implementation);
548 }
549
550 /// Forwards the call to the underlying MatcherInterface<T> pointer.
matches(const T & Node,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder)551 bool matches(const T &Node,
552 ASTMatchFinder *Finder,
553 BoundNodesTreeBuilder *Builder) const {
554 return Implementation.matches(DynTypedNode::create(Node), Finder, Builder);
555 }
556
557 /// Returns an ID that uniquely identifies the matcher.
getID()558 DynTypedMatcher::MatcherIDType getID() const {
559 return Implementation.getID();
560 }
561
562 /// Extract the dynamic matcher.
563 ///
564 /// The returned matcher keeps the same restrictions as \c this and remembers
565 /// that it is meant to support nodes of type \c T.
DynTypedMatcher()566 operator DynTypedMatcher() const { return Implementation; }
567
568 /// Allows the conversion of a \c Matcher<Type> to a \c
569 /// Matcher<QualType>.
570 ///
571 /// Depending on the constructor argument, the matcher is either strict, i.e.
572 /// does only matches in the absence of qualifiers, or not, i.e. simply
573 /// ignores any qualifiers.
574 template <typename TypeT>
575 class TypeToQualType : public MatcherInterface<QualType> {
576 const DynTypedMatcher InnerMatcher;
577
578 public:
TypeToQualType(const Matcher<TypeT> & InnerMatcher)579 TypeToQualType(const Matcher<TypeT> &InnerMatcher)
580 : InnerMatcher(InnerMatcher) {}
581
matches(const QualType & Node,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder)582 bool matches(const QualType &Node, ASTMatchFinder *Finder,
583 BoundNodesTreeBuilder *Builder) const override {
584 if (Node.isNull())
585 return false;
586 return this->InnerMatcher.matches(DynTypedNode::create(*Node), Finder,
587 Builder);
588 }
589
TraversalKind()590 llvm::Optional<clang::TraversalKind> TraversalKind() const override {
591 return this->InnerMatcher.getTraversalKind();
592 }
593 };
594
595 private:
596 // For Matcher<T> <=> Matcher<U> conversions.
597 template <typename U> friend class Matcher;
598
599 // For DynTypedMatcher::unconditionalConvertTo<T>.
600 friend class DynTypedMatcher;
601
restrictMatcher(const DynTypedMatcher & Other)602 static DynTypedMatcher restrictMatcher(const DynTypedMatcher &Other) {
603 return Other.dynCastTo(ASTNodeKind::getFromNodeKind<T>());
604 }
605
Matcher(const DynTypedMatcher & Implementation)606 explicit Matcher(const DynTypedMatcher &Implementation)
607 : Implementation(restrictMatcher(Implementation)) {
608 assert(this->Implementation.getSupportedKind().isSame(
609 ASTNodeKind::getFromNodeKind<T>()));
610 }
611
612 DynTypedMatcher Implementation;
613 }; // class Matcher
614
615 /// A convenient helper for creating a Matcher<T> without specifying
616 /// the template type argument.
617 template <typename T>
makeMatcher(MatcherInterface<T> * Implementation)618 inline Matcher<T> makeMatcher(MatcherInterface<T> *Implementation) {
619 return Matcher<T>(Implementation);
620 }
621
622 /// Interface that allows matchers to traverse the AST.
623 /// FIXME: Find a better name.
624 ///
625 /// This provides three entry methods for each base node type in the AST:
626 /// - \c matchesChildOf:
627 /// Matches a matcher on every child node of the given node. Returns true
628 /// if at least one child node could be matched.
629 /// - \c matchesDescendantOf:
630 /// Matches a matcher on all descendant nodes of the given node. Returns true
631 /// if at least one descendant matched.
632 /// - \c matchesAncestorOf:
633 /// Matches a matcher on all ancestors of the given node. Returns true if
634 /// at least one ancestor matched.
635 ///
636 /// FIXME: Currently we only allow Stmt and Decl nodes to start a traversal.
637 /// In the future, we want to implement this for all nodes for which it makes
638 /// sense. In the case of matchesAncestorOf, we'll want to implement it for
639 /// all nodes, as all nodes have ancestors.
640 class ASTMatchFinder {
641 public:
642 /// Defines how bindings are processed on recursive matches.
643 enum BindKind {
644 /// Stop at the first match and only bind the first match.
645 BK_First,
646
647 /// Create results for all combinations of bindings that match.
648 BK_All
649 };
650
651 /// Defines which ancestors are considered for a match.
652 enum AncestorMatchMode {
653 /// All ancestors.
654 AMM_All,
655
656 /// Direct parent only.
657 AMM_ParentOnly
658 };
659
660 virtual ~ASTMatchFinder() = default;
661
662 /// Returns true if the given C++ class is directly or indirectly derived
663 /// from a base type matching \c base.
664 ///
665 /// A class is not considered to be derived from itself.
666 virtual bool classIsDerivedFrom(const CXXRecordDecl *Declaration,
667 const Matcher<NamedDecl> &Base,
668 BoundNodesTreeBuilder *Builder,
669 bool Directly) = 0;
670
671 /// Returns true if the given Objective-C class is directly or indirectly
672 /// derived from a base class matching \c base.
673 ///
674 /// A class is not considered to be derived from itself.
675 virtual bool objcClassIsDerivedFrom(const ObjCInterfaceDecl *Declaration,
676 const Matcher<NamedDecl> &Base,
677 BoundNodesTreeBuilder *Builder,
678 bool Directly) = 0;
679
680 template <typename T>
matchesChildOf(const T & Node,const DynTypedMatcher & Matcher,BoundNodesTreeBuilder * Builder,BindKind Bind)681 bool matchesChildOf(const T &Node, const DynTypedMatcher &Matcher,
682 BoundNodesTreeBuilder *Builder, BindKind Bind) {
683 static_assert(std::is_base_of<Decl, T>::value ||
684 std::is_base_of<Stmt, T>::value ||
685 std::is_base_of<NestedNameSpecifier, T>::value ||
686 std::is_base_of<NestedNameSpecifierLoc, T>::value ||
687 std::is_base_of<TypeLoc, T>::value ||
688 std::is_base_of<QualType, T>::value,
689 "unsupported type for recursive matching");
690 return matchesChildOf(DynTypedNode::create(Node), getASTContext(), Matcher,
691 Builder, Bind);
692 }
693
694 template <typename T>
matchesDescendantOf(const T & Node,const DynTypedMatcher & Matcher,BoundNodesTreeBuilder * Builder,BindKind Bind)695 bool matchesDescendantOf(const T &Node, const DynTypedMatcher &Matcher,
696 BoundNodesTreeBuilder *Builder, BindKind Bind) {
697 static_assert(std::is_base_of<Decl, T>::value ||
698 std::is_base_of<Stmt, T>::value ||
699 std::is_base_of<NestedNameSpecifier, T>::value ||
700 std::is_base_of<NestedNameSpecifierLoc, T>::value ||
701 std::is_base_of<TypeLoc, T>::value ||
702 std::is_base_of<QualType, T>::value,
703 "unsupported type for recursive matching");
704 return matchesDescendantOf(DynTypedNode::create(Node), getASTContext(),
705 Matcher, Builder, Bind);
706 }
707
708 // FIXME: Implement support for BindKind.
709 template <typename T>
matchesAncestorOf(const T & Node,const DynTypedMatcher & Matcher,BoundNodesTreeBuilder * Builder,AncestorMatchMode MatchMode)710 bool matchesAncestorOf(const T &Node, const DynTypedMatcher &Matcher,
711 BoundNodesTreeBuilder *Builder,
712 AncestorMatchMode MatchMode) {
713 static_assert(std::is_base_of<Decl, T>::value ||
714 std::is_base_of<NestedNameSpecifierLoc, T>::value ||
715 std::is_base_of<Stmt, T>::value ||
716 std::is_base_of<TypeLoc, T>::value,
717 "type not allowed for recursive matching");
718 return matchesAncestorOf(DynTypedNode::create(Node), getASTContext(),
719 Matcher, Builder, MatchMode);
720 }
721
722 virtual ASTContext &getASTContext() const = 0;
723
724 virtual bool IsMatchingInASTNodeNotSpelledInSource() const = 0;
725
726 bool isTraversalIgnoringImplicitNodes() const;
727
728 protected:
729 virtual bool matchesChildOf(const DynTypedNode &Node, ASTContext &Ctx,
730 const DynTypedMatcher &Matcher,
731 BoundNodesTreeBuilder *Builder,
732 BindKind Bind) = 0;
733
734 virtual bool matchesDescendantOf(const DynTypedNode &Node, ASTContext &Ctx,
735 const DynTypedMatcher &Matcher,
736 BoundNodesTreeBuilder *Builder,
737 BindKind Bind) = 0;
738
739 virtual bool matchesAncestorOf(const DynTypedNode &Node, ASTContext &Ctx,
740 const DynTypedMatcher &Matcher,
741 BoundNodesTreeBuilder *Builder,
742 AncestorMatchMode MatchMode) = 0;
743 };
744
745 /// Specialization of the conversion functions for QualType.
746 ///
747 /// This specialization provides the Matcher<Type>->Matcher<QualType>
748 /// conversion that the static API does.
749 template <>
750 inline Matcher<QualType> DynTypedMatcher::convertTo<QualType>() const {
751 assert(canConvertTo<QualType>());
752 const ASTNodeKind SourceKind = getSupportedKind();
753 if (SourceKind.isSame(ASTNodeKind::getFromNodeKind<Type>())) {
754 // We support implicit conversion from Matcher<Type> to Matcher<QualType>
755 return unconditionalConvertTo<Type>();
756 }
757 return unconditionalConvertTo<QualType>();
758 }
759
760 /// Finds the first node in a range that matches the given matcher.
761 template <typename MatcherT, typename IteratorT>
matchesFirstInRange(const MatcherT & Matcher,IteratorT Start,IteratorT End,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder)762 IteratorT matchesFirstInRange(const MatcherT &Matcher, IteratorT Start,
763 IteratorT End, ASTMatchFinder *Finder,
764 BoundNodesTreeBuilder *Builder) {
765 for (IteratorT I = Start; I != End; ++I) {
766 BoundNodesTreeBuilder Result(*Builder);
767 if (Matcher.matches(*I, Finder, &Result)) {
768 *Builder = std::move(Result);
769 return I;
770 }
771 }
772 return End;
773 }
774
775 /// Finds the first node in a pointer range that matches the given
776 /// matcher.
777 template <typename MatcherT, typename IteratorT>
matchesFirstInPointerRange(const MatcherT & Matcher,IteratorT Start,IteratorT End,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder)778 IteratorT matchesFirstInPointerRange(const MatcherT &Matcher, IteratorT Start,
779 IteratorT End, ASTMatchFinder *Finder,
780 BoundNodesTreeBuilder *Builder) {
781 for (IteratorT I = Start; I != End; ++I) {
782 BoundNodesTreeBuilder Result(*Builder);
783 if (Matcher.matches(**I, Finder, &Result)) {
784 *Builder = std::move(Result);
785 return I;
786 }
787 }
788 return End;
789 }
790
791 template <typename T, std::enable_if_t<!std::is_base_of<FunctionDecl, T>::value>
792 * = nullptr>
isDefaultedHelper(const T *)793 inline bool isDefaultedHelper(const T *) {
794 return false;
795 }
isDefaultedHelper(const FunctionDecl * FD)796 inline bool isDefaultedHelper(const FunctionDecl *FD) {
797 return FD->isDefaulted();
798 }
799
800 // Metafunction to determine if type T has a member called getDecl.
801 template <typename Ty>
802 class has_getDecl {
803 using yes = char[1];
804 using no = char[2];
805
806 template <typename Inner>
807 static yes& test(Inner *I, decltype(I->getDecl()) * = nullptr);
808
809 template <typename>
810 static no& test(...);
811
812 public:
813 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
814 };
815
816 /// Matches overloaded operators with a specific name.
817 ///
818 /// The type argument ArgT is not used by this matcher but is used by
819 /// PolymorphicMatcherWithParam1 and should be StringRef.
820 template <typename T, typename ArgT>
821 class HasOverloadedOperatorNameMatcher : public SingleNodeMatcherInterface<T> {
822 static_assert(std::is_same<T, CXXOperatorCallExpr>::value ||
823 std::is_base_of<FunctionDecl, T>::value,
824 "unsupported class for matcher");
825 static_assert(std::is_same<ArgT, std::vector<std::string>>::value,
826 "argument type must be std::vector<std::string>");
827
828 public:
HasOverloadedOperatorNameMatcher(std::vector<std::string> Names)829 explicit HasOverloadedOperatorNameMatcher(std::vector<std::string> Names)
830 : SingleNodeMatcherInterface<T>(), Names(std::move(Names)) {}
831
matchesNode(const T & Node)832 bool matchesNode(const T &Node) const override {
833 return matchesSpecialized(Node);
834 }
835
836 private:
837
838 /// CXXOperatorCallExpr exist only for calls to overloaded operators
839 /// so this function returns true if the call is to an operator of the given
840 /// name.
matchesSpecialized(const CXXOperatorCallExpr & Node)841 bool matchesSpecialized(const CXXOperatorCallExpr &Node) const {
842 return llvm::is_contained(Names, getOperatorSpelling(Node.getOperator()));
843 }
844
845 /// Returns true only if CXXMethodDecl represents an overloaded
846 /// operator and has the given operator name.
matchesSpecialized(const FunctionDecl & Node)847 bool matchesSpecialized(const FunctionDecl &Node) const {
848 return Node.isOverloadedOperator() &&
849 llvm::is_contained(
850 Names, getOperatorSpelling(Node.getOverloadedOperator()));
851 }
852
853 const std::vector<std::string> Names;
854 };
855
856 /// Matches named declarations with a specific name.
857 ///
858 /// See \c hasName() and \c hasAnyName() in ASTMatchers.h for details.
859 class HasNameMatcher : public SingleNodeMatcherInterface<NamedDecl> {
860 public:
861 explicit HasNameMatcher(std::vector<std::string> Names);
862
863 bool matchesNode(const NamedDecl &Node) const override;
864
865 private:
866 /// Unqualified match routine.
867 ///
868 /// It is much faster than the full match, but it only works for unqualified
869 /// matches.
870 bool matchesNodeUnqualified(const NamedDecl &Node) const;
871
872 /// Full match routine
873 ///
874 /// Fast implementation for the simple case of a named declaration at
875 /// namespace or RecordDecl scope.
876 /// It is slower than matchesNodeUnqualified, but faster than
877 /// matchesNodeFullSlow.
878 bool matchesNodeFullFast(const NamedDecl &Node) const;
879
880 /// Full match routine
881 ///
882 /// It generates the fully qualified name of the declaration (which is
883 /// expensive) before trying to match.
884 /// It is slower but simple and works on all cases.
885 bool matchesNodeFullSlow(const NamedDecl &Node) const;
886
887 const bool UseUnqualifiedMatch;
888 const std::vector<std::string> Names;
889 };
890
891 /// Trampoline function to use VariadicFunction<> to construct a
892 /// HasNameMatcher.
893 Matcher<NamedDecl> hasAnyNameFunc(ArrayRef<const StringRef *> NameRefs);
894
895 /// Trampoline function to use VariadicFunction<> to construct a
896 /// hasAnySelector matcher.
897 Matcher<ObjCMessageExpr> hasAnySelectorFunc(
898 ArrayRef<const StringRef *> NameRefs);
899
900 /// Matches declarations for QualType and CallExpr.
901 ///
902 /// Type argument DeclMatcherT is required by PolymorphicMatcherWithParam1 but
903 /// not actually used.
904 template <typename T, typename DeclMatcherT>
905 class HasDeclarationMatcher : public MatcherInterface<T> {
906 static_assert(std::is_same<DeclMatcherT, Matcher<Decl>>::value,
907 "instantiated with wrong types");
908
909 const DynTypedMatcher InnerMatcher;
910
911 public:
HasDeclarationMatcher(const Matcher<Decl> & InnerMatcher)912 explicit HasDeclarationMatcher(const Matcher<Decl> &InnerMatcher)
913 : InnerMatcher(InnerMatcher) {}
914
matches(const T & Node,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder)915 bool matches(const T &Node, ASTMatchFinder *Finder,
916 BoundNodesTreeBuilder *Builder) const override {
917 return matchesSpecialized(Node, Finder, Builder);
918 }
919
920 private:
921 /// Forwards to matching on the underlying type of the QualType.
matchesSpecialized(const QualType & Node,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder)922 bool matchesSpecialized(const QualType &Node, ASTMatchFinder *Finder,
923 BoundNodesTreeBuilder *Builder) const {
924 if (Node.isNull())
925 return false;
926
927 return matchesSpecialized(*Node, Finder, Builder);
928 }
929
930 /// Finds the best declaration for a type and returns whether the inner
931 /// matcher matches on it.
matchesSpecialized(const Type & Node,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder)932 bool matchesSpecialized(const Type &Node, ASTMatchFinder *Finder,
933 BoundNodesTreeBuilder *Builder) const {
934 // DeducedType does not have declarations of its own, so
935 // match the deduced type instead.
936 const Type *EffectiveType = &Node;
937 if (const auto *S = dyn_cast<DeducedType>(&Node)) {
938 EffectiveType = S->getDeducedType().getTypePtrOrNull();
939 if (!EffectiveType)
940 return false;
941 }
942
943 // First, for any types that have a declaration, extract the declaration and
944 // match on it.
945 if (const auto *S = dyn_cast<TagType>(EffectiveType)) {
946 return matchesDecl(S->getDecl(), Finder, Builder);
947 }
948 if (const auto *S = dyn_cast<InjectedClassNameType>(EffectiveType)) {
949 return matchesDecl(S->getDecl(), Finder, Builder);
950 }
951 if (const auto *S = dyn_cast<TemplateTypeParmType>(EffectiveType)) {
952 return matchesDecl(S->getDecl(), Finder, Builder);
953 }
954 if (const auto *S = dyn_cast<TypedefType>(EffectiveType)) {
955 return matchesDecl(S->getDecl(), Finder, Builder);
956 }
957 if (const auto *S = dyn_cast<UnresolvedUsingType>(EffectiveType)) {
958 return matchesDecl(S->getDecl(), Finder, Builder);
959 }
960 if (const auto *S = dyn_cast<ObjCObjectType>(EffectiveType)) {
961 return matchesDecl(S->getInterface(), Finder, Builder);
962 }
963
964 // A SubstTemplateTypeParmType exists solely to mark a type substitution
965 // on the instantiated template. As users usually want to match the
966 // template parameter on the uninitialized template, we can always desugar
967 // one level without loss of expressivness.
968 // For example, given:
969 // template<typename T> struct X { T t; } class A {}; X<A> a;
970 // The following matcher will match, which otherwise would not:
971 // fieldDecl(hasType(pointerType())).
972 if (const auto *S = dyn_cast<SubstTemplateTypeParmType>(EffectiveType)) {
973 return matchesSpecialized(S->getReplacementType(), Finder, Builder);
974 }
975
976 // For template specialization types, we want to match the template
977 // declaration, as long as the type is still dependent, and otherwise the
978 // declaration of the instantiated tag type.
979 if (const auto *S = dyn_cast<TemplateSpecializationType>(EffectiveType)) {
980 if (!S->isTypeAlias() && S->isSugared()) {
981 // If the template is non-dependent, we want to match the instantiated
982 // tag type.
983 // For example, given:
984 // template<typename T> struct X {}; X<int> a;
985 // The following matcher will match, which otherwise would not:
986 // templateSpecializationType(hasDeclaration(cxxRecordDecl())).
987 return matchesSpecialized(*S->desugar(), Finder, Builder);
988 }
989 // If the template is dependent or an alias, match the template
990 // declaration.
991 return matchesDecl(S->getTemplateName().getAsTemplateDecl(), Finder,
992 Builder);
993 }
994
995 // FIXME: We desugar elaborated types. This makes the assumption that users
996 // do never want to match on whether a type is elaborated - there are
997 // arguments for both sides; for now, continue desugaring.
998 if (const auto *S = dyn_cast<ElaboratedType>(EffectiveType)) {
999 return matchesSpecialized(S->desugar(), Finder, Builder);
1000 }
1001 return false;
1002 }
1003
1004 /// Extracts the Decl the DeclRefExpr references and returns whether
1005 /// the inner matcher matches on it.
matchesSpecialized(const DeclRefExpr & Node,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder)1006 bool matchesSpecialized(const DeclRefExpr &Node, ASTMatchFinder *Finder,
1007 BoundNodesTreeBuilder *Builder) const {
1008 return matchesDecl(Node.getDecl(), Finder, Builder);
1009 }
1010
1011 /// Extracts the Decl of the callee of a CallExpr and returns whether
1012 /// the inner matcher matches on it.
matchesSpecialized(const CallExpr & Node,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder)1013 bool matchesSpecialized(const CallExpr &Node, ASTMatchFinder *Finder,
1014 BoundNodesTreeBuilder *Builder) const {
1015 return matchesDecl(Node.getCalleeDecl(), Finder, Builder);
1016 }
1017
1018 /// Extracts the Decl of the constructor call and returns whether the
1019 /// inner matcher matches on it.
matchesSpecialized(const CXXConstructExpr & Node,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder)1020 bool matchesSpecialized(const CXXConstructExpr &Node,
1021 ASTMatchFinder *Finder,
1022 BoundNodesTreeBuilder *Builder) const {
1023 return matchesDecl(Node.getConstructor(), Finder, Builder);
1024 }
1025
matchesSpecialized(const ObjCIvarRefExpr & Node,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder)1026 bool matchesSpecialized(const ObjCIvarRefExpr &Node,
1027 ASTMatchFinder *Finder,
1028 BoundNodesTreeBuilder *Builder) const {
1029 return matchesDecl(Node.getDecl(), Finder, Builder);
1030 }
1031
1032 /// Extracts the operator new of the new call and returns whether the
1033 /// inner matcher matches on it.
matchesSpecialized(const CXXNewExpr & Node,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder)1034 bool matchesSpecialized(const CXXNewExpr &Node,
1035 ASTMatchFinder *Finder,
1036 BoundNodesTreeBuilder *Builder) const {
1037 return matchesDecl(Node.getOperatorNew(), Finder, Builder);
1038 }
1039
1040 /// Extracts the \c ValueDecl a \c MemberExpr refers to and returns
1041 /// whether the inner matcher matches on it.
matchesSpecialized(const MemberExpr & Node,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder)1042 bool matchesSpecialized(const MemberExpr &Node,
1043 ASTMatchFinder *Finder,
1044 BoundNodesTreeBuilder *Builder) const {
1045 return matchesDecl(Node.getMemberDecl(), Finder, Builder);
1046 }
1047
1048 /// Extracts the \c LabelDecl a \c AddrLabelExpr refers to and returns
1049 /// whether the inner matcher matches on it.
matchesSpecialized(const AddrLabelExpr & Node,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder)1050 bool matchesSpecialized(const AddrLabelExpr &Node,
1051 ASTMatchFinder *Finder,
1052 BoundNodesTreeBuilder *Builder) const {
1053 return matchesDecl(Node.getLabel(), Finder, Builder);
1054 }
1055
1056 /// Extracts the declaration of a LabelStmt and returns whether the
1057 /// inner matcher matches on it.
matchesSpecialized(const LabelStmt & Node,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder)1058 bool matchesSpecialized(const LabelStmt &Node, ASTMatchFinder *Finder,
1059 BoundNodesTreeBuilder *Builder) const {
1060 return matchesDecl(Node.getDecl(), Finder, Builder);
1061 }
1062
1063 /// Returns whether the inner matcher \c Node. Returns false if \c Node
1064 /// is \c NULL.
matchesDecl(const Decl * Node,ASTMatchFinder * Finder,BoundNodesTreeBuilder * Builder)1065 bool matchesDecl(const Decl *Node, ASTMatchFinder *Finder,
1066 BoundNodesTreeBuilder *Builder) const {
1067 if (Finder->isTraversalIgnoringImplicitNodes() && Node->isImplicit())
1068 return false;
1069 return Node != nullptr && this->InnerMatcher.matches(
1070 DynTypedNode::create(*Node), Finder, Builder);
1071 }
1072 };
1073
1074 /// IsBaseType<T>::value is true if T is a "base" type in the AST
1075 /// node class hierarchies.
1076 template <typename T>
1077 struct IsBaseType {
1078 static const bool value =
1079 std::is_same<T, Decl>::value || std::is_same<T, Stmt>::value ||
1080 std::is_same<T, QualType>::value || std::is_same<T, Type>::value ||
1081 std::is_same<T, TypeLoc>::value ||
1082 std::is_same<T, NestedNameSpecifier>::value ||
1083 std::is_same<T, NestedNameSpecifierLoc>::value ||
1084 std::is_same<T, CXXCtorInitializer>::value ||
1085 std::is_same<T, TemplateArgumentLoc>::value;
1086 };
1087 template <typename T>
1088 const bool IsBaseType<T>::value;
1089
1090 /// A type-list implementation.
1091 ///
1092 /// A "linked list" of types, accessible by using the ::head and ::tail
1093 /// typedefs.
1094 template <typename... Ts> struct TypeList {}; // Empty sentinel type list.
1095
1096 template <typename T1, typename... Ts> struct TypeList<T1, Ts...> {
1097 /// The first type on the list.
1098 using head = T1;
1099
1100 /// A sublist with the tail. ie everything but the head.
1101 ///
1102 /// This type is used to do recursion. TypeList<>/EmptyTypeList indicates the
1103 /// end of the list.
1104 using tail = TypeList<Ts...>;
1105 };
1106
1107 /// The empty type list.
1108 using EmptyTypeList = TypeList<>;
1109
1110 /// Helper meta-function to determine if some type \c T is present or
1111 /// a parent type in the list.
1112 template <typename AnyTypeList, typename T>
1113 struct TypeListContainsSuperOf {
1114 static const bool value =
1115 std::is_base_of<typename AnyTypeList::head, T>::value ||
1116 TypeListContainsSuperOf<typename AnyTypeList::tail, T>::value;
1117 };
1118 template <typename T>
1119 struct TypeListContainsSuperOf<EmptyTypeList, T> {
1120 static const bool value = false;
1121 };
1122
1123 /// A "type list" that contains all types.
1124 ///
1125 /// Useful for matchers like \c anything and \c unless.
1126 using AllNodeBaseTypes =
1127 TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc, QualType,
1128 Type, TypeLoc, CXXCtorInitializer>;
1129
1130 /// Helper meta-function to extract the argument out of a function of
1131 /// type void(Arg).
1132 ///
1133 /// See AST_POLYMORPHIC_SUPPORTED_TYPES for details.
1134 template <class T> struct ExtractFunctionArgMeta;
1135 template <class T> struct ExtractFunctionArgMeta<void(T)> {
1136 using type = T;
1137 };
1138
1139 /// Default type lists for ArgumentAdaptingMatcher matchers.
1140 using AdaptativeDefaultFromTypes = AllNodeBaseTypes;
1141 using AdaptativeDefaultToTypes =
1142 TypeList<Decl, Stmt, NestedNameSpecifier, NestedNameSpecifierLoc, TypeLoc,
1143 QualType>;
1144
1145 /// All types that are supported by HasDeclarationMatcher above.
1146 using HasDeclarationSupportedTypes =
1147 TypeList<CallExpr, CXXConstructExpr, CXXNewExpr, DeclRefExpr, EnumType,
1148 ElaboratedType, InjectedClassNameType, LabelStmt, AddrLabelExpr,
1149 MemberExpr, QualType, RecordType, TagType,
1150 TemplateSpecializationType, TemplateTypeParmType, TypedefType,
1151 UnresolvedUsingType, ObjCIvarRefExpr>;
1152
1153 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
1154 typename T, typename ToTypes>
1155 class ArgumentAdaptingMatcherFuncAdaptor {
1156 public:
1157 explicit ArgumentAdaptingMatcherFuncAdaptor(const Matcher<T> &InnerMatcher)
1158 : InnerMatcher(InnerMatcher) {}
1159
1160 using ReturnTypes = ToTypes;
1161
1162 template <typename To> operator Matcher<To>() const {
1163 return Matcher<To>(new ArgumentAdapterT<To, T>(InnerMatcher));
1164 }
1165
1166 private:
1167 const Matcher<T> InnerMatcher;
1168 };
1169
1170 /// Converts a \c Matcher<T> to a matcher of desired type \c To by
1171 /// "adapting" a \c To into a \c T.
1172 ///
1173 /// The \c ArgumentAdapterT argument specifies how the adaptation is done.
1174 ///
1175 /// For example:
1176 /// \c ArgumentAdaptingMatcher<HasMatcher, T>(InnerMatcher);
1177 /// Given that \c InnerMatcher is of type \c Matcher<T>, this returns a matcher
1178 /// that is convertible into any matcher of type \c To by constructing
1179 /// \c HasMatcher<To, T>(InnerMatcher).
1180 ///
1181 /// If a matcher does not need knowledge about the inner type, prefer to use
1182 /// PolymorphicMatcherWithParam1.
1183 template <template <typename ToArg, typename FromArg> class ArgumentAdapterT,
1184 typename FromTypes = AdaptativeDefaultFromTypes,
1185 typename ToTypes = AdaptativeDefaultToTypes>
1186 struct ArgumentAdaptingMatcherFunc {
1187 template <typename T>
1188 static ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>
1189 create(const Matcher<T> &InnerMatcher) {
1190 return ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>(
1191 InnerMatcher);
1192 }
1193
1194 template <typename T>
1195 ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>
1196 operator()(const Matcher<T> &InnerMatcher) const {
1197 return create(InnerMatcher);
1198 }
1199 };
1200
1201 template <typename T> class TraversalMatcher : public MatcherInterface<T> {
1202 const DynTypedMatcher InnerMatcher;
1203 clang::TraversalKind Traversal;
1204
1205 public:
1206 explicit TraversalMatcher(clang::TraversalKind TK,
1207 const Matcher<T> &InnerMatcher)
1208 : InnerMatcher(InnerMatcher), Traversal(TK) {}
1209
1210 bool matches(const T &Node, ASTMatchFinder *Finder,
1211 BoundNodesTreeBuilder *Builder) const override {
1212 return this->InnerMatcher.matches(DynTypedNode::create(Node), Finder,
1213 Builder);
1214 }
1215
1216 llvm::Optional<clang::TraversalKind> TraversalKind() const override {
1217 if (auto NestedKind = this->InnerMatcher.getTraversalKind())
1218 return NestedKind;
1219 return Traversal;
1220 }
1221 };
1222
1223 template <typename MatcherType> class TraversalWrapper {
1224 public:
1225 TraversalWrapper(TraversalKind TK, const MatcherType &InnerMatcher)
1226 : TK(TK), InnerMatcher(InnerMatcher) {}
1227
1228 template <typename T> operator Matcher<T>() const {
1229 return internal::DynTypedMatcher::constructRestrictedWrapper(
1230 new internal::TraversalMatcher<T>(TK, InnerMatcher),
1231 ASTNodeKind::getFromNodeKind<T>())
1232 .template unconditionalConvertTo<T>();
1233 }
1234
1235 private:
1236 TraversalKind TK;
1237 MatcherType InnerMatcher;
1238 };
1239
1240 /// A PolymorphicMatcherWithParamN<MatcherT, P1, ..., PN> object can be
1241 /// created from N parameters p1, ..., pN (of type P1, ..., PN) and
1242 /// used as a Matcher<T> where a MatcherT<T, P1, ..., PN>(p1, ..., pN)
1243 /// can be constructed.
1244 ///
1245 /// For example:
1246 /// - PolymorphicMatcherWithParam0<IsDefinitionMatcher>()
1247 /// creates an object that can be used as a Matcher<T> for any type T
1248 /// where an IsDefinitionMatcher<T>() can be constructed.
1249 /// - PolymorphicMatcherWithParam1<ValueEqualsMatcher, int>(42)
1250 /// creates an object that can be used as a Matcher<T> for any type T
1251 /// where a ValueEqualsMatcher<T, int>(42) can be constructed.
1252 template <template <typename T> class MatcherT,
1253 typename ReturnTypesF = void(AllNodeBaseTypes)>
1254 class PolymorphicMatcherWithParam0 {
1255 public:
1256 using ReturnTypes = typename ExtractFunctionArgMeta<ReturnTypesF>::type;
1257
1258 template <typename T>
1259 operator Matcher<T>() const {
1260 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
1261 "right polymorphic conversion");
1262 return Matcher<T>(new MatcherT<T>());
1263 }
1264 };
1265
1266 template <template <typename T, typename P1> class MatcherT,
1267 typename P1,
1268 typename ReturnTypesF = void(AllNodeBaseTypes)>
1269 class PolymorphicMatcherWithParam1 {
1270 public:
1271 explicit PolymorphicMatcherWithParam1(const P1 &Param1)
1272 : Param1(Param1) {}
1273
1274 using ReturnTypes = typename ExtractFunctionArgMeta<ReturnTypesF>::type;
1275
1276 template <typename T>
1277 operator Matcher<T>() const {
1278 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
1279 "right polymorphic conversion");
1280 return Matcher<T>(new MatcherT<T, P1>(Param1));
1281 }
1282
1283 private:
1284 const P1 Param1;
1285 };
1286
1287 template <template <typename T, typename P1, typename P2> class MatcherT,
1288 typename P1, typename P2,
1289 typename ReturnTypesF = void(AllNodeBaseTypes)>
1290 class PolymorphicMatcherWithParam2 {
1291 public:
1292 PolymorphicMatcherWithParam2(const P1 &Param1, const P2 &Param2)
1293 : Param1(Param1), Param2(Param2) {}
1294
1295 using ReturnTypes = typename ExtractFunctionArgMeta<ReturnTypesF>::type;
1296
1297 template <typename T>
1298 operator Matcher<T>() const {
1299 static_assert(TypeListContainsSuperOf<ReturnTypes, T>::value,
1300 "right polymorphic conversion");
1301 return Matcher<T>(new MatcherT<T, P1, P2>(Param1, Param2));
1302 }
1303
1304 private:
1305 const P1 Param1;
1306 const P2 Param2;
1307 };
1308
1309 /// Matches any instance of the given NodeType.
1310 ///
1311 /// This is useful when a matcher syntactically requires a child matcher,
1312 /// but the context doesn't care. See for example: anything().
1313 class TrueMatcher {
1314 public:
1315 using ReturnTypes = AllNodeBaseTypes;
1316
1317 template <typename T>
1318 operator Matcher<T>() const {
1319 return DynTypedMatcher::trueMatcher(ASTNodeKind::getFromNodeKind<T>())
1320 .template unconditionalConvertTo<T>();
1321 }
1322 };
1323
1324 /// A Matcher that allows binding the node it matches to an id.
1325 ///
1326 /// BindableMatcher provides a \a bind() method that allows binding the
1327 /// matched node to an id if the match was successful.
1328 template <typename T>
1329 class BindableMatcher : public Matcher<T> {
1330 public:
1331 explicit BindableMatcher(const Matcher<T> &M) : Matcher<T>(M) {}
1332 explicit BindableMatcher(MatcherInterface<T> *Implementation)
1333 : Matcher<T>(Implementation) {}
1334
1335 /// Returns a matcher that will bind the matched node on a match.
1336 ///
1337 /// The returned matcher is equivalent to this matcher, but will
1338 /// bind the matched node on a match.
1339 Matcher<T> bind(StringRef ID) const {
1340 return DynTypedMatcher(*this)
1341 .tryBind(ID)
1342 ->template unconditionalConvertTo<T>();
1343 }
1344
1345 /// Same as Matcher<T>'s conversion operator, but enables binding on
1346 /// the returned matcher.
1347 operator DynTypedMatcher() const {
1348 DynTypedMatcher Result = static_cast<const Matcher<T>&>(*this);
1349 Result.setAllowBind(true);
1350 return Result;
1351 }
1352 };
1353
1354 /// Matches nodes of type T that have child nodes of type ChildT for
1355 /// which a specified child matcher matches.
1356 ///
1357 /// ChildT must be an AST base type.
1358 template <typename T, typename ChildT>
1359 class HasMatcher : public MatcherInterface<T> {
1360 const DynTypedMatcher InnerMatcher;
1361
1362 public:
1363 explicit HasMatcher(const Matcher<ChildT> &InnerMatcher)
1364 : InnerMatcher(InnerMatcher) {}
1365
1366 bool matches(const T &Node, ASTMatchFinder *Finder,
1367 BoundNodesTreeBuilder *Builder) const override {
1368 return Finder->matchesChildOf(Node, this->InnerMatcher, Builder,
1369 ASTMatchFinder::BK_First);
1370 }
1371 };
1372
1373 /// Matches nodes of type T that have child nodes of type ChildT for
1374 /// which a specified child matcher matches. ChildT must be an AST base
1375 /// type.
1376 /// As opposed to the HasMatcher, the ForEachMatcher will produce a match
1377 /// for each child that matches.
1378 template <typename T, typename ChildT>
1379 class ForEachMatcher : public MatcherInterface<T> {
1380 static_assert(IsBaseType<ChildT>::value,
1381 "for each only accepts base type matcher");
1382
1383 const DynTypedMatcher InnerMatcher;
1384
1385 public:
1386 explicit ForEachMatcher(const Matcher<ChildT> &InnerMatcher)
1387 : InnerMatcher(InnerMatcher) {}
1388
1389 bool matches(const T &Node, ASTMatchFinder *Finder,
1390 BoundNodesTreeBuilder *Builder) const override {
1391 return Finder->matchesChildOf(
1392 Node, this->InnerMatcher, Builder,
1393 ASTMatchFinder::BK_All);
1394 }
1395 };
1396
1397 /// VariadicOperatorMatcher related types.
1398 /// @{
1399
1400 /// Polymorphic matcher object that uses a \c
1401 /// DynTypedMatcher::VariadicOperator operator.
1402 ///
1403 /// Input matchers can have any type (including other polymorphic matcher
1404 /// types), and the actual Matcher<T> is generated on demand with an implicit
1405 /// conversion operator.
1406 template <typename... Ps> class VariadicOperatorMatcher {
1407 public:
1408 VariadicOperatorMatcher(DynTypedMatcher::VariadicOperator Op, Ps &&... Params)
1409 : Op(Op), Params(std::forward<Ps>(Params)...) {}
1410
1411 template <typename T> operator Matcher<T>() const {
1412 return DynTypedMatcher::constructVariadic(
1413 Op, ASTNodeKind::getFromNodeKind<T>(),
1414 getMatchers<T>(std::index_sequence_for<Ps...>()))
1415 .template unconditionalConvertTo<T>();
1416 }
1417
1418 private:
1419 // Helper method to unpack the tuple into a vector.
1420 template <typename T, std::size_t... Is>
1421 std::vector<DynTypedMatcher> getMatchers(std::index_sequence<Is...>) const {
1422 return {Matcher<T>(std::get<Is>(Params))...};
1423 }
1424
1425 const DynTypedMatcher::VariadicOperator Op;
1426 std::tuple<Ps...> Params;
1427 };
1428
1429 /// Overloaded function object to generate VariadicOperatorMatcher
1430 /// objects from arbitrary matchers.
1431 template <unsigned MinCount, unsigned MaxCount>
1432 struct VariadicOperatorMatcherFunc {
1433 DynTypedMatcher::VariadicOperator Op;
1434
1435 template <typename... Ms>
1436 VariadicOperatorMatcher<Ms...> operator()(Ms &&... Ps) const {
1437 static_assert(MinCount <= sizeof...(Ms) && sizeof...(Ms) <= MaxCount,
1438 "invalid number of parameters for variadic matcher");
1439 return VariadicOperatorMatcher<Ms...>(Op, std::forward<Ms>(Ps)...);
1440 }
1441 };
1442
1443 /// @}
1444
1445 template <typename T>
1446 inline Matcher<T> DynTypedMatcher::unconditionalConvertTo() const {
1447 return Matcher<T>(*this);
1448 }
1449
1450 /// Creates a Matcher<T> that matches if all inner matchers match.
1451 template<typename T>
1452 BindableMatcher<T> makeAllOfComposite(
1453 ArrayRef<const Matcher<T> *> InnerMatchers) {
1454 // For the size() == 0 case, we return a "true" matcher.
1455 if (InnerMatchers.empty()) {
1456 return BindableMatcher<T>(TrueMatcher());
1457 }
1458 // For the size() == 1 case, we simply return that one matcher.
1459 // No need to wrap it in a variadic operation.
1460 if (InnerMatchers.size() == 1) {
1461 return BindableMatcher<T>(*InnerMatchers[0]);
1462 }
1463
1464 using PI = llvm::pointee_iterator<const Matcher<T> *const *>;
1465
1466 std::vector<DynTypedMatcher> DynMatchers(PI(InnerMatchers.begin()),
1467 PI(InnerMatchers.end()));
1468 return BindableMatcher<T>(
1469 DynTypedMatcher::constructVariadic(DynTypedMatcher::VO_AllOf,
1470 ASTNodeKind::getFromNodeKind<T>(),
1471 std::move(DynMatchers))
1472 .template unconditionalConvertTo<T>());
1473 }
1474
1475 /// Creates a Matcher<T> that matches if
1476 /// T is dyn_cast'able into InnerT and all inner matchers match.
1477 ///
1478 /// Returns BindableMatcher, as matchers that use dyn_cast have
1479 /// the same object both to match on and to run submatchers on,
1480 /// so there is no ambiguity with what gets bound.
1481 template<typename T, typename InnerT>
1482 BindableMatcher<T> makeDynCastAllOfComposite(
1483 ArrayRef<const Matcher<InnerT> *> InnerMatchers) {
1484 return BindableMatcher<T>(
1485 makeAllOfComposite(InnerMatchers).template dynCastTo<T>());
1486 }
1487
1488 /// Matches nodes of type T that have at least one descendant node of
1489 /// type DescendantT for which the given inner matcher matches.
1490 ///
1491 /// DescendantT must be an AST base type.
1492 template <typename T, typename DescendantT>
1493 class HasDescendantMatcher : public MatcherInterface<T> {
1494 static_assert(IsBaseType<DescendantT>::value,
1495 "has descendant only accepts base type matcher");
1496
1497 const DynTypedMatcher DescendantMatcher;
1498
1499 public:
1500 explicit HasDescendantMatcher(const Matcher<DescendantT> &DescendantMatcher)
1501 : DescendantMatcher(DescendantMatcher) {}
1502
1503 bool matches(const T &Node, ASTMatchFinder *Finder,
1504 BoundNodesTreeBuilder *Builder) const override {
1505 return Finder->matchesDescendantOf(Node, this->DescendantMatcher, Builder,
1506 ASTMatchFinder::BK_First);
1507 }
1508 };
1509
1510 /// Matches nodes of type \c T that have a parent node of type \c ParentT
1511 /// for which the given inner matcher matches.
1512 ///
1513 /// \c ParentT must be an AST base type.
1514 template <typename T, typename ParentT>
1515 class HasParentMatcher : public MatcherInterface<T> {
1516 static_assert(IsBaseType<ParentT>::value,
1517 "has parent only accepts base type matcher");
1518
1519 const DynTypedMatcher ParentMatcher;
1520
1521 public:
1522 explicit HasParentMatcher(const Matcher<ParentT> &ParentMatcher)
1523 : ParentMatcher(ParentMatcher) {}
1524
1525 bool matches(const T &Node, ASTMatchFinder *Finder,
1526 BoundNodesTreeBuilder *Builder) const override {
1527 return Finder->matchesAncestorOf(Node, this->ParentMatcher, Builder,
1528 ASTMatchFinder::AMM_ParentOnly);
1529 }
1530 };
1531
1532 /// Matches nodes of type \c T that have at least one ancestor node of
1533 /// type \c AncestorT for which the given inner matcher matches.
1534 ///
1535 /// \c AncestorT must be an AST base type.
1536 template <typename T, typename AncestorT>
1537 class HasAncestorMatcher : public MatcherInterface<T> {
1538 static_assert(IsBaseType<AncestorT>::value,
1539 "has ancestor only accepts base type matcher");
1540
1541 const DynTypedMatcher AncestorMatcher;
1542
1543 public:
1544 explicit HasAncestorMatcher(const Matcher<AncestorT> &AncestorMatcher)
1545 : AncestorMatcher(AncestorMatcher) {}
1546
1547 bool matches(const T &Node, ASTMatchFinder *Finder,
1548 BoundNodesTreeBuilder *Builder) const override {
1549 return Finder->matchesAncestorOf(Node, this->AncestorMatcher, Builder,
1550 ASTMatchFinder::AMM_All);
1551 }
1552 };
1553
1554 /// Matches nodes of type T that have at least one descendant node of
1555 /// type DescendantT for which the given inner matcher matches.
1556 ///
1557 /// DescendantT must be an AST base type.
1558 /// As opposed to HasDescendantMatcher, ForEachDescendantMatcher will match
1559 /// for each descendant node that matches instead of only for the first.
1560 template <typename T, typename DescendantT>
1561 class ForEachDescendantMatcher : public MatcherInterface<T> {
1562 static_assert(IsBaseType<DescendantT>::value,
1563 "for each descendant only accepts base type matcher");
1564
1565 const DynTypedMatcher DescendantMatcher;
1566
1567 public:
1568 explicit ForEachDescendantMatcher(
1569 const Matcher<DescendantT> &DescendantMatcher)
1570 : DescendantMatcher(DescendantMatcher) {}
1571
1572 bool matches(const T &Node, ASTMatchFinder *Finder,
1573 BoundNodesTreeBuilder *Builder) const override {
1574 return Finder->matchesDescendantOf(Node, this->DescendantMatcher, Builder,
1575 ASTMatchFinder::BK_All);
1576 }
1577 };
1578
1579 /// Matches on nodes that have a getValue() method if getValue() equals
1580 /// the value the ValueEqualsMatcher was constructed with.
1581 template <typename T, typename ValueT>
1582 class ValueEqualsMatcher : public SingleNodeMatcherInterface<T> {
1583 static_assert(std::is_base_of<CharacterLiteral, T>::value ||
1584 std::is_base_of<CXXBoolLiteralExpr, T>::value ||
1585 std::is_base_of<FloatingLiteral, T>::value ||
1586 std::is_base_of<IntegerLiteral, T>::value,
1587 "the node must have a getValue method");
1588
1589 public:
1590 explicit ValueEqualsMatcher(const ValueT &ExpectedValue)
1591 : ExpectedValue(ExpectedValue) {}
1592
1593 bool matchesNode(const T &Node) const override {
1594 return Node.getValue() == ExpectedValue;
1595 }
1596
1597 private:
1598 const ValueT ExpectedValue;
1599 };
1600
1601 /// Template specializations to easily write matchers for floating point
1602 /// literals.
1603 template <>
1604 inline bool ValueEqualsMatcher<FloatingLiteral, double>::matchesNode(
1605 const FloatingLiteral &Node) const {
1606 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle())
1607 return Node.getValue().convertToFloat() == ExpectedValue;
1608 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble())
1609 return Node.getValue().convertToDouble() == ExpectedValue;
1610 return false;
1611 }
1612 template <>
1613 inline bool ValueEqualsMatcher<FloatingLiteral, float>::matchesNode(
1614 const FloatingLiteral &Node) const {
1615 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle())
1616 return Node.getValue().convertToFloat() == ExpectedValue;
1617 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble())
1618 return Node.getValue().convertToDouble() == ExpectedValue;
1619 return false;
1620 }
1621 template <>
1622 inline bool ValueEqualsMatcher<FloatingLiteral, llvm::APFloat>::matchesNode(
1623 const FloatingLiteral &Node) const {
1624 return ExpectedValue.compare(Node.getValue()) == llvm::APFloat::cmpEqual;
1625 }
1626
1627 /// A VariadicDynCastAllOfMatcher<SourceT, TargetT> object is a
1628 /// variadic functor that takes a number of Matcher<TargetT> and returns a
1629 /// Matcher<SourceT> that matches TargetT nodes that are matched by all of the
1630 /// given matchers, if SourceT can be dynamically casted into TargetT.
1631 ///
1632 /// For example:
1633 /// const VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl> record;
1634 /// Creates a functor record(...) that creates a Matcher<Decl> given
1635 /// a variable number of arguments of type Matcher<CXXRecordDecl>.
1636 /// The returned matcher matches if the given Decl can by dynamically
1637 /// casted to CXXRecordDecl and all given matchers match.
1638 template <typename SourceT, typename TargetT>
1639 class VariadicDynCastAllOfMatcher
1640 : public VariadicFunction<BindableMatcher<SourceT>, Matcher<TargetT>,
1641 makeDynCastAllOfComposite<SourceT, TargetT>> {
1642 public:
1643 VariadicDynCastAllOfMatcher() {}
1644 };
1645
1646 /// A \c VariadicAllOfMatcher<T> object is a variadic functor that takes
1647 /// a number of \c Matcher<T> and returns a \c Matcher<T> that matches \c T
1648 /// nodes that are matched by all of the given matchers.
1649 ///
1650 /// For example:
1651 /// const VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
1652 /// Creates a functor nestedNameSpecifier(...) that creates a
1653 /// \c Matcher<NestedNameSpecifier> given a variable number of arguments of type
1654 /// \c Matcher<NestedNameSpecifier>.
1655 /// The returned matcher matches if all given matchers match.
1656 template <typename T>
1657 class VariadicAllOfMatcher
1658 : public VariadicFunction<BindableMatcher<T>, Matcher<T>,
1659 makeAllOfComposite<T>> {
1660 public:
1661 VariadicAllOfMatcher() {}
1662 };
1663
1664 /// Matches nodes of type \c TLoc for which the inner
1665 /// \c Matcher<T> matches.
1666 template <typename TLoc, typename T>
1667 class LocMatcher : public MatcherInterface<TLoc> {
1668 const DynTypedMatcher InnerMatcher;
1669
1670 public:
1671 explicit LocMatcher(const Matcher<T> &InnerMatcher)
1672 : InnerMatcher(InnerMatcher) {}
1673
1674 bool matches(const TLoc &Node, ASTMatchFinder *Finder,
1675 BoundNodesTreeBuilder *Builder) const override {
1676 if (!Node)
1677 return false;
1678 return this->InnerMatcher.matches(extract(Node), Finder, Builder);
1679 }
1680
1681 private:
1682 static DynTypedNode extract(const NestedNameSpecifierLoc &Loc) {
1683 return DynTypedNode::create(*Loc.getNestedNameSpecifier());
1684 }
1685 };
1686
1687 /// Matches \c TypeLocs based on an inner matcher matching a certain
1688 /// \c QualType.
1689 ///
1690 /// Used to implement the \c loc() matcher.
1691 class TypeLocTypeMatcher : public MatcherInterface<TypeLoc> {
1692 const DynTypedMatcher InnerMatcher;
1693
1694 public:
1695 explicit TypeLocTypeMatcher(const Matcher<QualType> &InnerMatcher)
1696 : InnerMatcher(InnerMatcher) {}
1697
1698 bool matches(const TypeLoc &Node, ASTMatchFinder *Finder,
1699 BoundNodesTreeBuilder *Builder) const override {
1700 if (!Node)
1701 return false;
1702 return this->InnerMatcher.matches(DynTypedNode::create(Node.getType()),
1703 Finder, Builder);
1704 }
1705 };
1706
1707 /// Matches nodes of type \c T for which the inner matcher matches on a
1708 /// another node of type \c T that can be reached using a given traverse
1709 /// function.
1710 template <typename T> class TypeTraverseMatcher : public MatcherInterface<T> {
1711 const DynTypedMatcher InnerMatcher;
1712
1713 public:
1714 explicit TypeTraverseMatcher(const Matcher<QualType> &InnerMatcher,
1715 QualType (T::*TraverseFunction)() const)
1716 : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {}
1717
1718 bool matches(const T &Node, ASTMatchFinder *Finder,
1719 BoundNodesTreeBuilder *Builder) const override {
1720 QualType NextNode = (Node.*TraverseFunction)();
1721 if (NextNode.isNull())
1722 return false;
1723 return this->InnerMatcher.matches(DynTypedNode::create(NextNode), Finder,
1724 Builder);
1725 }
1726
1727 private:
1728 QualType (T::*TraverseFunction)() const;
1729 };
1730
1731 /// Matches nodes of type \c T in a ..Loc hierarchy, for which the inner
1732 /// matcher matches on a another node of type \c T that can be reached using a
1733 /// given traverse function.
1734 template <typename T>
1735 class TypeLocTraverseMatcher : public MatcherInterface<T> {
1736 const DynTypedMatcher InnerMatcher;
1737
1738 public:
1739 explicit TypeLocTraverseMatcher(const Matcher<TypeLoc> &InnerMatcher,
1740 TypeLoc (T::*TraverseFunction)() const)
1741 : InnerMatcher(InnerMatcher), TraverseFunction(TraverseFunction) {}
1742
1743 bool matches(const T &Node, ASTMatchFinder *Finder,
1744 BoundNodesTreeBuilder *Builder) const override {
1745 TypeLoc NextNode = (Node.*TraverseFunction)();
1746 if (!NextNode)
1747 return false;
1748 return this->InnerMatcher.matches(DynTypedNode::create(NextNode), Finder,
1749 Builder);
1750 }
1751
1752 private:
1753 TypeLoc (T::*TraverseFunction)() const;
1754 };
1755
1756 /// Converts a \c Matcher<InnerT> to a \c Matcher<OuterT>, where
1757 /// \c OuterT is any type that is supported by \c Getter.
1758 ///
1759 /// \code Getter<OuterT>::value() \endcode returns a
1760 /// \code InnerTBase (OuterT::*)() \endcode, which is used to adapt a \c OuterT
1761 /// object into a \c InnerT
1762 template <typename InnerTBase,
1763 template <typename OuterT> class Getter,
1764 template <typename OuterT> class MatcherImpl,
1765 typename ReturnTypesF>
1766 class TypeTraversePolymorphicMatcher {
1767 private:
1768 using Self = TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl,
1769 ReturnTypesF>;
1770
1771 static Self create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers);
1772
1773 public:
1774 using ReturnTypes = typename ExtractFunctionArgMeta<ReturnTypesF>::type;
1775
1776 explicit TypeTraversePolymorphicMatcher(
1777 ArrayRef<const Matcher<InnerTBase> *> InnerMatchers)
1778 : InnerMatcher(makeAllOfComposite(InnerMatchers)) {}
1779
1780 template <typename OuterT> operator Matcher<OuterT>() const {
1781 return Matcher<OuterT>(
1782 new MatcherImpl<OuterT>(InnerMatcher, Getter<OuterT>::value()));
1783 }
1784
1785 struct Func
1786 : public VariadicFunction<Self, Matcher<InnerTBase>, &Self::create> {
1787 Func() {}
1788 };
1789
1790 private:
1791 const Matcher<InnerTBase> InnerMatcher;
1792 };
1793
1794 /// A simple memoizer of T(*)() functions.
1795 ///
1796 /// It will call the passed 'Func' template parameter at most once.
1797 /// Used to support AST_MATCHER_FUNCTION() macro.
1798 template <typename Matcher, Matcher (*Func)()> class MemoizedMatcher {
1799 struct Wrapper {
1800 Wrapper() : M(Func()) {}
1801
1802 Matcher M;
1803 };
1804
1805 public:
1806 static const Matcher &getInstance() {
1807 static llvm::ManagedStatic<Wrapper> Instance;
1808 return Instance->M;
1809 }
1810 };
1811
1812 // Define the create() method out of line to silence a GCC warning about
1813 // the struct "Func" having greater visibility than its base, which comes from
1814 // using the flag -fvisibility-inlines-hidden.
1815 template <typename InnerTBase, template <typename OuterT> class Getter,
1816 template <typename OuterT> class MatcherImpl, typename ReturnTypesF>
1817 TypeTraversePolymorphicMatcher<InnerTBase, Getter, MatcherImpl, ReturnTypesF>
1818 TypeTraversePolymorphicMatcher<
1819 InnerTBase, Getter, MatcherImpl,
1820 ReturnTypesF>::create(ArrayRef<const Matcher<InnerTBase> *> InnerMatchers) {
1821 return Self(InnerMatchers);
1822 }
1823
1824 // FIXME: unify ClassTemplateSpecializationDecl and TemplateSpecializationType's
1825 // APIs for accessing the template argument list.
1826 inline ArrayRef<TemplateArgument>
1827 getTemplateSpecializationArgs(const ClassTemplateSpecializationDecl &D) {
1828 return D.getTemplateArgs().asArray();
1829 }
1830
1831 inline ArrayRef<TemplateArgument>
1832 getTemplateSpecializationArgs(const TemplateSpecializationType &T) {
1833 return llvm::makeArrayRef(T.getArgs(), T.getNumArgs());
1834 }
1835
1836 inline ArrayRef<TemplateArgument>
1837 getTemplateSpecializationArgs(const FunctionDecl &FD) {
1838 if (const auto* TemplateArgs = FD.getTemplateSpecializationArgs())
1839 return TemplateArgs->asArray();
1840 return ArrayRef<TemplateArgument>();
1841 }
1842
1843 struct NotEqualsBoundNodePredicate {
1844 bool operator()(const internal::BoundNodesMap &Nodes) const {
1845 return Nodes.getNode(ID) != Node;
1846 }
1847
1848 std::string ID;
1849 DynTypedNode Node;
1850 };
1851
1852 template <typename Ty, typename Enable = void> struct GetBodyMatcher {
1853 static const Stmt *get(const Ty &Node) { return Node.getBody(); }
1854 };
1855
1856 template <typename Ty>
1857 struct GetBodyMatcher<Ty, typename std::enable_if<
1858 std::is_base_of<FunctionDecl, Ty>::value>::type> {
1859 static const Stmt *get(const Ty &Node) {
1860 return Node.doesThisDeclarationHaveABody() ? Node.getBody() : nullptr;
1861 }
1862 };
1863
1864 template <typename Ty>
1865 struct HasSizeMatcher {
1866 static bool hasSize(const Ty &Node, unsigned int N) {
1867 return Node.getSize() == N;
1868 }
1869 };
1870
1871 template <>
1872 inline bool HasSizeMatcher<StringLiteral>::hasSize(
1873 const StringLiteral &Node, unsigned int N) {
1874 return Node.getLength() == N;
1875 }
1876
1877 template <typename Ty>
1878 struct GetSourceExpressionMatcher {
1879 static const Expr *get(const Ty &Node) {
1880 return Node.getSubExpr();
1881 }
1882 };
1883
1884 template <>
1885 inline const Expr *GetSourceExpressionMatcher<OpaqueValueExpr>::get(
1886 const OpaqueValueExpr &Node) {
1887 return Node.getSourceExpr();
1888 }
1889
1890 template <typename Ty>
1891 struct CompoundStmtMatcher {
1892 static const CompoundStmt *get(const Ty &Node) {
1893 return &Node;
1894 }
1895 };
1896
1897 template <>
1898 inline const CompoundStmt *
1899 CompoundStmtMatcher<StmtExpr>::get(const StmtExpr &Node) {
1900 return Node.getSubStmt();
1901 }
1902
1903 /// If \p Loc is (transitively) expanded from macro \p MacroName, returns the
1904 /// location (in the chain of expansions) at which \p MacroName was
1905 /// expanded. Since the macro may have been expanded inside a series of
1906 /// expansions, that location may itself be a MacroID.
1907 llvm::Optional<SourceLocation>
1908 getExpansionLocOfMacro(StringRef MacroName, SourceLocation Loc,
1909 const ASTContext &Context);
1910
1911 /// Matches overloaded operators with a specific name.
1912 ///
1913 /// The type argument ArgT is not used by this matcher but is used by
1914 /// PolymorphicMatcherWithParam1 and should be std::vector<std::string>>.
1915 template <typename T, typename ArgT = std::vector<std::string>>
1916 class HasAnyOperatorNameMatcher : public SingleNodeMatcherInterface<T> {
1917 static_assert(std::is_same<T, BinaryOperator>::value ||
1918 std::is_same<T, UnaryOperator>::value,
1919 "Matcher only supports `BinaryOperator` and `UnaryOperator`");
1920 static_assert(std::is_same<ArgT, std::vector<std::string>>::value,
1921 "Matcher ArgT must be std::vector<std::string>");
1922
1923 public:
1924 explicit HasAnyOperatorNameMatcher(std::vector<std::string> Names)
1925 : SingleNodeMatcherInterface<T>(), Names(std::move(Names)) {}
1926
1927 bool matchesNode(const T &Node) const override {
1928 StringRef OpName = getOpName(Node);
1929 return llvm::any_of(
1930 Names, [&](const std::string &Name) { return Name == OpName; });
1931 }
1932
1933 private:
1934 static StringRef getOpName(const UnaryOperator &Node) {
1935 return Node.getOpcodeStr(Node.getOpcode());
1936 }
1937 static StringRef getOpName(const BinaryOperator &Node) {
1938 return Node.getOpcodeStr();
1939 }
1940
1941 const std::vector<std::string> Names;
1942 };
1943
1944 using HasOpNameMatcher =
1945 PolymorphicMatcherWithParam1<HasAnyOperatorNameMatcher,
1946 std::vector<std::string>,
1947 void(TypeList<BinaryOperator, UnaryOperator>)>;
1948
1949 HasOpNameMatcher hasAnyOperatorNameFunc(ArrayRef<const StringRef *> NameRefs);
1950
1951 using HasOverloadOpNameMatcher = PolymorphicMatcherWithParam1<
1952 HasOverloadedOperatorNameMatcher, std::vector<std::string>,
1953 void(TypeList<CXXOperatorCallExpr, FunctionDecl>)>;
1954
1955 HasOverloadOpNameMatcher
1956 hasAnyOverloadedOperatorNameFunc(ArrayRef<const StringRef *> NameRefs);
1957
1958 /// Returns true if \p Node has a base specifier matching \p BaseSpec.
1959 ///
1960 /// A class is not considered to be derived from itself.
1961 bool matchesAnyBase(const CXXRecordDecl &Node,
1962 const Matcher<CXXBaseSpecifier> &BaseSpecMatcher,
1963 ASTMatchFinder *Finder, BoundNodesTreeBuilder *Builder);
1964
1965 std::shared_ptr<llvm::Regex> createAndVerifyRegex(StringRef Regex,
1966 llvm::Regex::RegexFlags Flags,
1967 StringRef MatcherID);
1968
1969 } // namespace internal
1970
1971 } // namespace ast_matchers
1972
1973 } // namespace clang
1974
1975 #endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERSINTERNAL_H
1976