Warning: This file is not a C or C++ file. It does not have highlighting.

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

Warning: This file is not a C or C++ file. It does not have highlighting.

source code of clang/include/clang/ASTMatchers/ASTMatchersInternal.h