clang-tools 24.0.0git
IncludeCleanerCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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"
12#include "../ClangTidyOptions.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/Preprocessor.h"
30#include "clang/Tooling/Core/Replacement.h"
31#include "clang/Tooling/Inclusions/HeaderIncludes.h"
32#include "clang/Tooling/Inclusions/StandardLibrary.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(
60 utils::options::parseStringList(Options.get("IgnoreHeaders", ""))),
61 DeduplicateFindings(Options.get("DeduplicateFindings", true)),
62 UnusedIncludes(Options.get("UnusedIncludes", true)),
63 MissingIncludes(Options.get("MissingIncludes", true)) {
64 for (const auto &Header : IgnoreHeaders) {
65 if (!llvm::Regex{Header}.isValid())
66 configurationDiag("Invalid ignore headers regex '%0'") << Header;
67 std::string HeaderSuffix{Header.str()};
68 if (!Header.ends_with('$'))
69 HeaderSuffix += '$';
70 IgnoreHeadersRegex.emplace_back(HeaderSuffix);
71 }
72
73 if (UnusedIncludes == false && MissingIncludes == false)
74 this->configurationDiag("The check 'misc-include-cleaner' will not "
75 "perform any analysis because 'UnusedIncludes' and "
76 "'MissingIncludes' are both false.");
77}
78
80 Options.store(Opts, "IgnoreHeaders",
82 Options.store(Opts, "DeduplicateFindings", DeduplicateFindings);
83 Options.store(Opts, "UnusedIncludes", UnusedIncludes);
84 Options.store(Opts, "MissingIncludes", MissingIncludes);
85}
86
88 const LangOptions &LangOpts) const {
89 return !LangOpts.ObjC;
90}
91
92void IncludeCleanerCheck::registerMatchers(MatchFinder *Finder) {
93 Finder->addMatcher(translationUnitDecl().bind("top"), this);
94}
95
96void IncludeCleanerCheck::registerPPCallbacks(const SourceManager &SM,
97 Preprocessor *PP,
98 Preprocessor *ModuleExpanderPP) {
99 PP->addPPCallbacks(RecordedPreprocessor.record(*PP));
100 this->PP = PP;
101 RecordedPI.record(*PP);
102}
103
104bool IncludeCleanerCheck::shouldIgnore(const include_cleaner::Header &H) {
105 return llvm::any_of(IgnoreHeadersRegex, [&H](const llvm::Regex &R) {
106 switch (H.kind()) {
107 case include_cleaner::Header::Standard:
108 // We don't trim angle brackets around standard library headers
109 // deliberately, so that they are only matched as <vector>, otherwise
110 // having just `.*/vector` might yield false positives.
111 return R.match(H.standard().name());
112 case include_cleaner::Header::Verbatim:
113 return R.match(H.verbatim().trim("<>\""));
114 case include_cleaner::Header::Physical: {
115 const StringRef Path = H.physical().getFileEntry().tryGetRealPathName();
116 return R.match(Path) || R.match(llvm::sys::path::convert_to_slash(Path));
117 }
118 }
119 llvm_unreachable("Unknown Header kind.");
120 });
121}
122
123void IncludeCleanerCheck::check(const MatchFinder::MatchResult &Result) {
124 const SourceManager *SM = Result.SourceManager;
125 const FileEntry *MainFile = SM->getFileEntryForID(SM->getMainFileID());
126 llvm::DenseSet<const include_cleaner::Include *> Used;
127 std::vector<MissingIncludeInfo> Missing;
128 SmallVector<Decl *> MainFileDecls;
129 for (Decl *D : Result.Nodes.getNodeAs<TranslationUnitDecl>("top")->decls()) {
130 if (!SM->isWrittenInMainFile(SM->getExpansionLoc(D->getLocation())))
131 continue;
132 // FIXME: Filter out implicit template specializations.
133 MainFileDecls.push_back(D);
134 }
135 llvm::DenseSet<include_cleaner::Symbol> SeenSymbols;
136 OptionalDirectoryEntryRef ResourceDir =
137 PP->getHeaderSearchInfo().getModuleMap().getBuiltinDir();
138 // FIXME: Find a way to have less code duplication between include-cleaner
139 // analysis implementation and the below code.
140 walkUsed(MainFileDecls, RecordedPreprocessor.MacroReferences, &RecordedPI,
141 *PP,
142 [&](const include_cleaner::SymbolReference &Ref,
143 llvm::ArrayRef<include_cleaner::Header> Providers) {
144 // Process each symbol once to reduce noise in the findings.
145 // Tidy checks are used in two different workflows:
146 // - Ones that show all the findings for a given file. For such
147 // workflows there is not much point in showing all the occurences,
148 // as one is enough to indicate the issue.
149 // - Ones that show only the findings on changed pieces. For such
150 // workflows it's useful to show findings on every reference of a
151 // symbol as otherwise tools might give incosistent results
152 // depending on the parts of the file being edited. But it should
153 // still help surface findings for "new violations" (i.e.
154 // dependency did not exist in the code at all before).
155 if (DeduplicateFindings && !SeenSymbols.insert(Ref.Target).second)
156 return;
157 bool Satisfied = false;
158 for (const include_cleaner::Header &H : Providers) {
159 if (H.kind() == include_cleaner::Header::Physical &&
160 (H.physical() == MainFile ||
161 H.physical().getDir() == ResourceDir)) {
162 Satisfied = true;
163 continue;
164 }
165
166 for (const include_cleaner::Include *I :
167 RecordedPreprocessor.Includes.match(H)) {
168 Used.insert(I);
169 Satisfied = true;
170 }
171 }
172 if (!Satisfied && !Providers.empty() &&
173 Ref.RT == include_cleaner::RefType::Explicit &&
174 !shouldIgnore(Providers.front()))
175 Missing.push_back({Ref, Providers.front()});
176 });
177
178 std::vector<const include_cleaner::Include *> Unused;
179 for (const include_cleaner::Include &I :
180 RecordedPreprocessor.Includes.all()) {
181 if (Used.contains(&I) || !I.Resolved || I.Resolved->getDir() == ResourceDir)
182 continue;
183 if (RecordedPI.shouldKeep(*I.Resolved))
184 continue;
185 // Check if main file is the public interface for a private header. If so
186 // we shouldn't diagnose it as unused.
187 if (auto PHeader = RecordedPI.getPublic(*I.Resolved); !PHeader.empty()) {
188 PHeader = PHeader.trim("<>\"");
189 // Since most private -> public mappings happen in a verbatim way, we
190 // check textually here. This might go wrong in presence of symlinks or
191 // header mappings. But that's not different than rest of the places.
192 if (getCurrentMainFile().ends_with(PHeader))
193 continue;
194 }
195 auto StdHeader = tooling::stdlib::Header::named(
196 I.quote(), PP->getLangOpts().CPlusPlus ? tooling::stdlib::Lang::CXX
197 : tooling::stdlib::Lang::C);
198 if (StdHeader && shouldIgnore(*StdHeader))
199 continue;
200 if (shouldIgnore(*I.Resolved))
201 continue;
202 Unused.push_back(&I);
203 }
204
205 const StringRef Code = SM->getBufferData(SM->getMainFileID());
206 auto FileStyle = llvm::expectedToOptional(
207 format::getStyle(format::DefaultFormatStyle, getCurrentMainFile(),
208 format::DefaultFallbackStyle, Code,
209 &SM->getFileManager().getVirtualFileSystem()));
210 if (!FileStyle)
211 FileStyle = format::getLLVMStyle();
212
213 if (UnusedIncludes) {
214 for (const auto *Inc : Unused) {
215 diag(Inc->HashLocation, "included header %0 is not used directly")
216 << llvm::sys::path::filename(Inc->Spelled,
217 llvm::sys::path::Style::posix)
218 << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
219 SM->translateLineCol(SM->getMainFileID(), Inc->Line, 1),
220 SM->translateLineCol(SM->getMainFileID(), Inc->Line + 1, 1)));
221 }
222 }
223
224 if (MissingIncludes) {
225 const tooling::HeaderIncludes HeaderIncludes(getCurrentMainFile(), Code,
226 FileStyle->IncludeStyle);
227 // Deduplicate insertions when running in bulk fix mode.
228 llvm::StringSet<> InsertedHeaders{};
229 for (const auto &Inc : Missing) {
230 const std::string Spelling = include_cleaner::spellHeader(
231 {Inc.Missing, PP->getHeaderSearchInfo(), MainFile});
232 const bool Angled = StringRef{Spelling}.starts_with('<');
233 // We might suggest insertion of an existing include in edge cases, e.g.,
234 // include is present in a PP-disabled region, or spelling of the header
235 // turns out to be the same as one of the unresolved includes in the
236 // main file.
237 if (auto Replacement =
238 HeaderIncludes.insert(StringRef{Spelling}.trim("\"<>"), Angled,
239 tooling::IncludeDirective::Include)) {
240 const DiagnosticBuilder DB =
241 diag(SM->getSpellingLoc(Inc.SymRef.RefLocation),
242 "no header providing \"%0\" is directly included")
243 << Inc.SymRef.Target.name();
244 if (areDiagsSelfContained() ||
245 InsertedHeaders.insert(Replacement->getReplacementText()).second) {
246 DB << FixItHint::CreateInsertion(
247 SM->getComposedLoc(SM->getMainFileID(), Replacement->getOffset()),
248 Replacement->getReplacementText());
249 }
250 }
251 }
252 }
253}
254
255} // namespace clang::tidy::misc
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
bool isLanguageVersionSupported(const LangOptions &LangOpts) const override
IncludeCleanerCheck(StringRef Name, ClangTidyContext *Context)
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
llvm::StringMap< ClangTidyValue > OptionMap