clang-tools 18.0.0git
IncludeCleanerCheck.cpp
Go to the documentation of this file.
1//===--- IncludeCleanerCheck.cpp - clang-tidy -----------------------------===//
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
10#include "../ClangTidyCheck.h"
11#include "../ClangTidyDiagnosticConsumer.h"
12#include "../ClangTidyOptions.h"
13#include "../utils/OptionsUtils.h"
14#include "clang-include-cleaner/Analysis.h"
15#include "clang-include-cleaner/IncludeSpeller.h"
16#include "clang-include-cleaner/Record.h"
17#include "clang-include-cleaner/Types.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/ASTMatchers/ASTMatchFinder.h"
22#include "clang/ASTMatchers/ASTMatchers.h"
23#include "clang/Basic/Diagnostic.h"
24#include "clang/Basic/FileEntry.h"
25#include "clang/Basic/LLVM.h"
26#include "clang/Basic/LangOptions.h"
27#include "clang/Basic/SourceLocation.h"
28#include "clang/Format/Format.h"
29#include "clang/Lex/HeaderSearchOptions.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Tooling/Core/Replacement.h"
32#include "clang/Tooling/Inclusions/HeaderIncludes.h"
33#include "llvm/ADT/DenseSet.h"
34#include "llvm/ADT/STLExtras.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/StringRef.h"
37#include "llvm/ADT/StringSet.h"
38#include "llvm/Support/ErrorHandling.h"
39#include "llvm/Support/Path.h"
40#include "llvm/Support/Regex.h"
41#include <optional>
42#include <string>
43#include <vector>
44
45using namespace clang::ast_matchers;
46
47namespace clang::tidy::misc {
48
49namespace {
50struct MissingIncludeInfo {
51 include_cleaner::SymbolReference SymRef;
52 include_cleaner::Header Missing;
53};
54} // namespace
55
57 ClangTidyContext *Context)
58 : ClangTidyCheck(Name, Context),
59 IgnoreHeaders(utils::options::parseStringList(
60 Options.getLocalOrGlobal("IgnoreHeaders", ""))),
61 DeduplicateFindings(
62 Options.getLocalOrGlobal("DeduplicateFindings", true)) {
63 for (const auto &Header : IgnoreHeaders) {
64 if (!llvm::Regex{Header}.isValid())
65 configurationDiag("Invalid ignore headers regex '%0'") << Header;
66 std::string HeaderSuffix{Header.str()};
67 if (!Header.ends_with("$"))
68 HeaderSuffix += "$";
69 IgnoreHeadersRegex.emplace_back(HeaderSuffix);
70 }
71}
72
74 Options.store(Opts, "IgnoreHeaders",
76 Options.store(Opts, "DeduplicateFindings", DeduplicateFindings);
77}
78
80 const LangOptions &LangOpts) const {
81 return !LangOpts.ObjC;
82}
83
84void IncludeCleanerCheck::registerMatchers(MatchFinder *Finder) {
85 Finder->addMatcher(translationUnitDecl().bind("top"), this);
86}
87
88void IncludeCleanerCheck::registerPPCallbacks(const SourceManager &SM,
89 Preprocessor *PP,
90 Preprocessor *ModuleExpanderPP) {
91 PP->addPPCallbacks(RecordedPreprocessor.record(*PP));
92 this->PP = PP;
93 RecordedPI.record(*PP);
94}
95
96bool IncludeCleanerCheck::shouldIgnore(const include_cleaner::Header &H) {
97 return llvm::any_of(IgnoreHeadersRegex, [&H](const llvm::Regex &R) {
98 switch (H.kind()) {
99 case include_cleaner::Header::Standard:
100 return R.match(H.standard().name());
101 case include_cleaner::Header::Verbatim:
102 return R.match(H.verbatim());
103 case include_cleaner::Header::Physical:
104 return R.match(H.physical().getFileEntry().tryGetRealPathName());
105 }
106 llvm_unreachable("Unknown Header kind.");
107 });
108}
109
110void IncludeCleanerCheck::check(const MatchFinder::MatchResult &Result) {
111 const SourceManager *SM = Result.SourceManager;
112 const FileEntry *MainFile = SM->getFileEntryForID(SM->getMainFileID());
113 llvm::DenseSet<const include_cleaner::Include *> Used;
114 std::vector<MissingIncludeInfo> Missing;
115 llvm::SmallVector<Decl *> MainFileDecls;
116 for (Decl *D : Result.Nodes.getNodeAs<TranslationUnitDecl>("top")->decls()) {
117 if (!SM->isWrittenInMainFile(SM->getExpansionLoc(D->getLocation())))
118 continue;
119 // FIXME: Filter out implicit template specializations.
120 MainFileDecls.push_back(D);
121 }
122 llvm::DenseSet<include_cleaner::Symbol> SeenSymbols;
123 const DirectoryEntry *ResourceDir =
124 PP->getHeaderSearchInfo().getModuleMap().getBuiltinDir();
125 // FIXME: Find a way to have less code duplication between include-cleaner
126 // analysis implementation and the below code.
127 walkUsed(MainFileDecls, RecordedPreprocessor.MacroReferences, &RecordedPI,
128 *PP,
129 [&](const include_cleaner::SymbolReference &Ref,
130 llvm::ArrayRef<include_cleaner::Header> Providers) {
131 // Process each symbol once to reduce noise in the findings.
132 // Tidy checks are used in two different workflows:
133 // - Ones that show all the findings for a given file. For such
134 // workflows there is not much point in showing all the occurences,
135 // as one is enough to indicate the issue.
136 // - Ones that show only the findings on changed pieces. For such
137 // workflows it's useful to show findings on every reference of a
138 // symbol as otherwise tools might give incosistent results
139 // depending on the parts of the file being edited. But it should
140 // still help surface findings for "new violations" (i.e.
141 // dependency did not exist in the code at all before).
142 if (DeduplicateFindings && !SeenSymbols.insert(Ref.Target).second)
143 return;
144 bool Satisfied = false;
145 for (const include_cleaner::Header &H : Providers) {
146 if (H.kind() == include_cleaner::Header::Physical &&
147 (H.physical() == MainFile ||
148 H.physical().getDir() == ResourceDir)) {
149 Satisfied = true;
150 continue;
151 }
152
153 for (const include_cleaner::Include *I :
154 RecordedPreprocessor.Includes.match(H)) {
155 Used.insert(I);
156 Satisfied = true;
157 }
158 }
159 if (!Satisfied && !Providers.empty() &&
160 Ref.RT == include_cleaner::RefType::Explicit &&
161 !shouldIgnore(Providers.front()))
162 Missing.push_back({Ref, Providers.front()});
163 });
164
165 std::vector<const include_cleaner::Include *> Unused;
166 for (const include_cleaner::Include &I :
167 RecordedPreprocessor.Includes.all()) {
168 if (Used.contains(&I) || !I.Resolved || I.Resolved->getDir() == ResourceDir)
169 continue;
170 if (RecordedPI.shouldKeep(*I.Resolved))
171 continue;
172 // Check if main file is the public interface for a private header. If so
173 // we shouldn't diagnose it as unused.
174 if (auto PHeader = RecordedPI.getPublic(*I.Resolved); !PHeader.empty()) {
175 PHeader = PHeader.trim("<>\"");
176 // Since most private -> public mappings happen in a verbatim way, we
177 // check textually here. This might go wrong in presence of symlinks or
178 // header mappings. But that's not different than rest of the places.
179 if (getCurrentMainFile().endswith(PHeader))
180 continue;
181 }
182
183 if (llvm::none_of(
184 IgnoreHeadersRegex,
185 [Resolved = (*I.Resolved).getFileEntry().tryGetRealPathName()](
186 const llvm::Regex &R) { return R.match(Resolved); }))
187 Unused.push_back(&I);
188 }
189
190 llvm::StringRef Code = SM->getBufferData(SM->getMainFileID());
191 auto FileStyle =
192 format::getStyle(format::DefaultFormatStyle, getCurrentMainFile(),
193 format::DefaultFallbackStyle, Code,
194 &SM->getFileManager().getVirtualFileSystem());
195 if (!FileStyle)
196 FileStyle = format::getLLVMStyle();
197
198 for (const auto *Inc : Unused) {
199 diag(Inc->HashLocation, "included header %0 is not used directly")
200 << llvm::sys::path::filename(Inc->Spelled,
201 llvm::sys::path::Style::posix)
202 << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
203 SM->translateLineCol(SM->getMainFileID(), Inc->Line, 1),
204 SM->translateLineCol(SM->getMainFileID(), Inc->Line + 1, 1)));
205 }
206
207 tooling::HeaderIncludes HeaderIncludes(getCurrentMainFile(), Code,
208 FileStyle->IncludeStyle);
209 // Deduplicate insertions when running in bulk fix mode.
210 llvm::StringSet<> InsertedHeaders{};
211 for (const auto &Inc : Missing) {
212 std::string Spelling = include_cleaner::spellHeader(
213 {Inc.Missing, PP->getHeaderSearchInfo(), MainFile});
214 bool Angled = llvm::StringRef{Spelling}.starts_with("<");
215 // We might suggest insertion of an existing include in edge cases, e.g.,
216 // include is present in a PP-disabled region, or spelling of the header
217 // turns out to be the same as one of the unresolved includes in the
218 // main file.
219 if (auto Replacement =
220 HeaderIncludes.insert(llvm::StringRef{Spelling}.trim("\"<>"),
221 Angled, tooling::IncludeDirective::Include)) {
222 DiagnosticBuilder DB =
223 diag(SM->getSpellingLoc(Inc.SymRef.RefLocation),
224 "no header providing \"%0\" is directly included")
225 << Inc.SymRef.Target.name();
226 if (areDiagsSelfContained() ||
227 InsertedHeaders.insert(Replacement->getReplacementText()).second) {
228 DB << FixItHint::CreateInsertion(
229 SM->getComposedLoc(SM->getMainFileID(), Replacement->getOffset()),
230 Replacement->getReplacementText());
231 }
232 }
233 }
234}
235
236} // namespace clang::tidy::misc
const FunctionDecl * Decl
std::string Code
llvm::StringRef Name
std::string MainFile
include_cleaner::Header Missing
include_cleaner::SymbolReference SymRef
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Base class for all clang-tidy checks.
DiagnosticBuilder configurationDiag(StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning) const
Adds a diagnostic to report errors in the check's configuration.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
bool isLanguageVersionSupported(const LangOptions &LangOpts) const override
Override this to disable registering matchers and PP callbacks if an invalid language version is bein...
IncludeCleanerCheck(StringRef Name, ClangTidyContext *Context)
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
Override this to register PPCallbacks in the preprocessor.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
llvm::StringMap< ClangTidyValue > OptionMap