| 1 |
//===--- IncludeCleaner.cpp - standalone tool for include analysis --------===// |
| 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 "AnalysisInternal.h" |
| 10 |
#include "clang-include-cleaner/Analysis.h" |
| 11 |
#include "clang-include-cleaner/Record.h" |
| 12 |
#include "clang/Frontend/CompilerInstance.h" |
| 13 |
#include "clang/Frontend/FrontendAction.h" |
| 14 |
#include "clang/Lex/Preprocessor.h" |
| 15 |
#include "clang/Tooling/CommonOptionsParser.h" |
| 16 |
#include "clang/Tooling/Tooling.h" |
| 17 |
#include "llvm/ADT/StringRef.h" |
| 18 |
#include "llvm/Support/CommandLine.h" |
| 19 |
#include "llvm/Support/Signals.h" |
| 20 |
#include "llvm/Support/raw_ostream.h" |
| 21 |
|
| 22 |
namespace clang { |
| 23 |
namespace include_cleaner { |
| 24 |
namespace { |
| 25 |
namespace cl = llvm::cl; |
| 26 |
|
| 27 |
llvm::StringRef Overview = llvm::StringLiteral(R"( |
| 28 |
clang-include-cleaner analyzes the #include directives in source code. |
| 29 |
|
| 30 |
It suggests removing headers that the code is not using. |
| 31 |
It suggests inserting headers that the code relies on, but does not include. |
| 32 |
These changes make the file more self-contained and (at scale) make the codebase |
| 33 |
easier to reason about and modify. |
| 34 |
|
| 35 |
The tool operates on *working* source code. This means it can suggest including |
| 36 |
headers that are only indirectly included, but cannot suggest those that are |
| 37 |
missing entirely. (clang-include-fixer can do this). |
| 38 |
)") |
| 39 |
.trim(); |
| 40 |
|
| 41 |
cl::OptionCategory IncludeCleaner("clang-include-cleaner"); |
| 42 |
|
| 43 |
cl::opt<std::string> HTMLReportPath{ |
| 44 |
"html", |
| 45 |
cl::desc("Specify an output filename for an HTML report. " |
| 46 |
"This describes both recommendations and reasons for changes."), |
| 47 |
cl::cat(IncludeCleaner), |
| 48 |
}; |
| 49 |
|
| 50 |
enum class PrintStyle { Changes, Final }; |
| 51 |
cl::opt<PrintStyle> Print{ |
| 52 |
"print", |
| 53 |
cl::values( |
| 54 |
clEnumValN(PrintStyle::Changes, "changes", "Print symbolic changes"), |
| 55 |
clEnumValN(PrintStyle::Final, "", "Print final code")), |
| 56 |
cl::ValueOptional, |
| 57 |
cl::init(PrintStyle::Final), |
| 58 |
cl::desc("Print the list of headers to insert and remove"), |
| 59 |
cl::cat(IncludeCleaner), |
| 60 |
}; |
| 61 |
|
| 62 |
cl::opt<bool> Edit{ |
| 63 |
"edit", |
| 64 |
cl::desc("Apply edits to analyzed source files"), |
| 65 |
cl::cat(IncludeCleaner), |
| 66 |
}; |
| 67 |
|
| 68 |
cl::opt<bool> Insert{ |
| 69 |
"insert", |
| 70 |
cl::desc("Allow header insertions"), |
| 71 |
cl::init(true), |
| 72 |
cl::cat(IncludeCleaner), |
| 73 |
}; |
| 74 |
cl::opt<bool> Remove{ |
| 75 |
"remove", |
| 76 |
cl::desc("Allow header removals"), |
| 77 |
cl::init(true), |
| 78 |
cl::cat(IncludeCleaner), |
| 79 |
}; |
| 80 |
|
| 81 |
std::atomic<unsigned> Errors = ATOMIC_VAR_INIT(0); |
| 82 |
|
| 83 |
format::FormatStyle getStyle(llvm::StringRef Filename) { |
| 84 |
auto S = format::getStyle(format::DefaultFormatStyle, Filename, |
| 85 |
format::DefaultFallbackStyle); |
| 86 |
if (!S || !S->isCpp()) { |
| 87 |
consumeError(S.takeError()); |
| 88 |
return format::getLLVMStyle(); |
| 89 |
} |
| 90 |
return std::move(*S); |
| 91 |
} |
| 92 |
|
| 93 |
class Action : public clang::ASTFrontendAction { |
| 94 |
RecordedAST AST; |
| 95 |
RecordedPP PP; |
| 96 |
PragmaIncludes PI; |
| 97 |
|
| 98 |
void ExecuteAction() override { |
| 99 |
auto &P = getCompilerInstance().getPreprocessor(); |
| 100 |
P.addPPCallbacks(PP.record(P)); |
| 101 |
PI.record(getCompilerInstance()); |
| 102 |
ASTFrontendAction::ExecuteAction(); |
| 103 |
} |
| 104 |
|
| 105 |
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, |
| 106 |
StringRef File) override { |
| 107 |
return AST.record(); |
| 108 |
} |
| 109 |
|
| 110 |
void EndSourceFile() override { |
| 111 |
if (!HTMLReportPath.empty()) |
| 112 |
writeHTML(); |
| 113 |
|
| 114 |
const auto &SM = getCompilerInstance().getSourceManager(); |
| 115 |
auto &HS = getCompilerInstance().getPreprocessor().getHeaderSearchInfo(); |
| 116 |
llvm::StringRef Path = |
| 117 |
SM.getFileEntryForID(SM.getMainFileID())->tryGetRealPathName(); |
| 118 |
assert(!Path.empty() && "Main file path not known?"); |
| 119 |
llvm::StringRef Code = SM.getBufferData(SM.getMainFileID()); |
| 120 |
|
| 121 |
auto Results = |
| 122 |
analyze(AST.Roots, PP.MacroReferences, PP.Includes, &PI, SM, HS); |
| 123 |
if (!Insert) |
| 124 |
Results.Missing.clear(); |
| 125 |
if (!Remove) |
| 126 |
Results.Unused.clear(); |
| 127 |
std::string Final = fixIncludes(Results, Code, getStyle(Path)); |
| 128 |
|
| 129 |
if (Print.getNumOccurrences()) { |
| 130 |
switch (Print) { |
| 131 |
case PrintStyle::Changes: |
| 132 |
for (const Include *I : Results.Unused) |
| 133 |
llvm::outs() << "- " << I->quote() << " @Line:" << I->Line << "\n"; |
| 134 |
for (const auto &I : Results.Missing) |
| 135 |
llvm::outs() << "+ " << I << "\n"; |
| 136 |
break; |
| 137 |
case PrintStyle::Final: |
| 138 |
llvm::outs() << Final; |
| 139 |
break; |
| 140 |
} |
| 141 |
} |
| 142 |
|
| 143 |
if (Edit) { |
| 144 |
if (auto Err = llvm::writeToOutput( |
| 145 |
Path, [&](llvm::raw_ostream &OS) -> llvm::Error { |
| 146 |
OS << Final; |
| 147 |
return llvm::Error::success(); |
| 148 |
})) { |
| 149 |
llvm::errs() << "Failed to apply edits to " << Path << ": " |
| 150 |
<< toString(std::move(Err)) << "\n"; |
| 151 |
++Errors; |
| 152 |
} |
| 153 |
} |
| 154 |
} |
| 155 |
|
| 156 |
void writeHTML() { |
| 157 |
std::error_code EC; |
| 158 |
llvm::raw_fd_ostream OS(HTMLReportPath, EC); |
| 159 |
if (EC) { |
| 160 |
llvm::errs() << "Unable to write HTML report to " << HTMLReportPath |
| 161 |
<< ": " << EC.message() << "\n"; |
| 162 |
++Errors; |
| 163 |
return; |
| 164 |
} |
| 165 |
writeHTMLReport( |
| 166 |
AST.Ctx->getSourceManager().getMainFileID(), PP.Includes, AST.Roots, |
| 167 |
PP.MacroReferences, *AST.Ctx, |
| 168 |
getCompilerInstance().getPreprocessor().getHeaderSearchInfo(), &PI, OS); |
| 169 |
} |
| 170 |
}; |
| 171 |
|
| 172 |
} // namespace |
| 173 |
} // namespace include_cleaner |
| 174 |
} // namespace clang |
| 175 |
|
| 176 |
int main(int argc, const char **argv) { |
| 177 |
using namespace clang::include_cleaner; |
| 178 |
|
| 179 |
llvm::sys::PrintStackTraceOnErrorSignal(argv[0]); |
| 180 |
auto OptionsParser = |
| 181 |
clang::tooling::CommonOptionsParser::create(argc, argv, IncludeCleaner); |
| 182 |
if (!OptionsParser) { |
| 183 |
llvm::errs() << toString(OptionsParser.takeError()); |
| 184 |
return 1; |
| 185 |
} |
| 186 |
|
| 187 |
if (OptionsParser->getSourcePathList().size() != 1) { |
| 188 |
std::vector<cl::Option *> IncompatibleFlags = {&HTMLReportPath, &Print}; |
| 189 |
for (const auto *Flag : IncompatibleFlags) { |
| 190 |
if (Flag->getNumOccurrences()) |
| 191 |
llvm::errs() << "-" << Flag->ArgStr << " requires a single input file"; |
| 192 |
return 1; |
| 193 |
} |
| 194 |
} |
| 195 |
auto Factory = clang::tooling::newFrontendActionFactory<Action>(); |
| 196 |
return clang::tooling::ClangTool(OptionsParser->getCompilations(), |
| 197 |
OptionsParser->getSourcePathList()) |
| 198 |
.run(Factory.get()) || |
| 199 |
Errors != 0; |
| 200 |
} |