File: IncludeCleaner.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (294 lines) | stat: -rw-r--r-- 9,644 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
//===--- IncludeCleaner.cpp - standalone tool for include analysis --------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "AnalysisInternal.h"
#include "clang-include-cleaner/Analysis.h"
#include "clang-include-cleaner/Record.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/STLFunctionalExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include <functional>
#include <memory>
#include <string>
#include <utility>
#include <vector>

namespace clang {
namespace include_cleaner {
namespace {
namespace cl = llvm::cl;

llvm::StringRef Overview = llvm::StringLiteral(R"(
clang-include-cleaner analyzes the #include directives in source code.

It suggests removing headers that the code is not using.
It suggests inserting headers that the code relies on, but does not include.
These changes make the file more self-contained and (at scale) make the codebase
easier to reason about and modify.

The tool operates on *working* source code. This means it can suggest including
headers that are only indirectly included, but cannot suggest those that are
missing entirely. (clang-include-fixer can do this).
)")
                               .trim();

cl::OptionCategory IncludeCleaner("clang-include-cleaner");

cl::opt<std::string> HTMLReportPath{
    "html",
    cl::desc("Specify an output filename for an HTML report. "
             "This describes both recommendations and reasons for changes."),
    cl::cat(IncludeCleaner),
};

cl::opt<std::string> IgnoreHeaders{
    "ignore-headers",
    cl::desc("A comma-separated list of regexes to match against suffix of a "
             "header, and disable analysis if matched."),
    cl::init(""),
    cl::cat(IncludeCleaner),
};

enum class PrintStyle { Changes, Final };
cl::opt<PrintStyle> Print{
    "print",
    cl::values(
        clEnumValN(PrintStyle::Changes, "changes", "Print symbolic changes"),
        clEnumValN(PrintStyle::Final, "", "Print final code")),
    cl::ValueOptional,
    cl::init(PrintStyle::Final),
    cl::desc("Print the list of headers to insert and remove"),
    cl::cat(IncludeCleaner),
};

cl::opt<bool> Edit{
    "edit",
    cl::desc("Apply edits to analyzed source files"),
    cl::cat(IncludeCleaner),
};

cl::opt<bool> Insert{
    "insert",
    cl::desc("Allow header insertions"),
    cl::init(true),
    cl::cat(IncludeCleaner),
};
cl::opt<bool> Remove{
    "remove",
    cl::desc("Allow header removals"),
    cl::init(true),
    cl::cat(IncludeCleaner),
};

std::atomic<unsigned> Errors = ATOMIC_VAR_INIT(0);

format::FormatStyle getStyle(llvm::StringRef Filename) {
  auto S = format::getStyle(format::DefaultFormatStyle, Filename,
                            format::DefaultFallbackStyle);
  if (!S || !S->isCpp()) {
    consumeError(S.takeError());
    return format::getLLVMStyle();
  }
  return std::move(*S);
}

class Action : public clang::ASTFrontendAction {
public:
  Action(llvm::function_ref<bool(llvm::StringRef)> HeaderFilter)
      : HeaderFilter(HeaderFilter){};

private:
  RecordedAST AST;
  RecordedPP PP;
  PragmaIncludes PI;
  llvm::function_ref<bool(llvm::StringRef)> HeaderFilter;

  bool BeginInvocation(CompilerInstance &CI) override {
    // We only perform include-cleaner analysis. So we disable diagnostics that
    // won't affect our analysis to make the tool more robust against
    // in-development code.
    CI.getLangOpts().ModulesDeclUse = false;
    CI.getLangOpts().ModulesStrictDeclUse = false;
    return true;
  }

  void ExecuteAction() override {
    auto &P = getCompilerInstance().getPreprocessor();
    P.addPPCallbacks(PP.record(P));
    PI.record(getCompilerInstance());
    ASTFrontendAction::ExecuteAction();
  }

  std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
                                                 StringRef File) override {
    return AST.record();
  }

  void EndSourceFile() override {
    const auto &SM = getCompilerInstance().getSourceManager();
    if (SM.getDiagnostics().hasUncompilableErrorOccurred()) {
      llvm::errs()
          << "Skipping file " << getCurrentFile()
          << " due to compiler errors. clang-include-cleaner expects to "
             "work on compilable source code.\n";
      return;
    }

    if (!HTMLReportPath.empty())
      writeHTML();

    auto &HS = getCompilerInstance().getPreprocessor().getHeaderSearchInfo();
    llvm::StringRef Path =
        SM.getFileEntryForID(SM.getMainFileID())->tryGetRealPathName();
    assert(!Path.empty() && "Main file path not known?");
    llvm::StringRef Code = SM.getBufferData(SM.getMainFileID());

    auto Results = analyze(AST.Roots, PP.MacroReferences, PP.Includes, &PI, SM,
                           HS, HeaderFilter);
    if (!Insert)
      Results.Missing.clear();
    if (!Remove)
      Results.Unused.clear();
    std::string Final = fixIncludes(Results, Path, Code, getStyle(Path));

    if (Print.getNumOccurrences()) {
      switch (Print) {
      case PrintStyle::Changes:
        for (const Include *I : Results.Unused)
          llvm::outs() << "- " << I->quote() << " @Line:" << I->Line << "\n";
        for (const auto &I : Results.Missing)
          llvm::outs() << "+ " << I << "\n";
        break;
      case PrintStyle::Final:
        llvm::outs() << Final;
        break;
      }
    }

    if (Edit && (!Results.Missing.empty() || !Results.Unused.empty())) {
      if (auto Err = llvm::writeToOutput(
              Path, [&](llvm::raw_ostream &OS) -> llvm::Error {
                OS << Final;
                return llvm::Error::success();
              })) {
        llvm::errs() << "Failed to apply edits to " << Path << ": "
                     << toString(std::move(Err)) << "\n";
        ++Errors;
      }
    }
  }

  void writeHTML() {
    std::error_code EC;
    llvm::raw_fd_ostream OS(HTMLReportPath, EC);
    if (EC) {
      llvm::errs() << "Unable to write HTML report to " << HTMLReportPath
                   << ": " << EC.message() << "\n";
      ++Errors;
      return;
    }
    writeHTMLReport(
        AST.Ctx->getSourceManager().getMainFileID(), PP.Includes, AST.Roots,
        PP.MacroReferences, *AST.Ctx,
        getCompilerInstance().getPreprocessor().getHeaderSearchInfo(), &PI, OS);
  }
};
class ActionFactory : public tooling::FrontendActionFactory {
public:
  ActionFactory(llvm::function_ref<bool(llvm::StringRef)> HeaderFilter)
      : HeaderFilter(HeaderFilter) {}

  std::unique_ptr<clang::FrontendAction> create() override {
    return std::make_unique<Action>(HeaderFilter);
  }

private:
  llvm::function_ref<bool(llvm::StringRef)> HeaderFilter;
};

std::function<bool(llvm::StringRef)> headerFilter() {
  auto FilterRegs = std::make_shared<std::vector<llvm::Regex>>();

  llvm::SmallVector<llvm::StringRef> Headers;
  llvm::StringRef(IgnoreHeaders).split(Headers, ',', -1, /*KeepEmpty=*/false);
  for (auto HeaderPattern : Headers) {
    std::string AnchoredPattern = "(" + HeaderPattern.str() + ")$";
    llvm::Regex CompiledRegex(AnchoredPattern);
    std::string RegexError;
    if (!CompiledRegex.isValid(RegexError)) {
      llvm::errs() << llvm::formatv("Invalid regular expression '{0}': {1}\n",
                                    HeaderPattern, RegexError);
      return nullptr;
    }
    FilterRegs->push_back(std::move(CompiledRegex));
  }
  return [FilterRegs](llvm::StringRef Path) {
    for (const auto &F : *FilterRegs) {
      if (F.match(Path))
        return true;
    }
    return false;
  };
}

} // namespace
} // namespace include_cleaner
} // namespace clang

int main(int argc, const char **argv) {
  using namespace clang::include_cleaner;

  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
  auto OptionsParser =
      clang::tooling::CommonOptionsParser::create(argc, argv, IncludeCleaner);
  if (!OptionsParser) {
    llvm::errs() << toString(OptionsParser.takeError());
    return 1;
  }

  if (OptionsParser->getSourcePathList().size() != 1) {
    std::vector<cl::Option *> IncompatibleFlags = {&HTMLReportPath, &Print};
    for (const auto *Flag : IncompatibleFlags) {
      if (Flag->getNumOccurrences()) {
        llvm::errs() << "-" << Flag->ArgStr << " requires a single input file";
        return 1;
      }
    }
  }

  clang::tooling::ClangTool Tool(OptionsParser->getCompilations(),
                                 OptionsParser->getSourcePathList());
  std::vector<std::unique_ptr<llvm::MemoryBuffer>> Buffers;
  for (const auto &File : OptionsParser->getSourcePathList()) {
    auto Content = llvm::MemoryBuffer::getFile(File);
    if (!Content) {
      llvm::errs() << "Error: can't read file '" << File
                   << "': " << Content.getError().message() << "\n";
      return 1;
    }
    Buffers.push_back(std::move(Content.get()));
    Tool.mapVirtualFile(File, Buffers.back()->getBuffer());
  }

  auto HeaderFilter = headerFilter();
  if (!HeaderFilter)
    return 1; // error already reported.
  ActionFactory Factory(HeaderFilter);
  return Tool.run(&Factory) || Errors != 0;
}