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"
50struct MissingIncludeInfo {
51 include_cleaner::SymbolReference
SymRef;
59 IgnoreHeaders(utils::options::parseStringList(
60 Options.getLocalOrGlobal(
"IgnoreHeaders",
""))),
62 Options.getLocalOrGlobal(
"DeduplicateFindings", true)) {
63 for (
const auto &Header : IgnoreHeaders) {
64 if (!llvm::Regex{Header}.isValid())
66 std::string HeaderSuffix{Header.str()};
67 if (!Header.ends_with(
"$"))
69 IgnoreHeadersRegex.emplace_back(HeaderSuffix);
76 Options.
store(Opts,
"DeduplicateFindings", DeduplicateFindings);
80 const LangOptions &LangOpts)
const {
81 return !LangOpts.ObjC;
85 Finder->addMatcher(translationUnitDecl().bind(
"top"),
this);
90 Preprocessor *ModuleExpanderPP) {
91 PP->addPPCallbacks(RecordedPreprocessor.record(*PP));
93 RecordedPI.record(*PP);
96bool IncludeCleanerCheck::shouldIgnore(
const include_cleaner::Header &H) {
97 return llvm::any_of(IgnoreHeadersRegex, [&H](
const llvm::Regex &R) {
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());
106 llvm_unreachable(
"Unknown Header kind.");
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())))
120 MainFileDecls.push_back(D);
122 llvm::DenseSet<include_cleaner::Symbol> SeenSymbols;
123 const DirectoryEntry *ResourceDir =
124 PP->getHeaderSearchInfo().getModuleMap().getBuiltinDir();
127 walkUsed(MainFileDecls, RecordedPreprocessor.MacroReferences, &RecordedPI,
129 [&](
const include_cleaner::SymbolReference &Ref,
130 llvm::ArrayRef<include_cleaner::Header> Providers) {
142 if (DeduplicateFindings && !SeenSymbols.insert(Ref.Target).second)
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)) {
153 for (const include_cleaner::Include *I :
154 RecordedPreprocessor.Includes.match(H)) {
159 if (!Satisfied && !Providers.empty() &&
160 Ref.RT == include_cleaner::RefType::Explicit &&
161 !shouldIgnore(Providers.front()))
162 Missing.push_back({Ref, Providers.front()});
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)
170 if (RecordedPI.shouldKeep(*I.Resolved))
174 if (
auto PHeader = RecordedPI.getPublic(*I.Resolved); !PHeader.empty()) {
175 PHeader = PHeader.trim(
"<>\"");
179 if (getCurrentMainFile().endswith(PHeader))
185 [Resolved = (*I.Resolved).getFileEntry().tryGetRealPathName()](
186 const llvm::Regex &R) { return R.match(Resolved); }))
187 Unused.push_back(&I);
190 llvm::StringRef
Code = SM->getBufferData(SM->getMainFileID());
192 format::getStyle(format::DefaultFormatStyle, getCurrentMainFile(),
193 format::DefaultFallbackStyle,
Code,
194 &SM->getFileManager().getVirtualFileSystem());
196 FileStyle = format::getLLVMStyle();
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)));
207 tooling::HeaderIncludes HeaderIncludes(getCurrentMainFile(),
Code,
208 FileStyle->IncludeStyle);
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(
"<");
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());
const FunctionDecl * Decl
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