1 //===- ASTMatchersInternal.cpp - Structural query framework ---------------===//
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 //===----------------------------------------------------------------------===//
12 
13 #include "clang/ASTMatchers/ASTMatchersInternal.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTTypeTraits.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/ParentMapContext.h"
19 #include "clang/AST/PrettyPrinter.h"
20 #include "clang/ASTMatchers/ASTMatchers.h"
21 #include "clang/Basic/LLVM.h"
22 #include "clang/Lex/Lexer.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/IntrusiveRefCntPtr.h"
25 #include "llvm/ADT/None.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <algorithm>
34 #include <cassert>
35 #include <cstddef>
36 #include <string>
37 #include <utility>
38 #include <vector>
39 
40 namespace clang {
41 namespace ast_matchers {
42 
43 AST_MATCHER_P(ObjCMessageExpr, hasAnySelectorMatcher, std::vector<std::string>,
44               Matches) {
45   std::string SelString = Node.getSelector().getAsString();
46   for (const std::string &S : Matches)
47     if (S == SelString)
48       return true;
49   return false;
50 }
51 
52 namespace internal {
53 
54 bool NotUnaryOperator(const DynTypedNode &DynNode, ASTMatchFinder *Finder,
55                       BoundNodesTreeBuilder *Builder,
56                       ArrayRef<DynTypedMatcher> InnerMatchers);
57 
58 bool AllOfVariadicOperator(const DynTypedNode &DynNode, ASTMatchFinder *Finder,
59                            BoundNodesTreeBuilder *Builder,
60                            ArrayRef<DynTypedMatcher> InnerMatchers);
61 
62 bool EachOfVariadicOperator(const DynTypedNode &DynNode, ASTMatchFinder *Finder,
63                             BoundNodesTreeBuilder *Builder,
64                             ArrayRef<DynTypedMatcher> InnerMatchers);
65 
66 bool AnyOfVariadicOperator(const DynTypedNode &DynNode, ASTMatchFinder *Finder,
67                            BoundNodesTreeBuilder *Builder,
68                            ArrayRef<DynTypedMatcher> InnerMatchers);
69 
70 bool OptionallyVariadicOperator(const DynTypedNode &DynNode,
71                                 ASTMatchFinder *Finder,
72                                 BoundNodesTreeBuilder *Builder,
73                                 ArrayRef<DynTypedMatcher> InnerMatchers);
74 
75 void BoundNodesTreeBuilder::visitMatches(Visitor *ResultVisitor) {
76   if (Bindings.empty())
77     Bindings.push_back(BoundNodesMap());
78   for (BoundNodesMap &Binding : Bindings) {
79     ResultVisitor->visitMatch(BoundNodes(Binding));
80   }
81 }
82 
83 namespace {
84 
85 using VariadicOperatorFunction = bool (*)(
86     const DynTypedNode &DynNode, ASTMatchFinder *Finder,
87     BoundNodesTreeBuilder *Builder, ArrayRef<DynTypedMatcher> InnerMatchers);
88 
89 template <VariadicOperatorFunction Func>
90 class VariadicMatcher : public DynMatcherInterface {
91 public:
92   VariadicMatcher(std::vector<DynTypedMatcher> InnerMatchers)
93       : InnerMatchers(std::move(InnerMatchers)) {}
94 
95   bool dynMatches(const DynTypedNode &DynNode, ASTMatchFinder *Finder,
96                   BoundNodesTreeBuilder *Builder) const override {
97     return Func(DynNode, Finder, Builder, InnerMatchers);
98   }
99 
100 private:
101   std::vector<DynTypedMatcher> InnerMatchers;
102 };
103 
104 class IdDynMatcher : public DynMatcherInterface {
105 public:
106   IdDynMatcher(StringRef ID,
107                IntrusiveRefCntPtr<DynMatcherInterface> InnerMatcher)
108       : ID(ID), InnerMatcher(std::move(InnerMatcher)) {}
109 
110   bool dynMatches(const DynTypedNode &DynNode, ASTMatchFinder *Finder,
111                   BoundNodesTreeBuilder *Builder) const override {
112     bool Result = InnerMatcher->dynMatches(DynNode, Finder, Builder);
113     if (Result) Builder->setBinding(ID, DynNode);
114     return Result;
115   }
116 
117   llvm::Optional<clang::TraversalKind> TraversalKind() const override {
118     return InnerMatcher->TraversalKind();
119   }
120 
121 private:
122   const std::string ID;
123   const IntrusiveRefCntPtr<DynMatcherInterface> InnerMatcher;
124 };
125 
126 /// A matcher that always returns true.
127 ///
128 /// We only ever need one instance of this matcher, so we create a global one
129 /// and reuse it to reduce the overhead of the matcher and increase the chance
130 /// of cache hits.
131 class TrueMatcherImpl : public DynMatcherInterface {
132 public:
133   TrueMatcherImpl() {
134     Retain(); // Reference count will never become zero.
135   }
136 
137   bool dynMatches(const DynTypedNode &, ASTMatchFinder *,
138                   BoundNodesTreeBuilder *) const override {
139     return true;
140   }
141 };
142 
143 } // namespace
144 
145 static llvm::ManagedStatic<TrueMatcherImpl> TrueMatcherInstance;
146 
147 DynTypedMatcher
148 DynTypedMatcher::constructVariadic(DynTypedMatcher::VariadicOperator Op,
149                                    ASTNodeKind SupportedKind,
150                                    std::vector<DynTypedMatcher> InnerMatchers) {
151   assert(!InnerMatchers.empty() && "Array must not be empty.");
152   assert(llvm::all_of(InnerMatchers,
153                       [SupportedKind](const DynTypedMatcher &M) {
154                         return M.canConvertTo(SupportedKind);
155                       }) &&
156          "InnerMatchers must be convertible to SupportedKind!");
157 
158   // We must relax the restrict kind here.
159   // The different operators might deal differently with a mismatch.
160   // Make it the same as SupportedKind, since that is the broadest type we are
161   // allowed to accept.
162   auto RestrictKind = SupportedKind;
163 
164   switch (Op) {
165   case VO_AllOf:
166     // In the case of allOf() we must pass all the checks, so making
167     // RestrictKind the most restrictive can save us time. This way we reject
168     // invalid types earlier and we can elide the kind checks inside the
169     // matcher.
170     for (auto &IM : InnerMatchers) {
171       RestrictKind =
172           ASTNodeKind::getMostDerivedType(RestrictKind, IM.RestrictKind);
173     }
174     return DynTypedMatcher(
175         SupportedKind, RestrictKind,
176         new VariadicMatcher<AllOfVariadicOperator>(std::move(InnerMatchers)));
177 
178   case VO_AnyOf:
179     return DynTypedMatcher(
180         SupportedKind, RestrictKind,
181         new VariadicMatcher<AnyOfVariadicOperator>(std::move(InnerMatchers)));
182 
183   case VO_EachOf:
184     return DynTypedMatcher(
185         SupportedKind, RestrictKind,
186         new VariadicMatcher<EachOfVariadicOperator>(std::move(InnerMatchers)));
187 
188   case VO_Optionally:
189     return DynTypedMatcher(SupportedKind, RestrictKind,
190                            new VariadicMatcher<OptionallyVariadicOperator>(
191                                std::move(InnerMatchers)));
192 
193   case VO_UnaryNot:
194     // FIXME: Implement the Not operator to take a single matcher instead of a
195     // vector.
196     return DynTypedMatcher(
197         SupportedKind, RestrictKind,
198         new VariadicMatcher<NotUnaryOperator>(std::move(InnerMatchers)));
199   }
200   llvm_unreachable("Invalid Op value.");
201 }
202 
203 DynTypedMatcher
204 DynTypedMatcher::constructRestrictedWrapper(const DynTypedMatcher &InnerMatcher,
205                                             ASTNodeKind RestrictKind) {
206   DynTypedMatcher Copy = InnerMatcher;
207   Copy.RestrictKind = RestrictKind;
208   return Copy;
209 }
210 
211 DynTypedMatcher DynTypedMatcher::trueMatcher(ASTNodeKind NodeKind) {
212   return DynTypedMatcher(NodeKind, NodeKind, &*TrueMatcherInstance);
213 }
214 
215 bool DynTypedMatcher::canMatchNodesOfKind(ASTNodeKind Kind) const {
216   return RestrictKind.isBaseOf(Kind);
217 }
218 
219 DynTypedMatcher DynTypedMatcher::dynCastTo(const ASTNodeKind Kind) const {
220   auto Copy = *this;
221   Copy.SupportedKind = Kind;
222   Copy.RestrictKind = ASTNodeKind::getMostDerivedType(Kind, RestrictKind);
223   return Copy;
224 }
225 
226 bool DynTypedMatcher::matches(const DynTypedNode &DynNode,
227                               ASTMatchFinder *Finder,
228                               BoundNodesTreeBuilder *Builder) const {
229   TraversalKindScope RAII(Finder->getASTContext(),
230                           Implementation->TraversalKind());
231 
232   auto N =
233       Finder->getASTContext().getParentMapContext().traverseIgnored(DynNode);
234 
235   if (RestrictKind.isBaseOf(N.getNodeKind()) &&
236       Implementation->dynMatches(N, Finder, Builder)) {
237     return true;
238   }
239   // Delete all bindings when a matcher does not match.
240   // This prevents unexpected exposure of bound nodes in unmatches
241   // branches of the match tree.
242   Builder->removeBindings([](const BoundNodesMap &) { return true; });
243   return false;
244 }
245 
246 bool DynTypedMatcher::matchesNoKindCheck(const DynTypedNode &DynNode,
247                                          ASTMatchFinder *Finder,
248                                          BoundNodesTreeBuilder *Builder) const {
249   TraversalKindScope raii(Finder->getASTContext(),
250                           Implementation->TraversalKind());
251 
252   auto N =
253       Finder->getASTContext().getParentMapContext().traverseIgnored(DynNode);
254 
255   assert(RestrictKind.isBaseOf(N.getNodeKind()));
256   if (Implementation->dynMatches(N, Finder, Builder)) {
257     return true;
258   }
259   // Delete all bindings when a matcher does not match.
260   // This prevents unexpected exposure of bound nodes in unmatches
261   // branches of the match tree.
262   Builder->removeBindings([](const BoundNodesMap &) { return true; });
263   return false;
264 }
265 
266 llvm::Optional<DynTypedMatcher> DynTypedMatcher::tryBind(StringRef ID) const {
267   if (!AllowBind) return llvm::None;
268   auto Result = *this;
269   Result.Implementation =
270       new IdDynMatcher(ID, std::move(Result.Implementation));
271   return std::move(Result);
272 }
273 
274 bool DynTypedMatcher::canConvertTo(ASTNodeKind To) const {
275   const auto From = getSupportedKind();
276   auto QualKind = ASTNodeKind::getFromNodeKind<QualType>();
277   auto TypeKind = ASTNodeKind::getFromNodeKind<Type>();
278   /// Mimic the implicit conversions of Matcher<>.
279   /// - From Matcher<Type> to Matcher<QualType>
280   if (From.isSame(TypeKind) && To.isSame(QualKind)) return true;
281   /// - From Matcher<Base> to Matcher<Derived>
282   return From.isBaseOf(To);
283 }
284 
285 void BoundNodesTreeBuilder::addMatch(const BoundNodesTreeBuilder &Other) {
286   Bindings.append(Other.Bindings.begin(), Other.Bindings.end());
287 }
288 
289 bool NotUnaryOperator(const DynTypedNode &DynNode, ASTMatchFinder *Finder,
290                       BoundNodesTreeBuilder *Builder,
291                       ArrayRef<DynTypedMatcher> InnerMatchers) {
292   if (InnerMatchers.size() != 1)
293     return false;
294 
295   // The 'unless' matcher will always discard the result:
296   // If the inner matcher doesn't match, unless returns true,
297   // but the inner matcher cannot have bound anything.
298   // If the inner matcher matches, the result is false, and
299   // any possible binding will be discarded.
300   // We still need to hand in all the bound nodes up to this
301   // point so the inner matcher can depend on bound nodes,
302   // and we need to actively discard the bound nodes, otherwise
303   // the inner matcher will reset the bound nodes if it doesn't
304   // match, but this would be inversed by 'unless'.
305   BoundNodesTreeBuilder Discard(*Builder);
306   return !InnerMatchers[0].matches(DynNode, Finder, &Discard);
307 }
308 
309 bool AllOfVariadicOperator(const DynTypedNode &DynNode, ASTMatchFinder *Finder,
310                            BoundNodesTreeBuilder *Builder,
311                            ArrayRef<DynTypedMatcher> InnerMatchers) {
312   // allOf leads to one matcher for each alternative in the first
313   // matcher combined with each alternative in the second matcher.
314   // Thus, we can reuse the same Builder.
315   for (const DynTypedMatcher &InnerMatcher : InnerMatchers) {
316     if (!InnerMatcher.matchesNoKindCheck(DynNode, Finder, Builder))
317       return false;
318   }
319   return true;
320 }
321 
322 bool EachOfVariadicOperator(const DynTypedNode &DynNode, ASTMatchFinder *Finder,
323                             BoundNodesTreeBuilder *Builder,
324                             ArrayRef<DynTypedMatcher> InnerMatchers) {
325   BoundNodesTreeBuilder Result;
326   bool Matched = false;
327   for (const DynTypedMatcher &InnerMatcher : InnerMatchers) {
328     BoundNodesTreeBuilder BuilderInner(*Builder);
329     if (InnerMatcher.matches(DynNode, Finder, &BuilderInner)) {
330       Matched = true;
331       Result.addMatch(BuilderInner);
332     }
333   }
334   *Builder = std::move(Result);
335   return Matched;
336 }
337 
338 bool AnyOfVariadicOperator(const DynTypedNode &DynNode, ASTMatchFinder *Finder,
339                            BoundNodesTreeBuilder *Builder,
340                            ArrayRef<DynTypedMatcher> InnerMatchers) {
341   for (const DynTypedMatcher &InnerMatcher : InnerMatchers) {
342     BoundNodesTreeBuilder Result = *Builder;
343     if (InnerMatcher.matches(DynNode, Finder, &Result)) {
344       *Builder = std::move(Result);
345       return true;
346     }
347   }
348   return false;
349 }
350 
351 bool OptionallyVariadicOperator(const DynTypedNode &DynNode,
352                                 ASTMatchFinder *Finder,
353                                 BoundNodesTreeBuilder *Builder,
354                                 ArrayRef<DynTypedMatcher> InnerMatchers) {
355   BoundNodesTreeBuilder Result;
356   for (const DynTypedMatcher &InnerMatcher : InnerMatchers) {
357     BoundNodesTreeBuilder BuilderInner(*Builder);
358     if (InnerMatcher.matches(DynNode, Finder, &BuilderInner))
359       Result.addMatch(BuilderInner);
360   }
361   *Builder = std::move(Result);
362   return true;
363 }
364 
365 inline static
366 std::vector<std::string> vectorFromRefs(ArrayRef<const StringRef *> NameRefs) {
367   std::vector<std::string> Names;
368   for (auto *Name : NameRefs)
369     Names.emplace_back(*Name);
370   return Names;
371 }
372 
373 Matcher<NamedDecl> hasAnyNameFunc(ArrayRef<const StringRef *> NameRefs) {
374   std::vector<std::string> Names = vectorFromRefs(NameRefs);
375   return internal::Matcher<NamedDecl>(new internal::HasNameMatcher(Names));
376 }
377 
378 Matcher<ObjCMessageExpr> hasAnySelectorFunc(
379     ArrayRef<const StringRef *> NameRefs) {
380   return hasAnySelectorMatcher(vectorFromRefs(NameRefs));
381 }
382 
383 HasNameMatcher::HasNameMatcher(std::vector<std::string> N)
384     : UseUnqualifiedMatch(std::all_of(
385           N.begin(), N.end(),
386           [](StringRef Name) { return Name.find("::") == Name.npos; })),
387       Names(std::move(N)) {
388 #ifndef NDEBUG
389   for (StringRef Name : Names)
390     assert(!Name.empty());
391 #endif
392 }
393 
394 static bool consumeNameSuffix(StringRef &FullName, StringRef Suffix) {
395   StringRef Name = FullName;
396   if (!Name.endswith(Suffix))
397     return false;
398   Name = Name.drop_back(Suffix.size());
399   if (!Name.empty()) {
400     if (!Name.endswith("::"))
401       return false;
402     Name = Name.drop_back(2);
403   }
404   FullName = Name;
405   return true;
406 }
407 
408 static StringRef getNodeName(const NamedDecl &Node,
409                              llvm::SmallString<128> &Scratch) {
410   // Simple name.
411   if (Node.getIdentifier())
412     return Node.getName();
413 
414   if (Node.getDeclName()) {
415     // Name needs to be constructed.
416     Scratch.clear();
417     llvm::raw_svector_ostream OS(Scratch);
418     Node.printName(OS);
419     return OS.str();
420   }
421 
422   return "(anonymous)";
423 }
424 
425 static StringRef getNodeName(const RecordDecl &Node,
426                              llvm::SmallString<128> &Scratch) {
427   if (Node.getIdentifier()) {
428     return Node.getName();
429   }
430   Scratch.clear();
431   return ("(anonymous " + Node.getKindName() + ")").toStringRef(Scratch);
432 }
433 
434 static StringRef getNodeName(const NamespaceDecl &Node,
435                              llvm::SmallString<128> &Scratch) {
436   return Node.isAnonymousNamespace() ? "(anonymous namespace)" : Node.getName();
437 }
438 
439 namespace {
440 
441 class PatternSet {
442 public:
443   PatternSet(ArrayRef<std::string> Names) {
444     for (StringRef Name : Names)
445       Patterns.push_back({Name, Name.startswith("::")});
446   }
447 
448   /// Consumes the name suffix from each pattern in the set and removes the ones
449   /// that didn't match.
450   /// Return true if there are still any patterns left.
451   bool consumeNameSuffix(StringRef NodeName, bool CanSkip) {
452     for (size_t I = 0; I < Patterns.size();) {
453       if (::clang::ast_matchers::internal::consumeNameSuffix(Patterns[I].P,
454                                                              NodeName) ||
455           CanSkip) {
456         ++I;
457       } else {
458         Patterns.erase(Patterns.begin() + I);
459       }
460     }
461     return !Patterns.empty();
462   }
463 
464   /// Check if any of the patterns are a match.
465   /// A match will be a pattern that was fully consumed, that also matches the
466   /// 'fully qualified' requirement.
467   bool foundMatch(bool AllowFullyQualified) const {
468     for (auto& P: Patterns)
469       if (P.P.empty() && (AllowFullyQualified || !P.IsFullyQualified))
470         return true;
471     return false;
472   }
473 
474 private:
475   struct Pattern {
476     StringRef P;
477     bool IsFullyQualified;
478   };
479 
480   llvm::SmallVector<Pattern, 8> Patterns;
481 };
482 
483 } // namespace
484 
485 bool HasNameMatcher::matchesNodeUnqualified(const NamedDecl &Node) const {
486   assert(UseUnqualifiedMatch);
487   llvm::SmallString<128> Scratch;
488   StringRef NodeName = getNodeName(Node, Scratch);
489   return llvm::any_of(Names, [&](StringRef Name) {
490     return consumeNameSuffix(Name, NodeName) && Name.empty();
491   });
492 }
493 
494 bool HasNameMatcher::matchesNodeFullFast(const NamedDecl &Node) const {
495   PatternSet Patterns(Names);
496   llvm::SmallString<128> Scratch;
497 
498   // This function is copied and adapted from NamedDecl::printQualifiedName()
499   // By matching each part individually we optimize in a couple of ways:
500   //  - We can exit early on the first failure.
501   //  - We can skip inline/anonymous namespaces without another pass.
502   //  - We print one name at a time, reducing the chance of overflowing the
503   //    inlined space of the SmallString.
504 
505   // First, match the name.
506   if (!Patterns.consumeNameSuffix(getNodeName(Node, Scratch),
507                                   /*CanSkip=*/false))
508     return false;
509 
510   // Try to match each declaration context.
511   // We are allowed to skip anonymous and inline namespaces if they don't match.
512   const DeclContext *Ctx = Node.getDeclContext();
513 
514   if (Ctx->isFunctionOrMethod())
515     return Patterns.foundMatch(/*AllowFullyQualified=*/false);
516 
517   for (; Ctx && isa<NamedDecl>(Ctx); Ctx = Ctx->getParent()) {
518     if (Patterns.foundMatch(/*AllowFullyQualified=*/false))
519       return true;
520 
521     if (const auto *ND = dyn_cast<NamespaceDecl>(Ctx)) {
522       // If it matches (or we can skip it), continue.
523       if (Patterns.consumeNameSuffix(getNodeName(*ND, Scratch),
524                                      /*CanSkip=*/ND->isAnonymousNamespace() ||
525                                          ND->isInline()))
526         continue;
527       return false;
528     }
529     if (const auto *RD = dyn_cast<RecordDecl>(Ctx)) {
530       if (!isa<ClassTemplateSpecializationDecl>(Ctx)) {
531         if (Patterns.consumeNameSuffix(getNodeName(*RD, Scratch),
532                                        /*CanSkip=*/false))
533           continue;
534 
535         return false;
536       }
537     }
538 
539     // We don't know how to deal with this DeclContext.
540     // Fallback to the slow version of the code.
541     return matchesNodeFullSlow(Node);
542   }
543 
544   return Patterns.foundMatch(/*AllowFullyQualified=*/true);
545 }
546 
547 bool HasNameMatcher::matchesNodeFullSlow(const NamedDecl &Node) const {
548   const bool SkipUnwrittenCases[] = {false, true};
549   for (bool SkipUnwritten : SkipUnwrittenCases) {
550     llvm::SmallString<128> NodeName = StringRef("::");
551     llvm::raw_svector_ostream OS(NodeName);
552 
553     if (SkipUnwritten) {
554       PrintingPolicy Policy = Node.getASTContext().getPrintingPolicy();
555       Policy.SuppressUnwrittenScope = true;
556       Node.printQualifiedName(OS, Policy);
557     } else {
558       Node.printQualifiedName(OS);
559     }
560 
561     const StringRef FullName = OS.str();
562 
563     for (const StringRef Pattern : Names) {
564       if (Pattern.startswith("::")) {
565         if (FullName == Pattern)
566           return true;
567       } else if (FullName.endswith(Pattern) &&
568                  FullName.drop_back(Pattern.size()).endswith("::")) {
569         return true;
570       }
571     }
572   }
573 
574   return false;
575 }
576 
577 bool HasNameMatcher::matchesNode(const NamedDecl &Node) const {
578   assert(matchesNodeFullFast(Node) == matchesNodeFullSlow(Node));
579   if (UseUnqualifiedMatch) {
580     assert(matchesNodeUnqualified(Node) == matchesNodeFullFast(Node));
581     return matchesNodeUnqualified(Node);
582   }
583   return matchesNodeFullFast(Node);
584 }
585 
586 // Checks whether \p Loc points to a token with source text of \p TokenText.
587 static bool isTokenAtLoc(const SourceManager &SM, const LangOptions &LangOpts,
588                          StringRef Text, SourceLocation Loc) {
589   llvm::SmallString<16> Buffer;
590   bool Invalid = false;
591   // Since `Loc` may point into an expansion buffer, which has no corresponding
592   // source, we need to look at the spelling location to read the actual source.
593   StringRef TokenText = Lexer::getSpelling(SM.getSpellingLoc(Loc), Buffer, SM,
594                                            LangOpts, &Invalid);
595   return !Invalid && Text == TokenText;
596 }
597 
598 llvm::Optional<SourceLocation>
599 getExpansionLocOfMacro(StringRef MacroName, SourceLocation Loc,
600                        const ASTContext &Context) {
601   auto &SM = Context.getSourceManager();
602   const LangOptions &LangOpts = Context.getLangOpts();
603   while (Loc.isMacroID()) {
604     SrcMgr::ExpansionInfo Expansion =
605         SM.getSLocEntry(SM.getFileID(Loc)).getExpansion();
606     if (Expansion.isMacroArgExpansion())
607       // Check macro argument for an expansion of the given macro. For example,
608       // `F(G(3))`, where `MacroName` is `G`.
609       if (llvm::Optional<SourceLocation> ArgLoc = getExpansionLocOfMacro(
610               MacroName, Expansion.getSpellingLoc(), Context))
611         return ArgLoc;
612     Loc = Expansion.getExpansionLocStart();
613     if (isTokenAtLoc(SM, LangOpts, MacroName, Loc))
614       return Loc;
615   }
616   return llvm::None;
617 }
618 
619 } // end namespace internal
620 
621 const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAutoreleasePoolStmt>
622     autoreleasePoolStmt;
623 const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl>
624     translationUnitDecl;
625 const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl> typedefDecl;
626 const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl>
627     typedefNameDecl;
628 const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl> typeAliasDecl;
629 const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl>
630     typeAliasTemplateDecl;
631 const internal::VariadicAllOfMatcher<Decl> decl;
632 const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl>
633     linkageSpecDecl;
634 const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl;
635 const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl;
636 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl;
637 const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl>
638     namespaceAliasDecl;
639 const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl;
640 const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl> cxxRecordDecl;
641 const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl>
642     classTemplateDecl;
643 const internal::VariadicDynCastAllOfMatcher<Decl,
644                                             ClassTemplateSpecializationDecl>
645     classTemplateSpecializationDecl;
646 const internal::VariadicDynCastAllOfMatcher<
647     Decl, ClassTemplatePartialSpecializationDecl>
648     classTemplatePartialSpecializationDecl;
649 const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl>
650     declaratorDecl;
651 const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl> parmVarDecl;
652 const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl>
653     accessSpecDecl;
654 const internal::VariadicAllOfMatcher<CXXCtorInitializer> cxxCtorInitializer;
655 const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument;
656 const internal::VariadicAllOfMatcher<TemplateName> templateName;
657 const internal::VariadicDynCastAllOfMatcher<Decl, NonTypeTemplateParmDecl>
658     nonTypeTemplateParmDecl;
659 const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl>
660     templateTypeParmDecl;
661 const internal::VariadicAllOfMatcher<QualType> qualType;
662 const internal::VariadicAllOfMatcher<Type> type;
663 const internal::VariadicAllOfMatcher<TypeLoc> typeLoc;
664 const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryExprOrTypeTraitExpr>
665     unaryExprOrTypeTraitExpr;
666 const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl;
667 const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl>
668     cxxConstructorDecl;
669 const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl>
670     cxxDestructorDecl;
671 const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl;
672 const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl>
673     enumConstantDecl;
674 const internal::VariadicDynCastAllOfMatcher<Decl, TagDecl> tagDecl;
675 const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> cxxMethodDecl;
676 const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl>
677     cxxConversionDecl;
678 const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl;
679 const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl;
680 const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl>
681     indirectFieldDecl;
682 const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl;
683 const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl>
684     functionTemplateDecl;
685 const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl;
686 const internal::VariadicAllOfMatcher<Stmt> stmt;
687 const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt;
688 const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr;
689 const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr>
690     unresolvedMemberExpr;
691 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDependentScopeMemberExpr>
692     cxxDependentScopeMemberExpr;
693 const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr;
694 const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr;
695 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr>
696     cxxMemberCallExpr;
697 const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr>
698     objcMessageExpr;
699 const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl>
700     objcInterfaceDecl;
701 const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl>
702     objcImplementationDecl;
703 const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl>
704     objcProtocolDecl;
705 const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl>
706     objcCategoryDecl;
707 const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl>
708     objcCategoryImplDecl;
709 const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl>
710     objcMethodDecl;
711 const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl>
712     blockDecl;
713 const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl> objcIvarDecl;
714 const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl>
715     objcPropertyDecl;
716 const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt>
717     objcThrowStmt;
718 const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt> objcTryStmt;
719 const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt>
720     objcCatchStmt;
721 const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt>
722     objcFinallyStmt;
723 const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups>
724     exprWithCleanups;
725 const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr;
726 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStdInitializerListExpr>
727     cxxStdInitializerListExpr;
728 const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr>
729     implicitValueInitExpr;
730 const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr> parenListExpr;
731 const internal::VariadicDynCastAllOfMatcher<Stmt, SubstNonTypeTemplateParmExpr>
732     substNonTypeTemplateParmExpr;
733 const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl;
734 const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl>
735     usingDirectiveDecl;
736 const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr>
737     unresolvedLookupExpr;
738 const internal::VariadicDynCastAllOfMatcher<Decl, UnresolvedUsingValueDecl>
739     unresolvedUsingValueDecl;
740 const internal::VariadicDynCastAllOfMatcher<Decl, UnresolvedUsingTypenameDecl>
741     unresolvedUsingTypenameDecl;
742 const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr> constantExpr;
743 const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;
744 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr>
745     cxxConstructExpr;
746 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXUnresolvedConstructExpr>
747     cxxUnresolvedConstructExpr;
748 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> cxxThisExpr;
749 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr>
750     cxxBindTemporaryExpr;
751 const internal::VariadicDynCastAllOfMatcher<Stmt, MaterializeTemporaryExpr>
752     materializeTemporaryExpr;
753 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr;
754 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> cxxDeleteExpr;
755 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNoexceptExpr>
756     cxxNoexceptExpr;
757 const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr>
758     arraySubscriptExpr;
759 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr>
760     cxxDefaultArgExpr;
761 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr>
762     cxxOperatorCallExpr;
763 const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr;
764 const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr;
765 const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr> objcIvarRefExpr;
766 const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr;
767 const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt;
768 const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt;
769 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt>
770     cxxForRangeStmt;
771 const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt;
772 const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt;
773 const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt;
774 const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt;
775 const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt;
776 const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt;
777 const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt;
778 const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr> addrLabelExpr;
779 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt;
780 const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase;
781 const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt;
782 const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt> defaultStmt;
783 const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt;
784 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> cxxCatchStmt;
785 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt;
786 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> cxxThrowExpr;
787 const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt;
788 const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt;
789 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr>
790     cxxBoolLiteral;
791 const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral> stringLiteral;
792 const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral>
793     characterLiteral;
794 const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral>
795     integerLiteral;
796 const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral> floatLiteral;
797 const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral> imaginaryLiteral;
798 const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral>
799     userDefinedLiteral;
800 const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr>
801     compoundLiteralExpr;
802 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr>
803     cxxNullPtrLiteralExpr;
804 const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr> chooseExpr;
805 const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr> gnuNullExpr;
806 const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr;
807 const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr;
808 const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator>
809     binaryOperator;
810 const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator> unaryOperator;
811 const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator>
812     conditionalOperator;
813 const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryConditionalOperator>
814     binaryConditionalOperator;
815 const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr>
816     opaqueValueExpr;
817 const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl>
818     staticAssertDecl;
819 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr>
820     cxxReinterpretCastExpr;
821 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr>
822     cxxStaticCastExpr;
823 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr>
824     cxxDynamicCastExpr;
825 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr>
826     cxxConstCastExpr;
827 const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr>
828     cStyleCastExpr;
829 const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr>
830     explicitCastExpr;
831 const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr>
832     implicitCastExpr;
833 const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr;
834 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr>
835     cxxFunctionalCastExpr;
836 const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr>
837     cxxTemporaryObjectExpr;
838 const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr>
839     predefinedExpr;
840 const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr>
841     designatedInitExpr;
842 const internal::VariadicOperatorMatcherFunc<
843     2, std::numeric_limits<unsigned>::max()>
844     eachOf = {internal::DynTypedMatcher::VO_EachOf};
845 const internal::VariadicOperatorMatcherFunc<
846     2, std::numeric_limits<unsigned>::max()>
847     anyOf = {internal::DynTypedMatcher::VO_AnyOf};
848 const internal::VariadicOperatorMatcherFunc<
849     2, std::numeric_limits<unsigned>::max()>
850     allOf = {internal::DynTypedMatcher::VO_AllOf};
851 const internal::VariadicOperatorMatcherFunc<
852     1, std::numeric_limits<unsigned>::max()>
853     optionally = {internal::DynTypedMatcher::VO_Optionally};
854 const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef,
855                                  internal::hasAnyNameFunc>
856     hasAnyName = {};
857 const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>, StringRef,
858                                  internal::hasAnySelectorFunc>
859     hasAnySelector = {};
860 const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has = {};
861 const internal::ArgumentAdaptingMatcherFunc<internal::HasDescendantMatcher>
862     hasDescendant = {};
863 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher> forEach =
864     {};
865 const internal::ArgumentAdaptingMatcherFunc<internal::ForEachDescendantMatcher>
866     forEachDescendant = {};
867 const internal::ArgumentAdaptingMatcherFunc<
868     internal::HasParentMatcher,
869     internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
870     internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
871     hasParent = {};
872 const internal::ArgumentAdaptingMatcherFunc<
873     internal::HasAncestorMatcher,
874     internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>,
875     internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>>
876     hasAncestor = {};
877 const internal::VariadicOperatorMatcherFunc<1, 1> unless = {
878     internal::DynTypedMatcher::VO_UnaryNot};
879 const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier;
880 const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc>
881     nestedNameSpecifierLoc;
882 const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr>
883     cudaKernelCallExpr;
884 const AstTypeMatcher<BuiltinType> builtinType;
885 const AstTypeMatcher<ArrayType> arrayType;
886 const AstTypeMatcher<ComplexType> complexType;
887 const AstTypeMatcher<ConstantArrayType> constantArrayType;
888 const AstTypeMatcher<DeducedTemplateSpecializationType>
889     deducedTemplateSpecializationType;
890 const AstTypeMatcher<DependentSizedArrayType> dependentSizedArrayType;
891 const AstTypeMatcher<IncompleteArrayType> incompleteArrayType;
892 const AstTypeMatcher<VariableArrayType> variableArrayType;
893 const AstTypeMatcher<AtomicType> atomicType;
894 const AstTypeMatcher<AutoType> autoType;
895 const AstTypeMatcher<DecltypeType> decltypeType;
896 const AstTypeMatcher<FunctionType> functionType;
897 const AstTypeMatcher<FunctionProtoType> functionProtoType;
898 const AstTypeMatcher<ParenType> parenType;
899 const AstTypeMatcher<BlockPointerType> blockPointerType;
900 const AstTypeMatcher<MemberPointerType> memberPointerType;
901 const AstTypeMatcher<PointerType> pointerType;
902 const AstTypeMatcher<ObjCObjectPointerType> objcObjectPointerType;
903 const AstTypeMatcher<ReferenceType> referenceType;
904 const AstTypeMatcher<LValueReferenceType> lValueReferenceType;
905 const AstTypeMatcher<RValueReferenceType> rValueReferenceType;
906 const AstTypeMatcher<TypedefType> typedefType;
907 const AstTypeMatcher<EnumType> enumType;
908 const AstTypeMatcher<TemplateSpecializationType> templateSpecializationType;
909 const AstTypeMatcher<UnaryTransformType> unaryTransformType;
910 const AstTypeMatcher<RecordType> recordType;
911 const AstTypeMatcher<TagType> tagType;
912 const AstTypeMatcher<ElaboratedType> elaboratedType;
913 const AstTypeMatcher<SubstTemplateTypeParmType> substTemplateTypeParmType;
914 const AstTypeMatcher<TemplateTypeParmType> templateTypeParmType;
915 const AstTypeMatcher<InjectedClassNameType> injectedClassNameType;
916 const AstTypeMatcher<DecayedType> decayedType;
917 AST_TYPELOC_TRAVERSE_MATCHER_DEF(hasElementType,
918                                  AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType,
919                                                                  ComplexType));
920 AST_TYPELOC_TRAVERSE_MATCHER_DEF(hasValueType,
921                                  AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType));
922 AST_TYPELOC_TRAVERSE_MATCHER_DEF(
923     pointee,
924     AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType,
925                                     PointerType, ReferenceType));
926 
927 const internal::VariadicDynCastAllOfMatcher<Stmt, OMPExecutableDirective>
928     ompExecutableDirective;
929 const internal::VariadicDynCastAllOfMatcher<OMPClause, OMPDefaultClause>
930     ompDefaultClause;
931 const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl>
932     cxxDeductionGuideDecl;
933 
934 } // end namespace ast_matchers
935 } // end namespace clang
936