1 //===--- AST.cpp - Utility AST functions  -----------------------*- 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 #include "AST.h"
10 
11 #include "SourceCode.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/ASTTypeTraits.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclBase.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/DeclarationName.h"
19 #include "clang/AST/NestedNameSpecifier.h"
20 #include "clang/AST/PrettyPrinter.h"
21 #include "clang/AST/RecursiveASTVisitor.h"
22 #include "clang/AST/Stmt.h"
23 #include "clang/AST/TemplateBase.h"
24 #include "clang/AST/TypeLoc.h"
25 #include "clang/Basic/SourceLocation.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/Basic/Specifiers.h"
28 #include "clang/Index/USRGeneration.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/Optional.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <string>
36 #include <vector>
37 
38 namespace clang {
39 namespace clangd {
40 
41 namespace {
42 llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>>
43 getTemplateSpecializationArgLocs(const NamedDecl &ND) {
44   if (auto *Func = llvm::dyn_cast<FunctionDecl>(&ND)) {
45     if (const ASTTemplateArgumentListInfo *Args =
46             Func->getTemplateSpecializationArgsAsWritten())
47       return Args->arguments();
48   } else if (auto *Cls =
49                  llvm::dyn_cast<ClassTemplatePartialSpecializationDecl>(&ND)) {
50     if (auto *Args = Cls->getTemplateArgsAsWritten())
51       return Args->arguments();
52   } else if (auto *Var =
53                  llvm::dyn_cast<VarTemplatePartialSpecializationDecl>(&ND)) {
54     if (auto *Args = Var->getTemplateArgsAsWritten())
55       return Args->arguments();
56   } else if (auto *Var = llvm::dyn_cast<VarTemplateSpecializationDecl>(&ND))
57     return Var->getTemplateArgsInfo().arguments();
58   // We return None for ClassTemplateSpecializationDecls because it does not
59   // contain TemplateArgumentLoc information.
60   return llvm::None;
61 }
62 
63 template <class T>
64 bool isTemplateSpecializationKind(const NamedDecl *D,
65                                   TemplateSpecializationKind Kind) {
66   if (const auto *TD = dyn_cast<T>(D))
67     return TD->getTemplateSpecializationKind() == Kind;
68   return false;
69 }
70 
71 bool isTemplateSpecializationKind(const NamedDecl *D,
72                                   TemplateSpecializationKind Kind) {
73   return isTemplateSpecializationKind<FunctionDecl>(D, Kind) ||
74          isTemplateSpecializationKind<CXXRecordDecl>(D, Kind) ||
75          isTemplateSpecializationKind<VarDecl>(D, Kind);
76 }
77 
78 // Store all UsingDirectiveDecls in parent contexts of DestContext, that were
79 // introduced before InsertionPoint.
80 llvm::DenseSet<const NamespaceDecl *>
81 getUsingNamespaceDirectives(const DeclContext *DestContext,
82                             SourceLocation Until) {
83   const auto &SM = DestContext->getParentASTContext().getSourceManager();
84   llvm::DenseSet<const NamespaceDecl *> VisibleNamespaceDecls;
85   for (const auto *DC = DestContext; DC; DC = DC->getLookupParent()) {
86     for (const auto *D : DC->decls()) {
87       if (!SM.isWrittenInSameFile(D->getLocation(), Until) ||
88           !SM.isBeforeInTranslationUnit(D->getLocation(), Until))
89         continue;
90       if (auto *UDD = llvm::dyn_cast<UsingDirectiveDecl>(D))
91         VisibleNamespaceDecls.insert(
92             UDD->getNominatedNamespace()->getCanonicalDecl());
93     }
94   }
95   return VisibleNamespaceDecls;
96 }
97 
98 // Goes over all parents of SourceContext until we find a common ancestor for
99 // DestContext and SourceContext. Any qualifier including and above common
100 // ancestor is redundant, therefore we stop at lowest common ancestor.
101 // In addition to that stops early whenever IsVisible returns true. This can be
102 // used to implement support for "using namespace" decls.
103 std::string
104 getQualification(ASTContext &Context, const DeclContext *DestContext,
105                  const DeclContext *SourceContext,
106                  llvm::function_ref<bool(NestedNameSpecifier *)> IsVisible) {
107   std::vector<const NestedNameSpecifier *> Parents;
108   bool ReachedNS = false;
109   for (const DeclContext *CurContext = SourceContext; CurContext;
110        CurContext = CurContext->getLookupParent()) {
111     // Stop once we reach a common ancestor.
112     if (CurContext->Encloses(DestContext))
113       break;
114 
115     NestedNameSpecifier *NNS = nullptr;
116     if (auto *TD = llvm::dyn_cast<TagDecl>(CurContext)) {
117       // There can't be any more tag parents after hitting a namespace.
118       assert(!ReachedNS);
119       (void)ReachedNS;
120       NNS = NestedNameSpecifier::Create(Context, nullptr, false,
121                                         TD->getTypeForDecl());
122     } else if (auto *NSD = llvm::dyn_cast<NamespaceDecl>(CurContext)) {
123       ReachedNS = true;
124       NNS = NestedNameSpecifier::Create(Context, nullptr, NSD);
125       // Anonymous and inline namespace names are not spelled while qualifying
126       // a name, so skip those.
127       if (NSD->isAnonymousNamespace() || NSD->isInlineNamespace())
128         continue;
129     } else {
130       // Other types of contexts cannot be spelled in code, just skip over
131       // them.
132       continue;
133     }
134     // Stop if this namespace is already visible at DestContext.
135     if (IsVisible(NNS))
136       break;
137 
138     Parents.push_back(NNS);
139   }
140 
141   // Go over name-specifiers in reverse order to create necessary qualification,
142   // since we stored inner-most parent first.
143   std::string Result;
144   llvm::raw_string_ostream OS(Result);
145   for (const auto *Parent : llvm::reverse(Parents))
146     Parent->print(OS, Context.getPrintingPolicy());
147   return OS.str();
148 }
149 
150 } // namespace
151 
152 bool isImplicitTemplateInstantiation(const NamedDecl *D) {
153   return isTemplateSpecializationKind(D, TSK_ImplicitInstantiation);
154 }
155 
156 bool isExplicitTemplateSpecialization(const NamedDecl *D) {
157   return isTemplateSpecializationKind(D, TSK_ExplicitSpecialization);
158 }
159 
160 bool isImplementationDetail(const Decl *D) {
161   return !isSpelledInSource(D->getLocation(),
162                             D->getASTContext().getSourceManager());
163 }
164 
165 SourceLocation nameLocation(const clang::Decl &D, const SourceManager &SM) {
166   auto L = D.getLocation();
167   if (isSpelledInSource(L, SM))
168     return SM.getSpellingLoc(L);
169   return SM.getExpansionLoc(L);
170 }
171 
172 std::string printQualifiedName(const NamedDecl &ND) {
173   std::string QName;
174   llvm::raw_string_ostream OS(QName);
175   PrintingPolicy Policy(ND.getASTContext().getLangOpts());
176   // Note that inline namespaces are treated as transparent scopes. This
177   // reflects the way they're most commonly used for lookup. Ideally we'd
178   // include them, but at query time it's hard to find all the inline
179   // namespaces to query: the preamble doesn't have a dedicated list.
180   Policy.SuppressUnwrittenScope = true;
181   ND.printQualifiedName(OS, Policy);
182   OS.flush();
183   assert(!StringRef(QName).startswith("::"));
184   return QName;
185 }
186 
187 static bool isAnonymous(const DeclarationName &N) {
188   return N.isIdentifier() && !N.getAsIdentifierInfo();
189 }
190 
191 NestedNameSpecifierLoc getQualifierLoc(const NamedDecl &ND) {
192   if (auto *V = llvm::dyn_cast<DeclaratorDecl>(&ND))
193     return V->getQualifierLoc();
194   if (auto *T = llvm::dyn_cast<TagDecl>(&ND))
195     return T->getQualifierLoc();
196   return NestedNameSpecifierLoc();
197 }
198 
199 std::string printUsingNamespaceName(const ASTContext &Ctx,
200                                     const UsingDirectiveDecl &D) {
201   PrintingPolicy PP(Ctx.getLangOpts());
202   std::string Name;
203   llvm::raw_string_ostream Out(Name);
204 
205   if (auto *Qual = D.getQualifier())
206     Qual->print(Out, PP);
207   D.getNominatedNamespaceAsWritten()->printName(Out);
208   return Out.str();
209 }
210 
211 std::string printName(const ASTContext &Ctx, const NamedDecl &ND) {
212   std::string Name;
213   llvm::raw_string_ostream Out(Name);
214   PrintingPolicy PP(Ctx.getLangOpts());
215   // We don't consider a class template's args part of the constructor name.
216   PP.SuppressTemplateArgsInCXXConstructors = true;
217 
218   // Handle 'using namespace'. They all have the same name - <using-directive>.
219   if (auto *UD = llvm::dyn_cast<UsingDirectiveDecl>(&ND)) {
220     Out << "using namespace ";
221     if (auto *Qual = UD->getQualifier())
222       Qual->print(Out, PP);
223     UD->getNominatedNamespaceAsWritten()->printName(Out);
224     return Out.str();
225   }
226 
227   if (isAnonymous(ND.getDeclName())) {
228     // Come up with a presentation for an anonymous entity.
229     if (isa<NamespaceDecl>(ND))
230       return "(anonymous namespace)";
231     if (auto *Cls = llvm::dyn_cast<RecordDecl>(&ND)) {
232       if (Cls->isLambda())
233         return "(lambda)";
234       return ("(anonymous " + Cls->getKindName() + ")").str();
235     }
236     if (isa<EnumDecl>(ND))
237       return "(anonymous enum)";
238     return "(anonymous)";
239   }
240 
241   // Print nested name qualifier if it was written in the source code.
242   if (auto *Qualifier = getQualifierLoc(ND).getNestedNameSpecifier())
243     Qualifier->print(Out, PP);
244   // Print the name itself.
245   ND.getDeclName().print(Out, PP);
246   // Print template arguments.
247   Out << printTemplateSpecializationArgs(ND);
248 
249   return Out.str();
250 }
251 
252 std::string printTemplateSpecializationArgs(const NamedDecl &ND) {
253   std::string TemplateArgs;
254   llvm::raw_string_ostream OS(TemplateArgs);
255   PrintingPolicy Policy(ND.getASTContext().getLangOpts());
256   if (llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>> Args =
257           getTemplateSpecializationArgLocs(ND)) {
258     printTemplateArgumentList(OS, *Args, Policy);
259   } else if (auto *Cls = llvm::dyn_cast<ClassTemplateSpecializationDecl>(&ND)) {
260     if (const TypeSourceInfo *TSI = Cls->getTypeAsWritten()) {
261       // ClassTemplateSpecializationDecls do not contain
262       // TemplateArgumentTypeLocs, they only have TemplateArgumentTypes. So we
263       // create a new argument location list from TypeSourceInfo.
264       auto STL = TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>();
265       llvm::SmallVector<TemplateArgumentLoc> ArgLocs;
266       ArgLocs.reserve(STL.getNumArgs());
267       for (unsigned I = 0; I < STL.getNumArgs(); ++I)
268         ArgLocs.push_back(STL.getArgLoc(I));
269       printTemplateArgumentList(OS, ArgLocs, Policy);
270     } else {
271       // FIXME: Fix cases when getTypeAsWritten returns null inside clang AST,
272       // e.g. friend decls. Currently we fallback to Template Arguments without
273       // location information.
274       printTemplateArgumentList(OS, Cls->getTemplateArgs().asArray(), Policy);
275     }
276   }
277   OS.flush();
278   return TemplateArgs;
279 }
280 
281 std::string printNamespaceScope(const DeclContext &DC) {
282   for (const auto *Ctx = &DC; Ctx != nullptr; Ctx = Ctx->getParent())
283     if (const auto *NS = dyn_cast<NamespaceDecl>(Ctx))
284       if (!NS->isAnonymousNamespace() && !NS->isInlineNamespace())
285         return printQualifiedName(*NS) + "::";
286   return "";
287 }
288 
289 static llvm::StringRef
290 getNameOrErrForObjCInterface(const ObjCInterfaceDecl *ID) {
291   return ID ? ID->getName() : "<<error-type>>";
292 }
293 
294 std::string printObjCMethod(const ObjCMethodDecl &Method) {
295   std::string Name;
296   llvm::raw_string_ostream OS(Name);
297 
298   OS << (Method.isInstanceMethod() ? '-' : '+') << '[';
299 
300   // Should always be true.
301   if (const ObjCContainerDecl *C =
302           dyn_cast<ObjCContainerDecl>(Method.getDeclContext()))
303     OS << printObjCContainer(*C);
304 
305   Method.getSelector().print(OS << ' ');
306   if (Method.isVariadic())
307     OS << ", ...";
308 
309   OS << ']';
310   OS.flush();
311   return Name;
312 }
313 
314 std::string printObjCContainer(const ObjCContainerDecl &C) {
315   if (const ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(&C)) {
316     std::string Name;
317     llvm::raw_string_ostream OS(Name);
318     const ObjCInterfaceDecl *Class = Category->getClassInterface();
319     OS << getNameOrErrForObjCInterface(Class) << '(' << Category->getName()
320        << ')';
321     OS.flush();
322     return Name;
323   }
324   if (const ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(&C)) {
325     std::string Name;
326     llvm::raw_string_ostream OS(Name);
327     const ObjCInterfaceDecl *Class = CID->getClassInterface();
328     OS << getNameOrErrForObjCInterface(Class) << '(' << CID->getName() << ')';
329     OS.flush();
330     return Name;
331   }
332   return C.getNameAsString();
333 }
334 
335 SymbolID getSymbolID(const Decl *D) {
336   llvm::SmallString<128> USR;
337   if (index::generateUSRForDecl(D, USR))
338     return {};
339   return SymbolID(USR);
340 }
341 
342 SymbolID getSymbolID(const llvm::StringRef MacroName, const MacroInfo *MI,
343                      const SourceManager &SM) {
344   if (MI == nullptr)
345     return {};
346   llvm::SmallString<128> USR;
347   if (index::generateUSRForMacro(MacroName, MI->getDefinitionLoc(), SM, USR))
348     return {};
349   return SymbolID(USR);
350 }
351 
352 std::string printType(const QualType QT, const DeclContext &CurContext) {
353   std::string Result;
354   llvm::raw_string_ostream OS(Result);
355   PrintingPolicy PP(CurContext.getParentASTContext().getPrintingPolicy());
356   PP.SuppressTagKeyword = true;
357   PP.SuppressUnwrittenScope = true;
358 
359   class PrintCB : public PrintingCallbacks {
360   public:
361     PrintCB(const DeclContext *CurContext) : CurContext(CurContext) {}
362     virtual ~PrintCB() {}
363     virtual bool isScopeVisible(const DeclContext *DC) const override {
364       return DC->Encloses(CurContext);
365     }
366 
367   private:
368     const DeclContext *CurContext;
369   };
370   PrintCB PCB(&CurContext);
371   PP.Callbacks = &PCB;
372 
373   QT.print(OS, PP);
374   return OS.str();
375 }
376 
377 bool hasReservedName(const Decl &D) {
378   if (const auto *ND = llvm::dyn_cast<NamedDecl>(&D))
379     if (const auto *II = ND->getIdentifier())
380       return isReservedName(II->getName());
381   return false;
382 }
383 
384 bool hasReservedScope(const DeclContext &DC) {
385   for (const DeclContext *D = &DC; D; D = D->getParent()) {
386     if (D->isTransparentContext() || D->isInlineNamespace())
387       continue;
388     if (const auto *ND = llvm::dyn_cast<NamedDecl>(D))
389       if (hasReservedName(*ND))
390         return true;
391   }
392   return false;
393 }
394 
395 QualType declaredType(const TypeDecl *D) {
396   if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D))
397     if (const auto *TSI = CTSD->getTypeAsWritten())
398       return TSI->getType();
399   return D->getASTContext().getTypeDeclType(D);
400 }
401 
402 namespace {
403 /// Computes the deduced type at a given location by visiting the relevant
404 /// nodes. We use this to display the actual type when hovering over an "auto"
405 /// keyword or "decltype()" expression.
406 /// FIXME: This could have been a lot simpler by visiting AutoTypeLocs but it
407 /// seems that the AutoTypeLocs that can be visited along with their AutoType do
408 /// not have the deduced type set. Instead, we have to go to the appropriate
409 /// DeclaratorDecl/FunctionDecl and work our back to the AutoType that does have
410 /// a deduced type set. The AST should be improved to simplify this scenario.
411 class DeducedTypeVisitor : public RecursiveASTVisitor<DeducedTypeVisitor> {
412   SourceLocation SearchedLocation;
413 
414 public:
415   DeducedTypeVisitor(SourceLocation SearchedLocation)
416       : SearchedLocation(SearchedLocation) {}
417 
418   // Handle auto initializers:
419   //- auto i = 1;
420   //- decltype(auto) i = 1;
421   //- auto& i = 1;
422   //- auto* i = &a;
423   bool VisitDeclaratorDecl(DeclaratorDecl *D) {
424     if (!D->getTypeSourceInfo() ||
425         D->getTypeSourceInfo()->getTypeLoc().getBeginLoc() != SearchedLocation)
426       return true;
427 
428     if (auto *AT = D->getType()->getContainedAutoType()) {
429       DeducedType = AT->desugar();
430     }
431     return true;
432   }
433 
434   // Handle auto return types:
435   //- auto foo() {}
436   //- auto& foo() {}
437   //- auto foo() -> int {}
438   //- auto foo() -> decltype(1+1) {}
439   //- operator auto() const { return 10; }
440   bool VisitFunctionDecl(FunctionDecl *D) {
441     if (!D->getTypeSourceInfo())
442       return true;
443     // Loc of auto in return type (c++14).
444     auto CurLoc = D->getReturnTypeSourceRange().getBegin();
445     // Loc of "auto" in operator auto()
446     if (CurLoc.isInvalid() && isa<CXXConversionDecl>(D))
447       CurLoc = D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
448     // Loc of "auto" in function with trailing return type (c++11).
449     if (CurLoc.isInvalid())
450       CurLoc = D->getSourceRange().getBegin();
451     if (CurLoc != SearchedLocation)
452       return true;
453 
454     const AutoType *AT = D->getReturnType()->getContainedAutoType();
455     if (AT && !AT->getDeducedType().isNull()) {
456       DeducedType = AT->getDeducedType();
457     } else if (auto *DT = dyn_cast<DecltypeType>(D->getReturnType())) {
458       // auto in a trailing return type just points to a DecltypeType and
459       // getContainedAutoType does not unwrap it.
460       if (!DT->getUnderlyingType().isNull())
461         DeducedType = DT->getUnderlyingType();
462     } else if (!D->getReturnType().isNull()) {
463       DeducedType = D->getReturnType();
464     }
465     return true;
466   }
467 
468   // Handle non-auto decltype, e.g.:
469   // - auto foo() -> decltype(expr) {}
470   // - decltype(expr);
471   bool VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
472     if (TL.getBeginLoc() != SearchedLocation)
473       return true;
474 
475     // A DecltypeType's underlying type can be another DecltypeType! E.g.
476     //  int I = 0;
477     //  decltype(I) J = I;
478     //  decltype(J) K = J;
479     const DecltypeType *DT = dyn_cast<DecltypeType>(TL.getTypePtr());
480     while (DT && !DT->getUnderlyingType().isNull()) {
481       DeducedType = DT->getUnderlyingType();
482       DT = dyn_cast<DecltypeType>(DeducedType.getTypePtr());
483     }
484     return true;
485   }
486 
487   // Handle functions/lambdas with `auto` typed parameters.
488   // We'll examine visible specializations and see if they yield a unique type.
489   bool VisitParmVarDecl(ParmVarDecl *PVD) {
490     if (!PVD->getType()->isDependentType())
491       return true;
492     // 'auto' here does not name an AutoType, but an implicit template param.
493     TemplateTypeParmTypeLoc Auto =
494         findContainedAutoTTPLoc(PVD->getTypeSourceInfo()->getTypeLoc());
495     if (Auto.isNull() || Auto.getNameLoc() != SearchedLocation)
496       return true;
497     // We expect the TTP to be attached to this function template.
498     // Find the template and the param index.
499     auto *FD = llvm::dyn_cast<FunctionDecl>(PVD->getDeclContext());
500     if (!FD)
501       return true;
502     auto *FTD = FD->getDescribedFunctionTemplate();
503     if (!FTD)
504       return true;
505     int ParamIndex = paramIndex(*FTD, *Auto.getDecl());
506     if (ParamIndex < 0) {
507       assert(false && "auto TTP is not from enclosing function?");
508       return true;
509     }
510 
511     // Now determine the unique type arg among the implicit specializations.
512     const ASTContext &Ctx = PVD->getASTContext();
513     QualType UniqueType;
514     CanQualType CanUniqueType;
515     for (const FunctionDecl *Spec : FTD->specializations()) {
516       // Meaning `auto` is a bit overloaded if the function is specialized.
517       if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
518         return true;
519       // Find the type for this specialization.
520       const auto *Args = Spec->getTemplateSpecializationArgs();
521       if (Args->size() != FTD->getTemplateParameters()->size())
522         continue; // no weird variadic stuff
523       QualType SpecType = Args->get(ParamIndex).getAsType();
524       if (SpecType.isNull())
525         continue;
526 
527       // Deduced types need only be *canonically* equal.
528       CanQualType CanSpecType = Ctx.getCanonicalType(SpecType);
529       if (CanUniqueType.isNull()) {
530         CanUniqueType = CanSpecType;
531         UniqueType = SpecType;
532         continue;
533       }
534       if (CanUniqueType != CanSpecType)
535         return true; // deduced type is not unique
536     }
537     DeducedType = UniqueType;
538     return true;
539   }
540 
541   // Find the abbreviated-function-template `auto` within a type.
542   // Similar to getContainedAutoTypeLoc, but these `auto`s are
543   // TemplateTypeParmTypes for implicit TTPs, instead of AutoTypes.
544   // Also we don't look very hard, just stripping const, references, pointers.
545   // FIXME: handle more types: vector<auto>?
546   static TemplateTypeParmTypeLoc findContainedAutoTTPLoc(TypeLoc TL) {
547     if (auto QTL = TL.getAs<QualifiedTypeLoc>())
548       return findContainedAutoTTPLoc(QTL.getUnqualifiedLoc());
549     if (llvm::isa<PointerType, ReferenceType>(TL.getTypePtr()))
550       return findContainedAutoTTPLoc(TL.getNextTypeLoc());
551     if (auto TTPTL = TL.getAs<TemplateTypeParmTypeLoc>()) {
552       if (TTPTL.getTypePtr()->getDecl()->isImplicit())
553         return TTPTL;
554     }
555     return {};
556   }
557 
558   static int paramIndex(const TemplateDecl &TD, NamedDecl &Param) {
559     unsigned I = 0;
560     for (auto *ND : *TD.getTemplateParameters()) {
561       if (&Param == ND)
562         return I;
563       ++I;
564     }
565     return -1;
566   }
567 
568   QualType DeducedType;
569 };
570 } // namespace
571 
572 llvm::Optional<QualType> getDeducedType(ASTContext &ASTCtx,
573                                         SourceLocation Loc) {
574   if (!Loc.isValid())
575     return {};
576   DeducedTypeVisitor V(Loc);
577   V.TraverseAST(ASTCtx);
578   if (V.DeducedType.isNull())
579     return llvm::None;
580   return V.DeducedType;
581 }
582 
583 std::vector<const Attr *> getAttributes(const DynTypedNode &N) {
584   std::vector<const Attr *> Result;
585   if (const auto *TL = N.get<TypeLoc>()) {
586     for (AttributedTypeLoc ATL = TL->getAs<AttributedTypeLoc>(); !ATL.isNull();
587          ATL = ATL.getModifiedLoc().getAs<AttributedTypeLoc>()) {
588       if (const Attr *A = ATL.getAttr())
589         Result.push_back(A);
590       assert(!ATL.getModifiedLoc().isNull());
591     }
592   }
593   if (const auto *S = N.get<AttributedStmt>()) {
594     for (; S != nullptr; S = dyn_cast<AttributedStmt>(S->getSubStmt()))
595       for (const Attr *A : S->getAttrs())
596         if (A)
597           Result.push_back(A);
598   }
599   if (const auto *D = N.get<Decl>()) {
600     for (const Attr *A : D->attrs())
601       if (A)
602         Result.push_back(A);
603   }
604   return Result;
605 }
606 
607 std::string getQualification(ASTContext &Context,
608                              const DeclContext *DestContext,
609                              SourceLocation InsertionPoint,
610                              const NamedDecl *ND) {
611   auto VisibleNamespaceDecls =
612       getUsingNamespaceDirectives(DestContext, InsertionPoint);
613   return getQualification(
614       Context, DestContext, ND->getDeclContext(),
615       [&](NestedNameSpecifier *NNS) {
616         if (NNS->getKind() != NestedNameSpecifier::Namespace)
617           return false;
618         const auto *CanonNSD = NNS->getAsNamespace()->getCanonicalDecl();
619         return llvm::any_of(VisibleNamespaceDecls,
620                             [CanonNSD](const NamespaceDecl *NSD) {
621                               return NSD->getCanonicalDecl() == CanonNSD;
622                             });
623       });
624 }
625 
626 std::string getQualification(ASTContext &Context,
627                              const DeclContext *DestContext,
628                              const NamedDecl *ND,
629                              llvm::ArrayRef<std::string> VisibleNamespaces) {
630   for (llvm::StringRef NS : VisibleNamespaces) {
631     assert(NS.endswith("::"));
632     (void)NS;
633   }
634   return getQualification(
635       Context, DestContext, ND->getDeclContext(),
636       [&](NestedNameSpecifier *NNS) {
637         return llvm::any_of(VisibleNamespaces, [&](llvm::StringRef Namespace) {
638           std::string NS;
639           llvm::raw_string_ostream OS(NS);
640           NNS->print(OS, Context.getPrintingPolicy());
641           return OS.str() == Namespace;
642         });
643       });
644 }
645 
646 bool hasUnstableLinkage(const Decl *D) {
647   // Linkage of a ValueDecl depends on the type.
648   // If that's not deduced yet, deducing it may change the linkage.
649   auto *VD = llvm::dyn_cast_or_null<ValueDecl>(D);
650   return VD && !VD->getType().isNull() && VD->getType()->isUndeducedType();
651 }
652 
653 bool isDeeplyNested(const Decl *D, unsigned MaxDepth) {
654   size_t ContextDepth = 0;
655   for (auto *Ctx = D->getDeclContext(); Ctx && !Ctx->isTranslationUnit();
656        Ctx = Ctx->getParent()) {
657     if (++ContextDepth == MaxDepth)
658       return true;
659   }
660   return false;
661 }
662 } // namespace clangd
663 } // namespace clang
664