1 //===--- AST.cpp - Utility AST functions -----------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
11 #include "SourceCode.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/AST/DeclTemplate.h"
15 #include "clang/AST/DeclarationName.h"
16 #include "clang/AST/NestedNameSpecifier.h"
17 #include "clang/AST/PrettyPrinter.h"
18 #include "clang/AST/TemplateBase.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Basic/Specifiers.h"
22 #include "clang/Index/USRGeneration.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/Support/Casting.h"
25 #include "llvm/Support/ScopedPrinter.h"
26 #include "llvm/Support/raw_ostream.h"
32 llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>>
33 getTemplateSpecializationArgLocs(const NamedDecl &ND) {
34 if (auto *Func = llvm::dyn_cast<FunctionDecl>(&ND)) {
35 if (const ASTTemplateArgumentListInfo *Args =
36 Func->getTemplateSpecializationArgsAsWritten())
37 return Args->arguments();
38 } else if (auto *Cls =
39 llvm::dyn_cast<ClassTemplatePartialSpecializationDecl>(&ND)) {
40 if (auto *Args = Cls->getTemplateArgsAsWritten())
41 return Args->arguments();
42 } else if (auto *Var =
43 llvm::dyn_cast<VarTemplatePartialSpecializationDecl>(&ND)) {
44 if (auto *Args = Var->getTemplateArgsAsWritten())
45 return Args->arguments();
46 } else if (auto *Var = llvm::dyn_cast<VarTemplateSpecializationDecl>(&ND))
47 return Var->getTemplateArgsInfo().arguments();
48 // We return None for ClassTemplateSpecializationDecls because it does not
49 // contain TemplateArgumentLoc information.
54 bool isTemplateSpecializationKind(const NamedDecl *D,
55 TemplateSpecializationKind Kind) {
56 if (const auto *TD = dyn_cast<T>(D))
57 return TD->getTemplateSpecializationKind() == Kind;
61 bool isTemplateSpecializationKind(const NamedDecl *D,
62 TemplateSpecializationKind Kind) {
63 return isTemplateSpecializationKind<FunctionDecl>(D, Kind) ||
64 isTemplateSpecializationKind<CXXRecordDecl>(D, Kind) ||
65 isTemplateSpecializationKind<VarDecl>(D, Kind);
70 bool isImplicitTemplateInstantiation(const NamedDecl *D) {
71 return isTemplateSpecializationKind(D, TSK_ImplicitInstantiation);
74 bool isExplicitTemplateSpecialization(const NamedDecl *D) {
75 return isTemplateSpecializationKind(D, TSK_ExplicitSpecialization);
78 bool isImplementationDetail(const Decl *D) {
79 return !isSpelledInSource(D->getLocation(),
80 D->getASTContext().getSourceManager());
83 SourceLocation findName(const clang::Decl *D) {
84 return D->getLocation();
87 std::string printQualifiedName(const NamedDecl &ND) {
89 llvm::raw_string_ostream OS(QName);
90 PrintingPolicy Policy(ND.getASTContext().getLangOpts());
91 // Note that inline namespaces are treated as transparent scopes. This
92 // reflects the way they're most commonly used for lookup. Ideally we'd
93 // include them, but at query time it's hard to find all the inline
94 // namespaces to query: the preamble doesn't have a dedicated list.
95 Policy.SuppressUnwrittenScope = true;
96 ND.printQualifiedName(OS, Policy);
98 assert(!StringRef(QName).startswith("::"));
102 static bool isAnonymous(const DeclarationName &N) {
103 return N.isIdentifier() && !N.getAsIdentifierInfo();
106 /// Returns a nested name specifier of \p ND if it was present in the source,
108 /// void ns::something::foo() -> returns 'ns::something'
109 /// void foo() -> returns null
110 static NestedNameSpecifier *getQualifier(const NamedDecl &ND) {
111 if (auto *V = llvm::dyn_cast<DeclaratorDecl>(&ND))
112 return V->getQualifier();
113 if (auto *T = llvm::dyn_cast<TagDecl>(&ND))
114 return T->getQualifier();
118 std::string printName(const ASTContext &Ctx, const NamedDecl &ND) {
120 llvm::raw_string_ostream Out(Name);
121 PrintingPolicy PP(Ctx.getLangOpts());
123 // Handle 'using namespace'. They all have the same name - <using-directive>.
124 if (auto *UD = llvm::dyn_cast<UsingDirectiveDecl>(&ND)) {
125 Out << "using namespace ";
126 if (auto *Qual = UD->getQualifier())
127 Qual->print(Out, PP);
128 UD->getNominatedNamespaceAsWritten()->printName(Out);
132 if (isAnonymous(ND.getDeclName())) {
133 // Come up with a presentation for an anonymous entity.
134 if (isa<NamespaceDecl>(ND))
135 return "(anonymous namespace)";
136 if (auto *Cls = llvm::dyn_cast<RecordDecl>(&ND))
137 return ("(anonymous " + Cls->getKindName() + ")").str();
138 if (isa<EnumDecl>(ND))
139 return "(anonymous enum)";
140 return "(anonymous)";
143 // Print nested name qualifier if it was written in the source code.
144 if (auto *Qualifier = getQualifier(ND))
145 Qualifier->print(Out, PP);
146 // Print the name itself.
147 ND.getDeclName().print(Out, PP);
148 // Print template arguments.
149 Out << printTemplateSpecializationArgs(ND);
154 std::string printTemplateSpecializationArgs(const NamedDecl &ND) {
155 std::string TemplateArgs;
156 llvm::raw_string_ostream OS(TemplateArgs);
157 PrintingPolicy Policy(ND.getASTContext().getLangOpts());
158 if (llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>> Args =
159 getTemplateSpecializationArgLocs(ND)) {
160 printTemplateArgumentList(OS, *Args, Policy);
161 } else if (auto *Cls = llvm::dyn_cast<ClassTemplateSpecializationDecl>(&ND)) {
162 if (const TypeSourceInfo *TSI = Cls->getTypeAsWritten()) {
163 // ClassTemplateSpecializationDecls do not contain
164 // TemplateArgumentTypeLocs, they only have TemplateArgumentTypes. So we
165 // create a new argument location list from TypeSourceInfo.
166 auto STL = TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>();
167 llvm::SmallVector<TemplateArgumentLoc, 8> ArgLocs;
168 ArgLocs.reserve(STL.getNumArgs());
169 for (unsigned I = 0; I < STL.getNumArgs(); ++I)
170 ArgLocs.push_back(STL.getArgLoc(I));
171 printTemplateArgumentList(OS, ArgLocs, Policy);
173 // FIXME: Fix cases when getTypeAsWritten returns null inside clang AST,
174 // e.g. friend decls. Currently we fallback to Template Arguments without
175 // location information.
176 printTemplateArgumentList(OS, Cls->getTemplateArgs().asArray(), Policy);
183 std::string printNamespaceScope(const DeclContext &DC) {
184 for (const auto *Ctx = &DC; Ctx != nullptr; Ctx = Ctx->getParent())
185 if (const auto *NS = dyn_cast<NamespaceDecl>(Ctx))
186 if (!NS->isAnonymousNamespace() && !NS->isInlineNamespace())
187 return printQualifiedName(*NS) + "::";
191 llvm::Optional<SymbolID> getSymbolID(const Decl *D) {
192 llvm::SmallString<128> USR;
193 if (index::generateUSRForDecl(D, USR))
195 return SymbolID(USR);
198 llvm::Optional<SymbolID> getSymbolID(const IdentifierInfo &II,
200 const SourceManager &SM) {
203 llvm::SmallString<128> USR;
204 if (index::generateUSRForMacro(II.getName(), MI->getDefinitionLoc(), SM, USR))
206 return SymbolID(USR);
209 std::string shortenNamespace(const llvm::StringRef OriginalName,
210 const llvm::StringRef CurrentNamespace) {
211 llvm::SmallVector<llvm::StringRef, 8> OriginalParts;
212 llvm::SmallVector<llvm::StringRef, 8> CurrentParts;
213 llvm::SmallVector<llvm::StringRef, 8> Result;
214 OriginalName.split(OriginalParts, "::");
215 CurrentNamespace.split(CurrentParts, "::");
216 auto MinLength = std::min(CurrentParts.size(), OriginalParts.size());
218 unsigned DifferentAt = 0;
219 while (DifferentAt < MinLength &&
220 CurrentParts[DifferentAt] == OriginalParts[DifferentAt]) {
224 for (unsigned i = DifferentAt; i < OriginalParts.size(); ++i) {
225 Result.push_back(OriginalParts[i]);
227 return join(Result, "::");
230 std::string printType(const QualType QT, const DeclContext & Context){
231 PrintingPolicy PP(Context.getParentASTContext().getPrintingPolicy());
232 PP.SuppressUnwrittenScope = 1;
233 PP.SuppressTagKeyword = 1;
234 return shortenNamespace(
236 printNamespaceScope(Context) );
240 } // namespace clangd