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/Decl.h" 14 #include "clang/AST/DeclBase.h" 15 #include "clang/AST/DeclTemplate.h" 16 #include "clang/AST/DeclarationName.h" 17 #include "clang/AST/NestedNameSpecifier.h" 18 #include "clang/AST/PrettyPrinter.h" 19 #include "clang/AST/RecursiveASTVisitor.h" 20 #include "clang/AST/TemplateBase.h" 21 #include "clang/Basic/SourceLocation.h" 22 #include "clang/Basic/SourceManager.h" 23 #include "clang/Basic/Specifiers.h" 24 #include "clang/Index/USRGeneration.h" 25 #include "clang/Lex/Lexer.h" 26 #include "llvm/ADT/ArrayRef.h" 27 #include "llvm/ADT/Optional.h" 28 #include "llvm/ADT/STLExtras.h" 29 #include "llvm/ADT/StringRef.h" 30 #include "llvm/Support/Casting.h" 31 #include "llvm/Support/ScopedPrinter.h" 32 #include "llvm/Support/raw_ostream.h" 33 #include <string> 34 #include <vector> 35 36 namespace clang { 37 namespace clangd { 38 39 namespace { 40 llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>> 41 getTemplateSpecializationArgLocs(const NamedDecl &ND) { 42 if (auto *Func = llvm::dyn_cast<FunctionDecl>(&ND)) { 43 if (const ASTTemplateArgumentListInfo *Args = 44 Func->getTemplateSpecializationArgsAsWritten()) 45 return Args->arguments(); 46 } else if (auto *Cls = 47 llvm::dyn_cast<ClassTemplatePartialSpecializationDecl>(&ND)) { 48 if (auto *Args = Cls->getTemplateArgsAsWritten()) 49 return Args->arguments(); 50 } else if (auto *Var = 51 llvm::dyn_cast<VarTemplatePartialSpecializationDecl>(&ND)) { 52 if (auto *Args = Var->getTemplateArgsAsWritten()) 53 return Args->arguments(); 54 } else if (auto *Var = llvm::dyn_cast<VarTemplateSpecializationDecl>(&ND)) 55 return Var->getTemplateArgsInfo().arguments(); 56 // We return None for ClassTemplateSpecializationDecls because it does not 57 // contain TemplateArgumentLoc information. 58 return llvm::None; 59 } 60 61 template <class T> 62 bool isTemplateSpecializationKind(const NamedDecl *D, 63 TemplateSpecializationKind Kind) { 64 if (const auto *TD = dyn_cast<T>(D)) 65 return TD->getTemplateSpecializationKind() == Kind; 66 return false; 67 } 68 69 bool isTemplateSpecializationKind(const NamedDecl *D, 70 TemplateSpecializationKind Kind) { 71 return isTemplateSpecializationKind<FunctionDecl>(D, Kind) || 72 isTemplateSpecializationKind<CXXRecordDecl>(D, Kind) || 73 isTemplateSpecializationKind<VarDecl>(D, Kind); 74 } 75 76 // Store all UsingDirectiveDecls in parent contexts of DestContext, that were 77 // introduced before InsertionPoint. 78 llvm::DenseSet<const NamespaceDecl *> 79 getUsingNamespaceDirectives(const DeclContext *DestContext, 80 SourceLocation Until) { 81 const auto &SM = DestContext->getParentASTContext().getSourceManager(); 82 llvm::DenseSet<const NamespaceDecl *> VisibleNamespaceDecls; 83 for (const auto *DC = DestContext; DC; DC = DC->getLookupParent()) { 84 for (const auto *D : DC->decls()) { 85 if (!SM.isWrittenInSameFile(D->getLocation(), Until) || 86 !SM.isBeforeInTranslationUnit(D->getLocation(), Until)) 87 continue; 88 if (auto *UDD = llvm::dyn_cast<UsingDirectiveDecl>(D)) 89 VisibleNamespaceDecls.insert( 90 UDD->getNominatedNamespace()->getCanonicalDecl()); 91 } 92 } 93 return VisibleNamespaceDecls; 94 } 95 96 // Goes over all parents of SourceContext until we find a comman ancestor for 97 // DestContext and SourceContext. Any qualifier including and above common 98 // ancestor is redundant, therefore we stop at lowest common ancestor. 99 // In addition to that stops early whenever IsVisible returns true. This can be 100 // used to implement support for "using namespace" decls. 101 std::string 102 getQualification(ASTContext &Context, const DeclContext *DestContext, 103 const DeclContext *SourceContext, 104 llvm::function_ref<bool(NestedNameSpecifier *)> IsVisible) { 105 std::vector<const NestedNameSpecifier *> Parents; 106 bool ReachedNS = false; 107 for (const DeclContext *CurContext = SourceContext; CurContext; 108 CurContext = CurContext->getLookupParent()) { 109 // Stop once we reach a common ancestor. 110 if (CurContext->Encloses(DestContext)) 111 break; 112 113 NestedNameSpecifier *NNS = nullptr; 114 if (auto *TD = llvm::dyn_cast<TagDecl>(CurContext)) { 115 // There can't be any more tag parents after hitting a namespace. 116 assert(!ReachedNS); 117 NNS = NestedNameSpecifier::Create(Context, nullptr, false, 118 TD->getTypeForDecl()); 119 } else { 120 ReachedNS = true; 121 auto *NSD = llvm::cast<NamespaceDecl>(CurContext); 122 NNS = NestedNameSpecifier::Create(Context, nullptr, NSD); 123 // Anonymous and inline namespace names are not spelled while qualifying a 124 // name, so skip those. 125 if (NSD->isAnonymousNamespace() || NSD->isInlineNamespace()) 126 continue; 127 } 128 // Stop if this namespace is already visible at DestContext. 129 if (IsVisible(NNS)) 130 break; 131 132 Parents.push_back(NNS); 133 } 134 135 // Go over name-specifiers in reverse order to create necessary qualification, 136 // since we stored inner-most parent first. 137 std::string Result; 138 llvm::raw_string_ostream OS(Result); 139 for (const auto *Parent : llvm::reverse(Parents)) 140 Parent->print(OS, Context.getPrintingPolicy()); 141 return OS.str(); 142 } 143 144 } // namespace 145 146 bool isImplicitTemplateInstantiation(const NamedDecl *D) { 147 return isTemplateSpecializationKind(D, TSK_ImplicitInstantiation); 148 } 149 150 bool isExplicitTemplateSpecialization(const NamedDecl *D) { 151 return isTemplateSpecializationKind(D, TSK_ExplicitSpecialization); 152 } 153 154 bool isImplementationDetail(const Decl *D) { 155 return !isSpelledInSource(D->getLocation(), 156 D->getASTContext().getSourceManager()); 157 } 158 159 SourceLocation findName(const clang::Decl *D) { return D->getLocation(); } 160 161 std::string printQualifiedName(const NamedDecl &ND) { 162 std::string QName; 163 llvm::raw_string_ostream OS(QName); 164 PrintingPolicy Policy(ND.getASTContext().getLangOpts()); 165 // Note that inline namespaces are treated as transparent scopes. This 166 // reflects the way they're most commonly used for lookup. Ideally we'd 167 // include them, but at query time it's hard to find all the inline 168 // namespaces to query: the preamble doesn't have a dedicated list. 169 Policy.SuppressUnwrittenScope = true; 170 ND.printQualifiedName(OS, Policy); 171 OS.flush(); 172 assert(!StringRef(QName).startswith("::")); 173 return QName; 174 } 175 176 static bool isAnonymous(const DeclarationName &N) { 177 return N.isIdentifier() && !N.getAsIdentifierInfo(); 178 } 179 180 NestedNameSpecifierLoc getQualifierLoc(const NamedDecl &ND) { 181 if (auto *V = llvm::dyn_cast<DeclaratorDecl>(&ND)) 182 return V->getQualifierLoc(); 183 if (auto *T = llvm::dyn_cast<TagDecl>(&ND)) 184 return T->getQualifierLoc(); 185 return NestedNameSpecifierLoc(); 186 } 187 188 std::string printUsingNamespaceName(const ASTContext &Ctx, 189 const UsingDirectiveDecl &D) { 190 PrintingPolicy PP(Ctx.getLangOpts()); 191 std::string Name; 192 llvm::raw_string_ostream Out(Name); 193 194 if (auto *Qual = D.getQualifier()) 195 Qual->print(Out, PP); 196 D.getNominatedNamespaceAsWritten()->printName(Out); 197 return Out.str(); 198 } 199 200 std::string printName(const ASTContext &Ctx, const NamedDecl &ND) { 201 std::string Name; 202 llvm::raw_string_ostream Out(Name); 203 PrintingPolicy PP(Ctx.getLangOpts()); 204 // We don't consider a class template's args part of the constructor name. 205 PP.SuppressTemplateArgsInCXXConstructors = true; 206 207 // Handle 'using namespace'. They all have the same name - <using-directive>. 208 if (auto *UD = llvm::dyn_cast<UsingDirectiveDecl>(&ND)) { 209 Out << "using namespace "; 210 if (auto *Qual = UD->getQualifier()) 211 Qual->print(Out, PP); 212 UD->getNominatedNamespaceAsWritten()->printName(Out); 213 return Out.str(); 214 } 215 216 if (isAnonymous(ND.getDeclName())) { 217 // Come up with a presentation for an anonymous entity. 218 if (isa<NamespaceDecl>(ND)) 219 return "(anonymous namespace)"; 220 if (auto *Cls = llvm::dyn_cast<RecordDecl>(&ND)) 221 return ("(anonymous " + Cls->getKindName() + ")").str(); 222 if (isa<EnumDecl>(ND)) 223 return "(anonymous enum)"; 224 return "(anonymous)"; 225 } 226 227 // Print nested name qualifier if it was written in the source code. 228 if (auto *Qualifier = getQualifierLoc(ND).getNestedNameSpecifier()) 229 Qualifier->print(Out, PP); 230 // Print the name itself. 231 ND.getDeclName().print(Out, PP); 232 // Print template arguments. 233 Out << printTemplateSpecializationArgs(ND); 234 235 return Out.str(); 236 } 237 238 std::string printTemplateSpecializationArgs(const NamedDecl &ND) { 239 std::string TemplateArgs; 240 llvm::raw_string_ostream OS(TemplateArgs); 241 PrintingPolicy Policy(ND.getASTContext().getLangOpts()); 242 if (llvm::Optional<llvm::ArrayRef<TemplateArgumentLoc>> Args = 243 getTemplateSpecializationArgLocs(ND)) { 244 printTemplateArgumentList(OS, *Args, Policy); 245 } else if (auto *Cls = llvm::dyn_cast<ClassTemplateSpecializationDecl>(&ND)) { 246 if (const TypeSourceInfo *TSI = Cls->getTypeAsWritten()) { 247 // ClassTemplateSpecializationDecls do not contain 248 // TemplateArgumentTypeLocs, they only have TemplateArgumentTypes. So we 249 // create a new argument location list from TypeSourceInfo. 250 auto STL = TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>(); 251 llvm::SmallVector<TemplateArgumentLoc, 8> ArgLocs; 252 ArgLocs.reserve(STL.getNumArgs()); 253 for (unsigned I = 0; I < STL.getNumArgs(); ++I) 254 ArgLocs.push_back(STL.getArgLoc(I)); 255 printTemplateArgumentList(OS, ArgLocs, Policy); 256 } else { 257 // FIXME: Fix cases when getTypeAsWritten returns null inside clang AST, 258 // e.g. friend decls. Currently we fallback to Template Arguments without 259 // location information. 260 printTemplateArgumentList(OS, Cls->getTemplateArgs().asArray(), Policy); 261 } 262 } 263 OS.flush(); 264 return TemplateArgs; 265 } 266 267 std::string printNamespaceScope(const DeclContext &DC) { 268 for (const auto *Ctx = &DC; Ctx != nullptr; Ctx = Ctx->getParent()) 269 if (const auto *NS = dyn_cast<NamespaceDecl>(Ctx)) 270 if (!NS->isAnonymousNamespace() && !NS->isInlineNamespace()) 271 return printQualifiedName(*NS) + "::"; 272 return ""; 273 } 274 275 llvm::Optional<SymbolID> getSymbolID(const Decl *D) { 276 llvm::SmallString<128> USR; 277 if (index::generateUSRForDecl(D, USR)) 278 return None; 279 return SymbolID(USR); 280 } 281 282 llvm::Optional<SymbolID> getSymbolID(const llvm::StringRef MacroName, 283 const MacroInfo *MI, 284 const SourceManager &SM) { 285 if (MI == nullptr) 286 return None; 287 llvm::SmallString<128> USR; 288 if (index::generateUSRForMacro(MacroName, MI->getDefinitionLoc(), SM, USR)) 289 return None; 290 return SymbolID(USR); 291 } 292 293 std::string shortenNamespace(const llvm::StringRef OriginalName, 294 const llvm::StringRef CurrentNamespace) { 295 llvm::SmallVector<llvm::StringRef, 8> OriginalParts; 296 llvm::SmallVector<llvm::StringRef, 8> CurrentParts; 297 llvm::SmallVector<llvm::StringRef, 8> Result; 298 OriginalName.split(OriginalParts, "::"); 299 CurrentNamespace.split(CurrentParts, "::"); 300 auto MinLength = std::min(CurrentParts.size(), OriginalParts.size()); 301 302 unsigned DifferentAt = 0; 303 while (DifferentAt < MinLength && 304 CurrentParts[DifferentAt] == OriginalParts[DifferentAt]) { 305 DifferentAt++; 306 } 307 308 for (unsigned i = DifferentAt; i < OriginalParts.size(); ++i) { 309 Result.push_back(OriginalParts[i]); 310 } 311 return join(Result, "::"); 312 } 313 314 std::string printType(const QualType QT, const DeclContext &Context) { 315 PrintingPolicy PP(Context.getParentASTContext().getPrintingPolicy()); 316 PP.SuppressUnwrittenScope = 1; 317 PP.SuppressTagKeyword = 1; 318 return shortenNamespace(QT.getAsString(PP), printNamespaceScope(Context)); 319 } 320 321 QualType declaredType(const TypeDecl *D) { 322 if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) 323 if (const auto *TSI = CTSD->getTypeAsWritten()) 324 return TSI->getType(); 325 return D->getASTContext().getTypeDeclType(D); 326 } 327 328 namespace { 329 /// Computes the deduced type at a given location by visiting the relevant 330 /// nodes. We use this to display the actual type when hovering over an "auto" 331 /// keyword or "decltype()" expression. 332 /// FIXME: This could have been a lot simpler by visiting AutoTypeLocs but it 333 /// seems that the AutoTypeLocs that can be visited along with their AutoType do 334 /// not have the deduced type set. Instead, we have to go to the appropriate 335 /// DeclaratorDecl/FunctionDecl and work our back to the AutoType that does have 336 /// a deduced type set. The AST should be improved to simplify this scenario. 337 class DeducedTypeVisitor : public RecursiveASTVisitor<DeducedTypeVisitor> { 338 SourceLocation SearchedLocation; 339 340 public: 341 DeducedTypeVisitor(SourceLocation SearchedLocation) 342 : SearchedLocation(SearchedLocation) {} 343 344 // Handle auto initializers: 345 //- auto i = 1; 346 //- decltype(auto) i = 1; 347 //- auto& i = 1; 348 //- auto* i = &a; 349 bool VisitDeclaratorDecl(DeclaratorDecl *D) { 350 if (!D->getTypeSourceInfo() || 351 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc() != SearchedLocation) 352 return true; 353 354 if (auto *AT = D->getType()->getContainedAutoType()) { 355 if (!AT->getDeducedType().isNull()) 356 DeducedType = AT->getDeducedType(); 357 } 358 return true; 359 } 360 361 // Handle auto return types: 362 //- auto foo() {} 363 //- auto& foo() {} 364 //- auto foo() -> int {} 365 //- auto foo() -> decltype(1+1) {} 366 //- operator auto() const { return 10; } 367 bool VisitFunctionDecl(FunctionDecl *D) { 368 if (!D->getTypeSourceInfo()) 369 return true; 370 // Loc of auto in return type (c++14). 371 auto CurLoc = D->getReturnTypeSourceRange().getBegin(); 372 // Loc of "auto" in operator auto() 373 if (CurLoc.isInvalid() && dyn_cast<CXXConversionDecl>(D)) 374 CurLoc = D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 375 // Loc of "auto" in function with traling return type (c++11). 376 if (CurLoc.isInvalid()) 377 CurLoc = D->getSourceRange().getBegin(); 378 if (CurLoc != SearchedLocation) 379 return true; 380 381 const AutoType *AT = D->getReturnType()->getContainedAutoType(); 382 if (AT && !AT->getDeducedType().isNull()) { 383 DeducedType = AT->getDeducedType(); 384 } else if (auto DT = dyn_cast<DecltypeType>(D->getReturnType())) { 385 // auto in a trailing return type just points to a DecltypeType and 386 // getContainedAutoType does not unwrap it. 387 if (!DT->getUnderlyingType().isNull()) 388 DeducedType = DT->getUnderlyingType(); 389 } else if (!D->getReturnType().isNull()) { 390 DeducedType = D->getReturnType(); 391 } 392 return true; 393 } 394 395 // Handle non-auto decltype, e.g.: 396 // - auto foo() -> decltype(expr) {} 397 // - decltype(expr); 398 bool VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 399 if (TL.getBeginLoc() != SearchedLocation) 400 return true; 401 402 // A DecltypeType's underlying type can be another DecltypeType! E.g. 403 // int I = 0; 404 // decltype(I) J = I; 405 // decltype(J) K = J; 406 const DecltypeType *DT = dyn_cast<DecltypeType>(TL.getTypePtr()); 407 while (DT && !DT->getUnderlyingType().isNull()) { 408 DeducedType = DT->getUnderlyingType(); 409 DT = dyn_cast<DecltypeType>(DeducedType.getTypePtr()); 410 } 411 return true; 412 } 413 414 QualType DeducedType; 415 }; 416 } // namespace 417 418 llvm::Optional<QualType> getDeducedType(ASTContext &ASTCtx, 419 SourceLocation Loc) { 420 Token Tok; 421 // Only try to find a deduced type if the token is auto or decltype. 422 if (!Loc.isValid() || 423 Lexer::getRawToken(Loc, Tok, ASTCtx.getSourceManager(), 424 ASTCtx.getLangOpts(), false) || 425 !Tok.is(tok::raw_identifier) || 426 !(Tok.getRawIdentifier() == "auto" || 427 Tok.getRawIdentifier() == "decltype")) { 428 return {}; 429 } 430 DeducedTypeVisitor V(Loc); 431 V.TraverseAST(ASTCtx); 432 if (V.DeducedType.isNull()) 433 return llvm::None; 434 return V.DeducedType; 435 } 436 437 std::string getQualification(ASTContext &Context, 438 const DeclContext *DestContext, 439 SourceLocation InsertionPoint, 440 const NamedDecl *ND) { 441 auto VisibleNamespaceDecls = 442 getUsingNamespaceDirectives(DestContext, InsertionPoint); 443 return getQualification( 444 Context, DestContext, ND->getDeclContext(), 445 [&](NestedNameSpecifier *NNS) { 446 if (NNS->getKind() != NestedNameSpecifier::Namespace) 447 return false; 448 const auto *CanonNSD = NNS->getAsNamespace()->getCanonicalDecl(); 449 return llvm::any_of(VisibleNamespaceDecls, 450 [CanonNSD](const NamespaceDecl *NSD) { 451 return NSD->getCanonicalDecl() == CanonNSD; 452 }); 453 }); 454 } 455 456 std::string getQualification(ASTContext &Context, 457 const DeclContext *DestContext, 458 SourceLocation InsertionPoint, const NamedDecl *ND, 459 llvm::ArrayRef<std::string> VisibleNamespaces) { 460 for (llvm::StringRef NS : VisibleNamespaces) { 461 assert(NS.endswith("::")); 462 (void)NS; 463 } 464 return getQualification( 465 Context, DestContext, ND->getDeclContext(), 466 [&](NestedNameSpecifier *NNS) { 467 return llvm::any_of(VisibleNamespaces, [&](llvm::StringRef Namespace) { 468 std::string NS; 469 llvm::raw_string_ostream OS(NS); 470 NNS->print(OS, Context.getPrintingPolicy()); 471 return OS.str() == Namespace; 472 }); 473 }); 474 } 475 476 } // namespace clangd 477 } // namespace clang 478