1 //===--- IncludeFixer.cpp ----------------------------------------*- 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 "IncludeFixer.h" 10 #include "AST.h" 11 #include "Diagnostics.h" 12 #include "SourceCode.h" 13 #include "index/Index.h" 14 #include "index/Symbol.h" 15 #include "support/Logger.h" 16 #include "support/Trace.h" 17 #include "clang/AST/Decl.h" 18 #include "clang/AST/DeclBase.h" 19 #include "clang/AST/DeclarationName.h" 20 #include "clang/AST/NestedNameSpecifier.h" 21 #include "clang/AST/Type.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/DiagnosticSema.h" 24 #include "clang/Basic/LangOptions.h" 25 #include "clang/Basic/SourceLocation.h" 26 #include "clang/Basic/SourceManager.h" 27 #include "clang/Basic/TokenKinds.h" 28 #include "clang/Lex/Lexer.h" 29 #include "clang/Sema/DeclSpec.h" 30 #include "clang/Sema/Lookup.h" 31 #include "clang/Sema/Scope.h" 32 #include "clang/Sema/Sema.h" 33 #include "clang/Sema/TypoCorrection.h" 34 #include "llvm/ADT/ArrayRef.h" 35 #include "llvm/ADT/DenseMap.h" 36 #include "llvm/ADT/None.h" 37 #include "llvm/ADT/Optional.h" 38 #include "llvm/ADT/StringExtras.h" 39 #include "llvm/ADT/StringRef.h" 40 #include "llvm/ADT/StringSet.h" 41 #include "llvm/Support/Error.h" 42 #include "llvm/Support/FormatVariadic.h" 43 #include <vector> 44 45 namespace clang { 46 namespace clangd { 47 48 namespace { 49 50 // Collects contexts visited during a Sema name lookup. 51 class VisitedContextCollector : public VisibleDeclConsumer { 52 public: 53 void EnteredContext(DeclContext *Ctx) override { Visited.push_back(Ctx); } 54 55 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, 56 bool InBaseClass) override {} 57 58 std::vector<DeclContext *> takeVisitedContexts() { 59 return std::move(Visited); 60 } 61 62 private: 63 std::vector<DeclContext *> Visited; 64 }; 65 66 } // namespace 67 68 std::vector<Fix> IncludeFixer::fix(DiagnosticsEngine::Level DiagLevel, 69 const clang::Diagnostic &Info) const { 70 switch (Info.getID()) { 71 case diag::err_incomplete_type: 72 case diag::err_incomplete_member_access: 73 case diag::err_incomplete_base_class: 74 case diag::err_incomplete_nested_name_spec: 75 // Incomplete type diagnostics should have a QualType argument for the 76 // incomplete type. 77 for (unsigned Idx = 0; Idx < Info.getNumArgs(); ++Idx) { 78 if (Info.getArgKind(Idx) == DiagnosticsEngine::ak_qualtype) { 79 auto QT = QualType::getFromOpaquePtr((void *)Info.getRawArg(Idx)); 80 if (const Type *T = QT.getTypePtrOrNull()) 81 if (T->isIncompleteType()) 82 return fixIncompleteType(*T); 83 } 84 } 85 break; 86 case diag::err_unknown_typename: 87 case diag::err_unknown_typename_suggest: 88 case diag::err_typename_nested_not_found: 89 case diag::err_no_template: 90 case diag::err_no_template_suggest: 91 case diag::err_undeclared_use: 92 case diag::err_undeclared_use_suggest: 93 case diag::err_undeclared_var_use: 94 case diag::err_undeclared_var_use_suggest: 95 case diag::err_no_member: // Could be no member in namespace. 96 case diag::err_no_member_suggest: 97 if (LastUnresolvedName) { 98 // Try to fix unresolved name caused by missing declaration. 99 // E.g. 100 // clang::SourceManager SM; 101 // ~~~~~~~~~~~~~ 102 // UnresolvedName 103 // or 104 // namespace clang { SourceManager SM; } 105 // ~~~~~~~~~~~~~ 106 // UnresolvedName 107 // We only attempt to recover a diagnostic if it has the same location as 108 // the last seen unresolved name. 109 if (DiagLevel >= DiagnosticsEngine::Error && 110 LastUnresolvedName->Loc == Info.getLocation()) 111 return fixUnresolvedName(); 112 } 113 } 114 return {}; 115 } 116 117 std::vector<Fix> IncludeFixer::fixIncompleteType(const Type &T) const { 118 // Only handle incomplete TagDecl type. 119 const TagDecl *TD = T.getAsTagDecl(); 120 if (!TD) 121 return {}; 122 std::string TypeName = printQualifiedName(*TD); 123 trace::Span Tracer("Fix include for incomplete type"); 124 SPAN_ATTACH(Tracer, "type", TypeName); 125 vlog("Trying to fix include for incomplete type {0}", TypeName); 126 127 auto ID = getSymbolID(TD); 128 if (!ID) 129 return {}; 130 llvm::Optional<const SymbolSlab *> Symbols = lookupCached(*ID); 131 if (!Symbols) 132 return {}; 133 const SymbolSlab &Syms = **Symbols; 134 std::vector<Fix> Fixes; 135 if (!Syms.empty()) { 136 auto &Matched = *Syms.begin(); 137 if (!Matched.IncludeHeaders.empty() && Matched.Definition && 138 Matched.CanonicalDeclaration.FileURI == Matched.Definition.FileURI) 139 Fixes = fixesForSymbols(Syms); 140 } 141 return Fixes; 142 } 143 144 std::vector<Fix> IncludeFixer::fixesForSymbols(const SymbolSlab &Syms) const { 145 auto Inserted = [&](const Symbol &Sym, llvm::StringRef Header) 146 -> llvm::Expected<std::pair<std::string, bool>> { 147 auto ResolvedDeclaring = 148 URI::resolve(Sym.CanonicalDeclaration.FileURI, File); 149 if (!ResolvedDeclaring) 150 return ResolvedDeclaring.takeError(); 151 auto ResolvedInserted = toHeaderFile(Header, File); 152 if (!ResolvedInserted) 153 return ResolvedInserted.takeError(); 154 auto Spelled = Inserter->calculateIncludePath(*ResolvedInserted, File); 155 if (!Spelled) 156 return error("Header not on include path"); 157 return std::make_pair( 158 std::move(*Spelled), 159 Inserter->shouldInsertInclude(*ResolvedDeclaring, *ResolvedInserted)); 160 }; 161 162 std::vector<Fix> Fixes; 163 // Deduplicate fixes by include headers. This doesn't distinguish symbols in 164 // different scopes from the same header, but this case should be rare and is 165 // thus ignored. 166 llvm::StringSet<> InsertedHeaders; 167 for (const auto &Sym : Syms) { 168 for (const auto &Inc : getRankedIncludes(Sym)) { 169 if (auto ToInclude = Inserted(Sym, Inc)) { 170 if (ToInclude->second) { 171 auto I = InsertedHeaders.try_emplace(ToInclude->first); 172 if (!I.second) 173 continue; 174 if (auto Edit = Inserter->insert(ToInclude->first)) 175 Fixes.push_back(Fix{std::string(llvm::formatv( 176 "Add include {0} for symbol {1}{2}", 177 ToInclude->first, Sym.Scope, Sym.Name)), 178 {std::move(*Edit)}}); 179 } 180 } else { 181 vlog("Failed to calculate include insertion for {0} into {1}: {2}", Inc, 182 File, ToInclude.takeError()); 183 } 184 } 185 } 186 return Fixes; 187 } 188 189 // Returns the identifiers qualified by an unresolved name. \p Loc is the 190 // start location of the unresolved name. For the example below, this returns 191 // "::X::Y" that is qualified by unresolved name "clangd": 192 // clang::clangd::X::Y 193 // ~ 194 llvm::Optional<std::string> qualifiedByUnresolved(const SourceManager &SM, 195 SourceLocation Loc, 196 const LangOptions &LangOpts) { 197 std::string Result; 198 199 SourceLocation NextLoc = Loc; 200 while (auto CCTok = Lexer::findNextToken(NextLoc, SM, LangOpts)) { 201 if (!CCTok->is(tok::coloncolon)) 202 break; 203 auto IDTok = Lexer::findNextToken(CCTok->getLocation(), SM, LangOpts); 204 if (!IDTok || !IDTok->is(tok::raw_identifier)) 205 break; 206 Result.append(("::" + IDTok->getRawIdentifier()).str()); 207 NextLoc = IDTok->getLocation(); 208 } 209 if (Result.empty()) 210 return llvm::None; 211 return Result; 212 } 213 214 // An unresolved name and its scope information that can be extracted cheaply. 215 struct CheapUnresolvedName { 216 std::string Name; 217 // This is the part of what was typed that was resolved, and it's in its 218 // resolved form not its typed form (think `namespace clang { clangd::x }` --> 219 // `clang::clangd::`). 220 llvm::Optional<std::string> ResolvedScope; 221 222 // Unresolved part of the scope. When the unresolved name is a specifier, we 223 // use the name that comes after it as the alternative name to resolve and use 224 // the specifier as the extra scope in the accessible scopes. 225 llvm::Optional<std::string> UnresolvedScope; 226 }; 227 228 // Extracts unresolved name and scope information around \p Unresolved. 229 // FIXME: try to merge this with the scope-wrangling code in CodeComplete. 230 llvm::Optional<CheapUnresolvedName> extractUnresolvedNameCheaply( 231 const SourceManager &SM, const DeclarationNameInfo &Unresolved, 232 CXXScopeSpec *SS, const LangOptions &LangOpts, bool UnresolvedIsSpecifier) { 233 bool Invalid = false; 234 llvm::StringRef Code = SM.getBufferData( 235 SM.getDecomposedLoc(Unresolved.getBeginLoc()).first, &Invalid); 236 if (Invalid) 237 return llvm::None; 238 CheapUnresolvedName Result; 239 Result.Name = Unresolved.getAsString(); 240 if (SS && SS->isNotEmpty()) { // "::" or "ns::" 241 if (auto *Nested = SS->getScopeRep()) { 242 if (Nested->getKind() == NestedNameSpecifier::Global) 243 Result.ResolvedScope = ""; 244 else if (const auto *NS = Nested->getAsNamespace()) { 245 auto SpecifiedNS = printNamespaceScope(*NS); 246 247 // Check the specifier spelled in the source. 248 // If the resolved scope doesn't end with the spelled scope. The 249 // resolved scope can come from a sema typo correction. For example, 250 // sema assumes that "clangd::" is a typo of "clang::" and uses 251 // "clang::" as the specified scope in: 252 // namespace clang { clangd::X; } 253 // In this case, we use the "typo" specifier as extra scope instead 254 // of using the scope assumed by sema. 255 auto B = SM.getFileOffset(SS->getBeginLoc()); 256 auto E = SM.getFileOffset(SS->getEndLoc()); 257 std::string Spelling = (Code.substr(B, E - B) + "::").str(); 258 if (llvm::StringRef(SpecifiedNS).endswith(Spelling)) 259 Result.ResolvedScope = SpecifiedNS; 260 else 261 Result.UnresolvedScope = Spelling; 262 } else if (const auto *ANS = Nested->getAsNamespaceAlias()) { 263 Result.ResolvedScope = printNamespaceScope(*ANS->getNamespace()); 264 } else { 265 // We don't fix symbols in scopes that are not top-level e.g. class 266 // members, as we don't collect includes for them. 267 return llvm::None; 268 } 269 } 270 } 271 272 if (UnresolvedIsSpecifier) { 273 // If the unresolved name is a specifier e.g. 274 // clang::clangd::X 275 // ~~~~~~ 276 // We try to resolve clang::clangd::X instead of clang::clangd. 277 // FIXME: We won't be able to fix include if the specifier is what we 278 // should resolve (e.g. it's a class scope specifier). Collecting include 279 // headers for nested types could make this work. 280 281 // Not using the end location as it doesn't always point to the end of 282 // identifier. 283 if (auto QualifiedByUnresolved = 284 qualifiedByUnresolved(SM, Unresolved.getBeginLoc(), LangOpts)) { 285 auto Split = splitQualifiedName(*QualifiedByUnresolved); 286 if (!Result.UnresolvedScope) 287 Result.UnresolvedScope.emplace(); 288 // If UnresolvedSpecifiedScope is already set, we simply append the 289 // extra scope. Suppose the unresolved name is "index" in the following 290 // example: 291 // namespace clang { clangd::index::X; } 292 // ~~~~~~ ~~~~~ 293 // "clangd::" is assumed to be clang:: by Sema, and we would have used 294 // it as extra scope. With "index" being a specifier, we append "index::" 295 // to the extra scope. 296 Result.UnresolvedScope->append((Result.Name + Split.first).str()); 297 Result.Name = std::string(Split.second); 298 } 299 } 300 return Result; 301 } 302 303 /// Returns all namespace scopes that the unqualified lookup would visit. 304 std::vector<std::string> 305 collectAccessibleScopes(Sema &Sem, const DeclarationNameInfo &Typo, Scope *S, 306 Sema::LookupNameKind LookupKind) { 307 std::vector<std::string> Scopes; 308 VisitedContextCollector Collector; 309 Sem.LookupVisibleDecls(S, LookupKind, Collector, 310 /*IncludeGlobalScope=*/false, 311 /*LoadExternal=*/false); 312 313 Scopes.push_back(""); 314 for (const auto *Ctx : Collector.takeVisitedContexts()) { 315 if (isa<NamespaceDecl>(Ctx)) 316 Scopes.push_back(printNamespaceScope(*Ctx)); 317 } 318 return Scopes; 319 } 320 321 class IncludeFixer::UnresolvedNameRecorder : public ExternalSemaSource { 322 public: 323 UnresolvedNameRecorder(llvm::Optional<UnresolvedName> &LastUnresolvedName) 324 : LastUnresolvedName(LastUnresolvedName) {} 325 326 void InitializeSema(Sema &S) override { this->SemaPtr = &S; } 327 328 // Captures the latest typo and treat it as an unresolved name that can 329 // potentially be fixed by adding #includes. 330 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, int LookupKind, 331 Scope *S, CXXScopeSpec *SS, 332 CorrectionCandidateCallback &CCC, 333 DeclContext *MemberContext, bool EnteringContext, 334 const ObjCObjectPointerType *OPT) override { 335 assert(SemaPtr && "Sema must have been set."); 336 if (SemaPtr->isSFINAEContext()) 337 return TypoCorrection(); 338 if (!isInsideMainFile(Typo.getLoc(), SemaPtr->SourceMgr)) 339 return clang::TypoCorrection(); 340 341 auto Extracted = extractUnresolvedNameCheaply( 342 SemaPtr->SourceMgr, Typo, SS, SemaPtr->LangOpts, 343 static_cast<Sema::LookupNameKind>(LookupKind) == 344 Sema::LookupNameKind::LookupNestedNameSpecifierName); 345 if (!Extracted) 346 return TypoCorrection(); 347 348 UnresolvedName Unresolved; 349 Unresolved.Name = Extracted->Name; 350 Unresolved.Loc = Typo.getBeginLoc(); 351 if (!Extracted->ResolvedScope && !S) // Give up if no scope available. 352 return TypoCorrection(); 353 354 if (Extracted->ResolvedScope) 355 Unresolved.Scopes.push_back(*Extracted->ResolvedScope); 356 else // no qualifier or qualifier is unresolved. 357 Unresolved.Scopes = collectAccessibleScopes( 358 *SemaPtr, Typo, S, static_cast<Sema::LookupNameKind>(LookupKind)); 359 360 if (Extracted->UnresolvedScope) { 361 for (std::string &Scope : Unresolved.Scopes) 362 Scope += *Extracted->UnresolvedScope; 363 } 364 365 LastUnresolvedName = std::move(Unresolved); 366 367 // Never return a valid correction to try to recover. Our suggested fixes 368 // always require a rebuild. 369 return TypoCorrection(); 370 } 371 372 private: 373 Sema *SemaPtr = nullptr; 374 375 llvm::Optional<UnresolvedName> &LastUnresolvedName; 376 }; 377 378 llvm::IntrusiveRefCntPtr<ExternalSemaSource> 379 IncludeFixer::unresolvedNameRecorder() { 380 return new UnresolvedNameRecorder(LastUnresolvedName); 381 } 382 383 std::vector<Fix> IncludeFixer::fixUnresolvedName() const { 384 assert(LastUnresolvedName.hasValue()); 385 auto &Unresolved = *LastUnresolvedName; 386 vlog("Trying to fix unresolved name \"{0}\" in scopes: [{1}]", 387 Unresolved.Name, llvm::join(Unresolved.Scopes, ", ")); 388 389 FuzzyFindRequest Req; 390 Req.AnyScope = false; 391 Req.Query = Unresolved.Name; 392 Req.Scopes = Unresolved.Scopes; 393 Req.RestrictForCodeCompletion = true; 394 Req.Limit = 100; 395 396 if (llvm::Optional<const SymbolSlab *> Syms = fuzzyFindCached(Req)) 397 return fixesForSymbols(**Syms); 398 399 return {}; 400 } 401 402 llvm::Optional<const SymbolSlab *> 403 IncludeFixer::fuzzyFindCached(const FuzzyFindRequest &Req) const { 404 auto ReqStr = llvm::formatv("{0}", toJSON(Req)).str(); 405 auto I = FuzzyFindCache.find(ReqStr); 406 if (I != FuzzyFindCache.end()) 407 return &I->second; 408 409 if (IndexRequestCount >= IndexRequestLimit) 410 return llvm::None; 411 IndexRequestCount++; 412 413 SymbolSlab::Builder Matches; 414 Index.fuzzyFind(Req, [&](const Symbol &Sym) { 415 if (Sym.Name != Req.Query) 416 return; 417 if (!Sym.IncludeHeaders.empty()) 418 Matches.insert(Sym); 419 }); 420 auto Syms = std::move(Matches).build(); 421 auto E = FuzzyFindCache.try_emplace(ReqStr, std::move(Syms)); 422 return &E.first->second; 423 } 424 425 llvm::Optional<const SymbolSlab *> 426 IncludeFixer::lookupCached(const SymbolID &ID) const { 427 LookupRequest Req; 428 Req.IDs.insert(ID); 429 430 auto I = LookupCache.find(ID); 431 if (I != LookupCache.end()) 432 return &I->second; 433 434 if (IndexRequestCount >= IndexRequestLimit) 435 return llvm::None; 436 IndexRequestCount++; 437 438 // FIXME: consider batching the requests for all diagnostics. 439 SymbolSlab::Builder Matches; 440 Index.lookup(Req, [&](const Symbol &Sym) { Matches.insert(Sym); }); 441 auto Syms = std::move(Matches).build(); 442 443 std::vector<Fix> Fixes; 444 if (!Syms.empty()) { 445 auto &Matched = *Syms.begin(); 446 if (!Matched.IncludeHeaders.empty() && Matched.Definition && 447 Matched.CanonicalDeclaration.FileURI == Matched.Definition.FileURI) 448 Fixes = fixesForSymbols(Syms); 449 } 450 auto E = LookupCache.try_emplace(ID, std::move(Syms)); 451 return &E.first->second; 452 } 453 454 } // namespace clangd 455 } // namespace clang 456