16#include "clang-include-cleaner/Analysis.h"
17#include "clang-include-cleaner/IncludeSpeller.h"
18#include "clang-include-cleaner/Record.h"
19#include "clang-include-cleaner/Types.h"
23#include "clang/AST/ASTContext.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/LLVM.h"
26#include "clang/Basic/SourceLocation.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Format/Format.h"
29#include "clang/Lex/DirectoryLookup.h"
30#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Tooling/Core/Replacement.h"
33#include "clang/Tooling/Inclusions/HeaderIncludes.h"
34#include "clang/Tooling/Inclusions/StandardLibrary.h"
35#include "clang/Tooling/Syntax/Tokens.h"
36#include "llvm/ADT/ArrayRef.h"
37#include "llvm/ADT/DenseSet.h"
38#include "llvm/ADT/GenericUniformityImpl.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/SmallString.h"
41#include "llvm/ADT/SmallVector.h"
42#include "llvm/ADT/StringRef.h"
43#include "llvm/Support/Error.h"
44#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/FormatVariadic.h"
46#include "llvm/Support/Path.h"
47#include "llvm/Support/Regex.h"
59bool isIgnored(llvm::StringRef HeaderPath,
HeaderFilter IgnoreHeaders) {
61 llvm::SmallString<64> NormalizedPath(HeaderPath);
62 llvm::sys::path::native(NormalizedPath, llvm::sys::path::Style::posix);
63 for (
auto &Filter : IgnoreHeaders) {
64 if (Filter(NormalizedPath))
71 const include_cleaner::PragmaIncludes *PI,
72 bool AnalyzeAngledIncludes) {
75 auto FE =
AST.getSourceManager().getFileManager().getFileRef(
76 AST.getIncludeStructure().getRealPath(HID));
78 if (FE->getDir() ==
AST.getPreprocessor()
79 .getHeaderSearchInfo()
83 if (PI && PI->shouldKeep(*FE))
89 if (Inc.Written.front() ==
'<') {
90 if (tooling::stdlib::Header::named(Inc.Written))
92 if (!AnalyzeAngledIncludes)
98 if (
auto PHeader = PI->getPublic(*FE); !PHeader.empty()) {
99 PHeader = PHeader.trim(
"<>\"");
103 if (
AST.tuPath().ends_with(PHeader))
109 if (!
AST.getPreprocessor().getHeaderSearchInfo().isFileMultipleIncludeGuarded(
111 dlog(
"{0} doesn't have header guard and will not be considered unused",
118std::vector<Diag> generateMissingIncludeDiagnostics(
119 ParsedAST &
AST, llvm::ArrayRef<MissingIncludeDiagInfo> MissingIncludes,
123 std::vector<Diag> Result;
124 const SourceManager &SM =
AST.getSourceManager();
125 const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID());
129 tooling::HeaderIncludes HeaderIncludes(
AST.tuPath(), Code,
130 FileStyle.IncludeStyle);
131 for (
const auto &SymbolWithMissingInclude : MissingIncludes) {
132 llvm::StringRef ResolvedPath =
133 SymbolWithMissingInclude.Providers.front().resolvedPath();
134 if (isIgnored(ResolvedPath, IgnoreHeaders)) {
135 dlog(
"IncludeCleaner: not diagnosing missing include {0}, filtered by "
141 std::string Spelling = include_cleaner::spellHeader(
142 {SymbolWithMissingInclude.Providers.front(),
143 AST.getPreprocessor().getHeaderSearchInfo(), MainFile});
145 llvm::StringRef HeaderRef{Spelling};
147 bool Angled = HeaderRef.starts_with(
"<");
148 if (SymbolWithMissingInclude.Providers.front().kind() ==
149 include_cleaner::Header::Kind::Physical) {
150 for (
auto &Filter : Angled ? QuotedHeaders : AngledHeaders) {
151 if (Filter(ResolvedPath)) {
162 std::optional<tooling::Replacement> Replacement = HeaderIncludes.insert(
163 HeaderRef.trim(
"\"<>"), Angled, tooling::IncludeDirective::Include);
164 if (!Replacement.has_value())
167 if (Angled != (Spelling.front() ==
'<')) {
168 Spelling.front() = Angled ?
'<' :
'"';
169 Spelling.back() = Angled ?
'>' :
'"';
172 Diag &
D = Result.emplace_back();
174 llvm::formatv(
"No header providing \"{0}\" is directly included",
175 SymbolWithMissingInclude.Symbol.name());
176 D.Name =
"missing-includes";
178 D.File =
AST.tuPath();
179 D.InsideMainFile =
true;
196 D.Severity = DiagnosticsEngine::Note;
197 D.Range = clangd::Range{
199 SymbolWithMissingInclude.SymRefRange.beginOffset()),
201 SymbolWithMissingInclude.SymRefRange.endOffset())};
202 auto &F =
D.Fixes.emplace_back();
203 F.Message =
"#include " + Spelling;
205 F.Edits.emplace_back(std::move(
Edit));
210std::vector<Diag> generateUnusedIncludeDiagnostics(
211 PathRef FileName, llvm::ArrayRef<const Inclusion *> UnusedIncludes,
213 std::vector<Diag> Result;
214 for (
const auto *Inc : UnusedIncludes) {
215 if (isIgnored(Inc->Resolved, IgnoreHeaders))
217 Diag &
D = Result.emplace_back();
219 llvm::formatv(
"included header {0} is not used directly",
220 llvm::sys::path::filename(
221 Inc->Written.substr(1, Inc->Written.size() - 2),
222 llvm::sys::path::Style::posix));
223 D.Name =
"unused-includes";
226 D.InsideMainFile =
true;
227 D.Severity = DiagnosticsEngine::Warning;
235 auto &F =
D.Fixes.emplace_back();
236 F.Message =
"remove #include directive";
237 F.Edits.emplace_back();
238 F.Edits.back().range.start.line = Inc->HashLine;
239 F.Edits.back().range.end.line = Inc->HashLine + 1;
245removeAllUnusedIncludes(llvm::ArrayRef<Diag> UnusedIncludes) {
246 if (UnusedIncludes.empty())
250 RemoveAll.
Message =
"remove all unused includes";
251 for (
const auto &
Diag : UnusedIncludes) {
252 assert(
Diag.
Fixes.size() == 1 &&
"Expected exactly one fix.");
253 RemoveAll.Edits.insert(RemoveAll.Edits.end(),
261addAllMissingIncludes(llvm::ArrayRef<Diag> MissingIncludeDiags) {
262 if (MissingIncludeDiags.empty())
266 AddAllMissing.
Message =
"add all missing includes";
269 std::map<std::string, TextEdit> Edits;
270 for (
const auto &
Diag : MissingIncludeDiags) {
271 assert(
Diag.
Fixes.size() == 1 &&
"Expected exactly one fix.");
273 Edits.try_emplace(
Edit.newText,
Edit);
276 for (
auto &It : Edits)
277 AddAllMissing.Edits.push_back(std::move(It.second));
278 return AddAllMissing;
280Fix fixAll(
const Fix &RemoveAllUnused,
const Fix &AddAllMissing) {
282 FixAll.
Message =
"fix all includes";
284 for (
const auto &F : RemoveAllUnused.Edits)
285 FixAll.Edits.push_back(F);
286 for (
const auto &F : AddAllMissing.Edits)
287 FixAll.Edits.push_back(F);
291std::vector<const Inclusion *>
293 const llvm::DenseSet<IncludeStructure::HeaderID> &ReferencedFiles,
294 bool AnalyzeAngledIncludes) {
296 std::vector<const Inclusion *> Unused;
297 for (
const Inclusion &MFI :
AST.getIncludeStructure().MainFileIncludes) {
301 if (ReferencedFiles.contains(IncludeID))
303 if (!mayConsiderUnused(MFI,
AST, &
AST.getPragmaIncludes(),
304 AnalyzeAngledIncludes)) {
305 dlog(
"{0} was not used, but is not eligible to be diagnosed as unused",
309 Unused.push_back(&MFI);
316std::vector<include_cleaner::SymbolReference>
318 const auto &SM =
AST.getSourceManager();
319 auto &PP =
AST.getPreprocessor();
320 std::vector<include_cleaner::SymbolReference> Macros;
321 for (
const auto &[_, Refs] :
AST.getMacros().MacroRefs) {
322 for (
const auto &
Ref : Refs) {
323 auto Loc = SM.getComposedLoc(SM.getMainFileID(),
Ref.StartOffset);
324 const auto *Tok =
AST.getTokens().spelledTokenContaining(Loc);
330 auto DefLoc =
Macro->NameLoc;
331 if (!DefLoc.isValid())
334 {include_cleaner::Macro{PP.getIdentifierInfo(Tok->text(SM)),
337 Ref.InConditionalDirective ? include_cleaner::RefType::Ambiguous
338 : include_cleaner::RefType::Explicit});
346 auto &SM =
AST.getSourceManager();
348 include_cleaner::Includes ConvertedIncludes;
351 for (
const auto &Dir :
AST.getIncludeStructure().SearchPathsCanonical)
352 ConvertedIncludes.addSearchDirectory(Dir);
354 for (
const Inclusion &Inc :
AST.getIncludeStructure().MainFileIncludes) {
355 include_cleaner::Include TransformedInc;
356 llvm::StringRef WrittenRef = llvm::StringRef(Inc.Written);
357 TransformedInc.Spelled = WrittenRef.trim(
"\"<>");
358 TransformedInc.HashLocation =
359 SM.getComposedLoc(SM.getMainFileID(), Inc.HashOffset);
360 TransformedInc.Line = Inc.HashLine + 1;
361 TransformedInc.Angled = WrittenRef.starts_with(
"<");
364 auto FE = SM.getFileManager().getFileRef(Inc.Resolved);
366 elog(
"IncludeCleaner: Failed to get an entry for resolved path '{0}' "
367 "from include {1} : {2}",
368 Inc.Resolved, Inc.Written, FE.takeError());
371 TransformedInc.Resolved = *FE;
372 ConvertedIncludes.add(std::move(TransformedInc));
374 return ConvertedIncludes;
377IncludeCleanerFindings
380 if (
AST.getLangOpts().ObjC)
382 const auto &SM =
AST.getSourceManager();
384 const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID());
387 std::vector<include_cleaner::SymbolReference> Macros =
389 std::vector<MissingIncludeDiagInfo> MissingIncludes;
390 llvm::DenseSet<IncludeStructure::HeaderID> Used;
392 OptionalDirectoryEntryRef ResourceDir =
AST.getPreprocessor()
393 .getHeaderSearchInfo()
396 include_cleaner::walkUsed(
397 AST.getLocalTopLevelDecls(), Macros,
398 &
AST.getPragmaIncludes(),
AST.getPreprocessor(),
399 [&](
const include_cleaner::SymbolReference &
Ref,
400 llvm::ArrayRef<include_cleaner::Header> Providers) {
401 bool Satisfied = false;
402 for (const auto &H : Providers) {
403 if (H.kind() == include_cleaner::Header::Physical &&
404 (H.physical() == MainFile || H.physical() == PreamblePatch ||
405 H.physical().getDir() == ResourceDir)) {
409 for (auto *Inc : ConvertedIncludes.match(H)) {
412 AST.getIncludeStructure().getID(&Inc->Resolved->getFileEntry());
413 assert(HeaderID.has_value() &&
414 "ConvertedIncludes only contains resolved includes.");
415 Used.insert(*HeaderID);
419 if (Satisfied || Providers.empty() ||
420 Ref.RT != include_cleaner::RefType::Explicit)
428 std::string Spelling = include_cleaner::spellHeader(
429 {Providers.front(), AST.getPreprocessor().getHeaderSearchInfo(),
432 ConvertedIncludes.match(include_cleaner::Header{Spelling})) {
435 AST.getIncludeStructure().getID(&Inc->Resolved->getFileEntry());
436 assert(HeaderID.has_value() &&
437 "ConvertedIncludes only contains resolved includes.");
438 Used.insert(*HeaderID);
450 auto Loc = SM.getFileLoc(
Ref.RefLocation);
453 while (SM.getFileID(Loc) != SM.getMainFileID())
454 Loc = SM.getIncludeLoc(SM.getFileID(Loc));
455 auto TouchingTokens =
456 syntax::spelledTokensTouching(Loc,
AST.getTokens());
457 assert(!TouchingTokens.empty());
462 Ref.Target, TouchingTokens.back().range(SM), Providers};
463 MissingIncludes.push_back(std::move(DiagInfo));
468 llvm::stable_sort(MissingIncludes, [](
const MissingIncludeDiagInfo &LHS,
469 const MissingIncludeDiagInfo &RHS) {
471 if (LHS.SymRefRange != RHS.SymRefRange) {
474 return LHS.SymRefRange.beginOffset() < RHS.SymRefRange.beginOffset();
478 using MapInfo = llvm::DenseMapInfo<include_cleaner::Symbol>;
479 return MapInfo::getHashValue(LHS.Symbol) <
480 MapInfo::getHashValue(RHS.Symbol);
482 MissingIncludes.erase(llvm::unique(MissingIncludes), MissingIncludes.end());
483 std::vector<const Inclusion *> UnusedIncludes =
484 getUnused(
AST, Used, AnalyzeAngledIncludes);
485 return {std::move(UnusedIncludes), std::move(MissingIncludes)};
489 const include_cleaner::Includes &Includes,
490 llvm::ArrayRef<include_cleaner::Header> Providers) {
491 for (
const auto &H : Providers) {
492 auto Matches = Includes.match(H);
493 for (
const include_cleaner::Include *Match : Matches)
494 if (Match->Line ==
unsigned(Inc.
HashLine + 1))
496 if (!Matches.empty())
507 trace::Span Tracer(
"IncludeCleaner::issueIncludeCleanerDiagnostics");
508 std::vector<Diag> UnusedIncludes = generateUnusedIncludeDiagnostics(
510 std::optional<Fix> RemoveAllUnused = removeAllUnusedIncludes(UnusedIncludes);
512 std::vector<Diag> MissingIncludeDiags = generateMissingIncludeDiagnostics(
515 std::optional<Fix> AddAllMissing = addAllMissingIncludes(MissingIncludeDiags);
517 std::optional<Fix> FixAll;
518 if (RemoveAllUnused && AddAllMissing)
519 FixAll = fixAll(*RemoveAllUnused, *AddAllMissing);
524 Out->Fixes.push_back(*F);
526 for (
auto &
Diag : MissingIncludeDiags) {
527 AddBatchFix(MissingIncludeDiags.size() > 1 ? AddAllMissing : std::nullopt,
529 AddBatchFix(FixAll, &
Diag);
531 for (
auto &
Diag : UnusedIncludes) {
532 AddBatchFix(UnusedIncludes.size() > 1 ? RemoveAllUnused : std::nullopt,
534 AddBatchFix(FixAll, &
Diag);
537 auto Result = std::move(MissingIncludeDiags);
538 llvm::move(UnusedIncludes, std::back_inserter(Result));
Include Cleaner is clangd functionality for providing diagnostics for misuse of transitive headers an...
Stores and provides access to parsed AST.
Stores information required to parse a TU using a (possibly stale) Baseline preamble.
static OptionalFileEntryRef getPatchEntry(llvm::StringRef MainFilePath, const SourceManager &SM)
Returns the FileEntry for the preamble patch of MainFilePath in SM, if any.
Wrapper for vfs::FileSystem for use in multithreaded programs like clangd.
Records an event whose duration is the lifetime of the Span object.
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
Position offsetToPosition(llvm::StringRef Code, size_t Offset)
Turn an offset in Code into a [line, column] pair.
std::vector< include_cleaner::SymbolReference > collectMacroReferences(ParsedAST &AST)
include_cleaner::Includes convertIncludes(const ParsedAST &AST)
Converts the clangd include representation to include-cleaner include representation.
std::optional< DefinedMacro > locateMacroAt(const syntax::Token &SpelledTok, Preprocessor &PP)
Gets the macro referenced by SpelledTok.
llvm::ArrayRef< std::function< bool(llvm::StringRef)> > HeaderFilter
bool isPreferredProvider(const Inclusion &Inc, const include_cleaner::Includes &Includes, llvm::ArrayRef< include_cleaner::Header > Providers)
Whether this include is considered to provide a particular symbol.
IncludeCleanerFindings computeIncludeCleanerFindings(ParsedAST &AST, bool AnalyzeAngledIncludes)
llvm::StringRef PathRef
A typedef to represent a ref to file path.
@ Unnecessary
Unused or unnecessary code.
std::vector< Diag > issueIncludeCleanerDiagnostics(ParsedAST &AST, llvm::StringRef Code, const IncludeCleanerFindings &Findings, const ThreadsafeFS &TFS, HeaderFilter IgnoreHeaders, HeaderFilter AngledHeaders, HeaderFilter QuotedHeaders)
clangd::Range rangeTillEOL(llvm::StringRef Code, unsigned HashOffset)
Returns the range starting at offset and spanning the whole line.
void elog(const char *Fmt, Ts &&... Vals)
TextEdit replacementToEdit(llvm::StringRef Code, const tooling::Replacement &R)
format::FormatStyle getFormatStyleForFile(llvm::StringRef File, llvm::StringRef Content, const ThreadsafeFS &TFS, bool FormatFile)
Choose the clang-format style we should apply to a certain file.
A top-level diagnostic that may have Notes and Fixes.
std::vector< Fix > Fixes
Alternative fixes for this diagnostic, one should be chosen.
A set of edits generated for a single file.
Represents a single fix-it that editor can apply to fix the error.
std::string Message
Message for the fix-it.
std::vector< const Inclusion * > UnusedIncludes
std::vector< MissingIncludeDiagInfo > MissingIncludes
Represents a symbol occurrence in the source file.