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"
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 if (
auto *
Args = Var->getTemplateArgsInfo())
58 return Args->arguments();
66 bool isTemplateSpecializationKind(
const NamedDecl *
D,
67 TemplateSpecializationKind
Kind) {
68 if (
const auto *TD = dyn_cast<T>(
D))
69 return TD->getTemplateSpecializationKind() ==
Kind;
73 bool isTemplateSpecializationKind(
const NamedDecl *
D,
74 TemplateSpecializationKind
Kind) {
75 return isTemplateSpecializationKind<FunctionDecl>(
D,
Kind) ||
76 isTemplateSpecializationKind<CXXRecordDecl>(
D,
Kind) ||
77 isTemplateSpecializationKind<VarDecl>(
D,
Kind);
82 llvm::DenseSet<const NamespaceDecl *>
83 getUsingNamespaceDirectives(
const DeclContext *DestContext,
84 SourceLocation Until) {
85 const auto &SM = DestContext->getParentASTContext().getSourceManager();
86 llvm::DenseSet<const NamespaceDecl *> VisibleNamespaceDecls;
87 for (
const auto *DC = DestContext; DC; DC = DC->getLookupParent()) {
88 for (
const auto *
D : DC->decls()) {
89 if (!SM.isWrittenInSameFile(
D->getLocation(), Until) ||
90 !SM.isBeforeInTranslationUnit(
D->getLocation(), Until))
92 if (
auto *UDD = llvm::dyn_cast<UsingDirectiveDecl>(
D))
93 VisibleNamespaceDecls.insert(
94 UDD->getNominatedNamespace()->getCanonicalDecl());
97 return VisibleNamespaceDecls;
107 const DeclContext *SourceContext,
108 llvm::function_ref<
bool(NestedNameSpecifier *)> IsVisible) {
109 std::vector<const NestedNameSpecifier *>
Parents;
110 bool ReachedNS =
false;
111 for (
const DeclContext *CurContext = SourceContext; CurContext;
112 CurContext = CurContext->getLookupParent()) {
114 if (CurContext->Encloses(DestContext))
117 NestedNameSpecifier *NNS =
nullptr;
118 if (
auto *TD = llvm::dyn_cast<TagDecl>(CurContext)) {
122 NNS = NestedNameSpecifier::Create(
Context,
nullptr,
false,
123 TD->getTypeForDecl());
124 }
else if (
auto *NSD = llvm::dyn_cast<NamespaceDecl>(CurContext)) {
126 NNS = NestedNameSpecifier::Create(
Context,
nullptr, NSD);
129 if (NSD->isAnonymousNamespace() || NSD->isInlineNamespace())
146 llvm::raw_string_ostream
OS(Result);
155 return isTemplateSpecializationKind(
D, TSK_ImplicitInstantiation);
159 return isTemplateSpecializationKind(
D, TSK_ExplicitSpecialization);
164 D->getASTContext().getSourceManager());
168 auto L =
D.getLocation();
170 return SM.getSpellingLoc(L);
171 return SM.getExpansionLoc(L);
176 llvm::raw_string_ostream
OS(QName);
177 PrintingPolicy Policy(ND.getASTContext().getLangOpts());
182 Policy.SuppressUnwrittenScope =
true;
183 ND.printQualifiedName(
OS, Policy);
185 assert(!StringRef(QName).startswith(
"::"));
190 return N.isIdentifier() && !N.getAsIdentifierInfo();
194 if (
auto *V = llvm::dyn_cast<DeclaratorDecl>(&ND))
195 return V->getQualifierLoc();
196 if (
auto *T = llvm::dyn_cast<TagDecl>(&ND))
197 return T->getQualifierLoc();
198 return NestedNameSpecifierLoc();
202 const UsingDirectiveDecl &
D) {
203 PrintingPolicy
PP(
Ctx.getLangOpts());
205 llvm::raw_string_ostream
Out(
Name);
207 if (
auto *Qual =
D.getQualifier())
208 Qual->print(
Out,
PP);
209 D.getNominatedNamespaceAsWritten()->printName(
Out);
215 llvm::raw_string_ostream
Out(
Name);
216 PrintingPolicy
PP(
Ctx.getLangOpts());
218 PP.SuppressTemplateArgsInCXXConstructors =
true;
221 if (
auto *UD = llvm::dyn_cast<UsingDirectiveDecl>(&ND)) {
222 Out <<
"using namespace ";
223 if (
auto *Qual = UD->getQualifier())
224 Qual->print(
Out,
PP);
225 UD->getNominatedNamespaceAsWritten()->printName(
Out);
231 if (isa<NamespaceDecl>(ND))
232 return "(anonymous namespace)";
233 if (
auto *Cls = llvm::dyn_cast<RecordDecl>(&ND)) {
236 return (
"(anonymous " + Cls->getKindName() +
")").str();
238 if (isa<EnumDecl>(ND))
239 return "(anonymous enum)";
240 return "(anonymous)";
245 Qualifier->print(
Out,
PP);
247 ND.getDeclName().print(
Out,
PP);
255 std::string TemplateArgs;
256 llvm::raw_string_ostream
OS(TemplateArgs);
257 PrintingPolicy Policy(ND.getASTContext().getLangOpts());
258 if (llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>>
Args =
259 getTemplateSpecializationArgLocs(ND)) {
260 printTemplateArgumentList(
OS, *
Args, Policy);
261 }
else if (
auto *Cls = llvm::dyn_cast<ClassTemplateSpecializationDecl>(&ND)) {
262 if (
const TypeSourceInfo *TSI = Cls->getTypeAsWritten()) {
266 auto STL = TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>();
267 llvm::SmallVector<TemplateArgumentLoc> ArgLocs;
268 ArgLocs.reserve(STL.getNumArgs());
269 for (
unsigned I = 0; I < STL.getNumArgs(); ++I)
270 ArgLocs.push_back(STL.getArgLoc(I));
271 printTemplateArgumentList(
OS, ArgLocs, Policy);
276 printTemplateArgumentList(
OS, Cls->getTemplateArgs().asArray(), Policy);
284 for (
const auto *
Ctx = &DC;
Ctx !=
nullptr;
Ctx =
Ctx->getParent())
285 if (
const auto *NS = dyn_cast<NamespaceDecl>(
Ctx))
286 if (!NS->isAnonymousNamespace() && !NS->isInlineNamespace())
291 static llvm::StringRef
293 return ID ?
ID->getName() :
"<<error-type>>";
298 llvm::raw_string_ostream
OS(
Name);
300 OS << (
Method.isInstanceMethod() ?
'-' :
'+') <<
'[';
303 if (
const ObjCContainerDecl *
C =
304 dyn_cast<ObjCContainerDecl>(
Method.getDeclContext()))
307 Method.getSelector().print(
OS <<
' ');
317 if (
const ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(&
C)) {
319 llvm::raw_string_ostream
OS(
Name);
320 const ObjCInterfaceDecl *Class = Category->getClassInterface();
326 if (
const ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(&
C)) {
328 llvm::raw_string_ostream
OS(
Name);
329 const ObjCInterfaceDecl *Class = CID->getClassInterface();
334 return C.getNameAsString();
338 llvm::SmallString<128> USR;
339 if (index::generateUSRForDecl(
D, USR))
345 const SourceManager &SM) {
348 llvm::SmallString<128> USR;
349 if (index::generateUSRForMacro(MacroName, MI->getDefinitionLoc(), SM, USR))
354 std::string
printType(
const QualType QT,
const DeclContext &CurContext,
355 const llvm::StringRef Placeholder) {
357 llvm::raw_string_ostream
OS(Result);
358 PrintingPolicy
PP(CurContext.getParentASTContext().getPrintingPolicy());
359 PP.SuppressTagKeyword =
true;
360 PP.SuppressUnwrittenScope =
true;
362 class PrintCB :
public PrintingCallbacks {
364 PrintCB(
const DeclContext *CurContext) : CurContext(CurContext) {}
365 virtual ~PrintCB() {}
366 virtual bool isScopeVisible(
const DeclContext *DC)
const override {
367 return DC->Encloses(CurContext);
371 const DeclContext *CurContext;
373 PrintCB PCB(&CurContext);
376 QT.print(
OS,
PP, Placeholder);
381 if (
const auto *ND = llvm::dyn_cast<NamedDecl>(&
D))
382 if (
const auto *II = ND->getIdentifier())
388 for (
const DeclContext *
D = &DC;
D;
D =
D->getParent()) {
389 if (
D->isTransparentContext() ||
D->isInlineNamespace())
391 if (
const auto *ND = llvm::dyn_cast<NamedDecl>(
D))
399 if (
const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(
D))
400 if (
const auto *TSI = CTSD->getTypeAsWritten())
401 return TSI->getType();
402 return D->getASTContext().getTypeDeclType(
D);
415 SourceLocation SearchedLocation;
418 DeducedTypeVisitor(SourceLocation SearchedLocation)
419 : SearchedLocation(SearchedLocation) {}
426 bool VisitDeclaratorDecl(DeclaratorDecl *
D) {
427 if (!
D->getTypeSourceInfo() ||
428 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc() != SearchedLocation)
431 if (
auto *AT =
D->getType()->getContainedAutoType()) {
443 bool VisitFunctionDecl(FunctionDecl *
D) {
444 if (!
D->getTypeSourceInfo())
447 auto CurLoc =
D->getReturnTypeSourceRange().getBegin();
449 if (CurLoc.isInvalid() && isa<CXXConversionDecl>(
D))
450 CurLoc =
D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
452 if (CurLoc.isInvalid())
453 CurLoc =
D->getSourceRange().getBegin();
454 if (CurLoc != SearchedLocation)
457 const AutoType *AT =
D->getReturnType()->getContainedAutoType();
458 if (AT && !AT->getDeducedType().isNull()) {
460 }
else if (
auto *DT = dyn_cast<DecltypeType>(
D->getReturnType())) {
463 if (!DT->getUnderlyingType().isNull())
465 }
else if (!
D->getReturnType().isNull()) {
474 bool VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
475 if (TL.getBeginLoc() != SearchedLocation)
482 const DecltypeType *DT = dyn_cast<DecltypeType>(TL.getTypePtr());
483 while (DT && !DT->getUnderlyingType().isNull()) {
485 DT = dyn_cast<DecltypeType>(
DeducedType.getTypePtr());
492 bool VisitParmVarDecl(ParmVarDecl *PVD) {
493 if (!PVD->getType()->isDependentType())
496 TemplateTypeParmTypeLoc
Auto =
498 if (
Auto.isNull() ||
Auto.getNameLoc() != SearchedLocation)
503 auto *Templated = llvm::dyn_cast<FunctionDecl>(PVD->getDeclContext());
506 auto *FTD = Templated->getDescribedFunctionTemplate();
509 int ParamIndex = paramIndex(*FTD, *
Auto.getDecl());
510 if (ParamIndex < 0) {
511 assert(
false &&
"auto TTP is not from enclosing function?");
516 auto *Instantiation =
520 const auto *
Args = Instantiation->getTemplateSpecializationArgs();
521 if (
Args->size() != FTD->getTemplateParameters()->size())
527 static int paramIndex(
const TemplateDecl &TD, NamedDecl &Param) {
529 for (
auto *ND : *TD.getTemplateParameters()) {
542 SourceLocation
Loc) {
545 DeducedTypeVisitor V(
Loc);
546 V.TraverseAST(ASTCtx);
547 if (V.DeducedType.isNull())
549 return V.DeducedType;
553 if (
auto QTL = TL.getAs<QualifiedTypeLoc>())
555 if (llvm::isa<PointerType, ReferenceType, ParenType>(TL.getTypePtr()))
557 if (
auto FTL = TL.getAs<FunctionTypeLoc>())
559 if (
auto TTPTL = TL.getAs<TemplateTypeParmTypeLoc>()) {
560 if (TTPTL.getTypePtr()->getDecl()->isImplicit())
566 template <
typename TemplateDeclTy>
568 NamedDecl *Only =
nullptr;
569 for (
auto *Spec : TD->specializations()) {
570 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
580 if (TemplateDecl *TD = TemplatedDecl->getDescribedTemplate()) {
581 if (
auto *CTD = llvm::dyn_cast<ClassTemplateDecl>(TD))
583 if (
auto *FTD = llvm::dyn_cast<FunctionTemplateDecl>(TD))
585 if (
auto *VTD = llvm::dyn_cast<VarTemplateDecl>(TD))
592 std::vector<const Attr *> Result;
593 if (
const auto *TL = N.get<TypeLoc>()) {
594 for (AttributedTypeLoc ATL = TL->getAs<AttributedTypeLoc>(); !ATL.isNull();
595 ATL = ATL.getModifiedLoc().getAs<AttributedTypeLoc>()) {
596 if (
const Attr *
A = ATL.getAttr())
598 assert(!ATL.getModifiedLoc().isNull());
601 if (
const auto *S = N.get<AttributedStmt>()) {
602 for (; S !=
nullptr; S = dyn_cast<AttributedStmt>(S->getSubStmt()))
603 for (
const Attr *
A : S->getAttrs())
607 if (
const auto *
D = N.get<
Decl>()) {
608 for (
const Attr *
A :
D->attrs())
616 const DeclContext *DestContext,
617 SourceLocation InsertionPoint,
618 const NamedDecl *ND) {
619 auto VisibleNamespaceDecls =
620 getUsingNamespaceDirectives(DestContext, InsertionPoint);
622 Context, DestContext, ND->getDeclContext(),
623 [&](NestedNameSpecifier *NNS) {
624 if (NNS->getKind() != NestedNameSpecifier::Namespace)
626 const auto *CanonNSD = NNS->getAsNamespace()->getCanonicalDecl();
627 return llvm::any_of(VisibleNamespaceDecls,
628 [CanonNSD](const NamespaceDecl *NSD) {
629 return NSD->getCanonicalDecl() == CanonNSD;
635 const DeclContext *DestContext,
637 llvm::ArrayRef<std::string> VisibleNamespaces) {
638 for (llvm::StringRef NS : VisibleNamespaces) {
639 assert(NS.endswith(
"::"));
643 Context, DestContext, ND->getDeclContext(),
644 [&](NestedNameSpecifier *NNS) {
645 return llvm::any_of(VisibleNamespaces, [&](llvm::StringRef Namespace) {
647 llvm::raw_string_ostream OS(NS);
648 NNS->print(OS, Context.getPrintingPolicy());
649 return OS.str() == Namespace;
657 auto *VD = llvm::dyn_cast_or_null<ValueDecl>(
D);
658 return VD && !VD->getType().isNull() && VD->getType()->isUndeducedType();
662 size_t ContextDepth = 0;
663 for (
auto *
Ctx =
D->getDeclContext();
Ctx && !
Ctx->isTranslationUnit();
665 if (++ContextDepth == MaxDepth)