1e5dd7070Spatrick //===--- tools/clang-check/ClangCheck.cpp - Clang check tool --------------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This file implements a clang-check tool that runs clang based on the info
10e5dd7070Spatrick // stored in a compilation database.
11e5dd7070Spatrick //
12e5dd7070Spatrick // This tool uses the Clang Tooling infrastructure, see
13e5dd7070Spatrick // http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
14e5dd7070Spatrick // for details on setting it up with LLVM source tree.
15e5dd7070Spatrick //
16e5dd7070Spatrick //===----------------------------------------------------------------------===//
17e5dd7070Spatrick
18e5dd7070Spatrick #include "clang/AST/ASTConsumer.h"
19e5dd7070Spatrick #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
20e5dd7070Spatrick #include "clang/Driver/Options.h"
21e5dd7070Spatrick #include "clang/Frontend/ASTConsumers.h"
22e5dd7070Spatrick #include "clang/Frontend/CompilerInstance.h"
23e5dd7070Spatrick #include "clang/Rewrite/Frontend/FixItRewriter.h"
24e5dd7070Spatrick #include "clang/Rewrite/Frontend/FrontendActions.h"
25e5dd7070Spatrick #include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
26e5dd7070Spatrick #include "clang/Tooling/CommonOptionsParser.h"
27a9ac8606Spatrick #include "clang/Tooling/Syntax/BuildTree.h"
28*12c85518Srobert #include "clang/Tooling/Syntax/TokenBufferTokenManager.h"
29a9ac8606Spatrick #include "clang/Tooling/Syntax/Tokens.h"
30a9ac8606Spatrick #include "clang/Tooling/Syntax/Tree.h"
31e5dd7070Spatrick #include "clang/Tooling/Tooling.h"
32e5dd7070Spatrick #include "llvm/ADT/STLExtras.h"
33e5dd7070Spatrick #include "llvm/Option/OptTable.h"
34e5dd7070Spatrick #include "llvm/Support/Path.h"
35e5dd7070Spatrick #include "llvm/Support/Signals.h"
36e5dd7070Spatrick #include "llvm/Support/TargetSelect.h"
37e5dd7070Spatrick
38e5dd7070Spatrick using namespace clang::driver;
39e5dd7070Spatrick using namespace clang::tooling;
40e5dd7070Spatrick using namespace llvm;
41e5dd7070Spatrick
42e5dd7070Spatrick static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
43e5dd7070Spatrick static cl::extrahelp MoreHelp(
44e5dd7070Spatrick "\tFor example, to run clang-check on all files in a subtree of the\n"
45e5dd7070Spatrick "\tsource tree, use:\n"
46e5dd7070Spatrick "\n"
47e5dd7070Spatrick "\t find path/in/subtree -name '*.cpp'|xargs clang-check\n"
48e5dd7070Spatrick "\n"
49e5dd7070Spatrick "\tor using a specific build path:\n"
50e5dd7070Spatrick "\n"
51e5dd7070Spatrick "\t find path/in/subtree -name '*.cpp'|xargs clang-check -p build/path\n"
52e5dd7070Spatrick "\n"
53e5dd7070Spatrick "\tNote, that path/in/subtree and current directory should follow the\n"
54e5dd7070Spatrick "\trules described above.\n"
55e5dd7070Spatrick "\n"
56e5dd7070Spatrick );
57e5dd7070Spatrick
58e5dd7070Spatrick static cl::OptionCategory ClangCheckCategory("clang-check options");
59e5dd7070Spatrick static const opt::OptTable &Options = getDriverOptTable();
60e5dd7070Spatrick static cl::opt<bool>
61e5dd7070Spatrick ASTDump("ast-dump",
62e5dd7070Spatrick cl::desc(Options.getOptionHelpText(options::OPT_ast_dump)),
63e5dd7070Spatrick cl::cat(ClangCheckCategory));
64e5dd7070Spatrick static cl::opt<bool>
65e5dd7070Spatrick ASTList("ast-list",
66e5dd7070Spatrick cl::desc(Options.getOptionHelpText(options::OPT_ast_list)),
67e5dd7070Spatrick cl::cat(ClangCheckCategory));
68e5dd7070Spatrick static cl::opt<bool>
69e5dd7070Spatrick ASTPrint("ast-print",
70e5dd7070Spatrick cl::desc(Options.getOptionHelpText(options::OPT_ast_print)),
71e5dd7070Spatrick cl::cat(ClangCheckCategory));
72e5dd7070Spatrick static cl::opt<std::string> ASTDumpFilter(
73e5dd7070Spatrick "ast-dump-filter",
74e5dd7070Spatrick cl::desc(Options.getOptionHelpText(options::OPT_ast_dump_filter)),
75e5dd7070Spatrick cl::cat(ClangCheckCategory));
76e5dd7070Spatrick static cl::opt<bool>
77e5dd7070Spatrick Analyze("analyze",
78e5dd7070Spatrick cl::desc(Options.getOptionHelpText(options::OPT_analyze)),
79e5dd7070Spatrick cl::cat(ClangCheckCategory));
80*12c85518Srobert static cl::opt<std::string>
81*12c85518Srobert AnalyzerOutput("analyzer-output-path",
82*12c85518Srobert cl::desc(Options.getOptionHelpText(options::OPT_o)),
83*12c85518Srobert cl::cat(ClangCheckCategory));
84e5dd7070Spatrick
85e5dd7070Spatrick static cl::opt<bool>
86e5dd7070Spatrick Fixit("fixit", cl::desc(Options.getOptionHelpText(options::OPT_fixit)),
87e5dd7070Spatrick cl::cat(ClangCheckCategory));
88e5dd7070Spatrick static cl::opt<bool> FixWhatYouCan(
89e5dd7070Spatrick "fix-what-you-can",
90e5dd7070Spatrick cl::desc(Options.getOptionHelpText(options::OPT_fix_what_you_can)),
91e5dd7070Spatrick cl::cat(ClangCheckCategory));
92e5dd7070Spatrick
93a9ac8606Spatrick static cl::opt<bool> SyntaxTreeDump("syntax-tree-dump",
94a9ac8606Spatrick cl::desc("dump the syntax tree"),
95a9ac8606Spatrick cl::cat(ClangCheckCategory));
96a9ac8606Spatrick static cl::opt<bool> TokensDump("tokens-dump",
97a9ac8606Spatrick cl::desc("dump the preprocessed tokens"),
98a9ac8606Spatrick cl::cat(ClangCheckCategory));
99a9ac8606Spatrick
100e5dd7070Spatrick namespace {
101e5dd7070Spatrick
102e5dd7070Spatrick // FIXME: Move FixItRewriteInPlace from lib/Rewrite/Frontend/FrontendActions.cpp
103e5dd7070Spatrick // into a header file and reuse that.
104e5dd7070Spatrick class FixItOptions : public clang::FixItOptions {
105e5dd7070Spatrick public:
FixItOptions()106e5dd7070Spatrick FixItOptions() {
107e5dd7070Spatrick FixWhatYouCan = ::FixWhatYouCan;
108e5dd7070Spatrick }
109e5dd7070Spatrick
RewriteFilename(const std::string & filename,int & fd)110e5dd7070Spatrick std::string RewriteFilename(const std::string& filename, int &fd) override {
111e5dd7070Spatrick // We don't need to do permission checking here since clang will diagnose
112e5dd7070Spatrick // any I/O errors itself.
113e5dd7070Spatrick
114e5dd7070Spatrick fd = -1; // No file descriptor for file.
115e5dd7070Spatrick
116e5dd7070Spatrick return filename;
117e5dd7070Spatrick }
118e5dd7070Spatrick };
119e5dd7070Spatrick
120e5dd7070Spatrick /// Subclasses \c clang::FixItRewriter to not count fixed errors/warnings
121e5dd7070Spatrick /// in the final error counts.
122e5dd7070Spatrick ///
123e5dd7070Spatrick /// This has the side-effect that clang-check -fixit exits with code 0 on
124e5dd7070Spatrick /// successfully fixing all errors.
125e5dd7070Spatrick class FixItRewriter : public clang::FixItRewriter {
126e5dd7070Spatrick public:
FixItRewriter(clang::DiagnosticsEngine & Diags,clang::SourceManager & SourceMgr,const clang::LangOptions & LangOpts,clang::FixItOptions * FixItOpts)127e5dd7070Spatrick FixItRewriter(clang::DiagnosticsEngine& Diags,
128e5dd7070Spatrick clang::SourceManager& SourceMgr,
129e5dd7070Spatrick const clang::LangOptions& LangOpts,
130e5dd7070Spatrick clang::FixItOptions* FixItOpts)
131e5dd7070Spatrick : clang::FixItRewriter(Diags, SourceMgr, LangOpts, FixItOpts) {
132e5dd7070Spatrick }
133e5dd7070Spatrick
IncludeInDiagnosticCounts() const134e5dd7070Spatrick bool IncludeInDiagnosticCounts() const override { return false; }
135e5dd7070Spatrick };
136e5dd7070Spatrick
137e5dd7070Spatrick /// Subclasses \c clang::FixItAction so that we can install the custom
138e5dd7070Spatrick /// \c FixItRewriter.
139e5dd7070Spatrick class ClangCheckFixItAction : public clang::FixItAction {
140e5dd7070Spatrick public:
BeginSourceFileAction(clang::CompilerInstance & CI)141e5dd7070Spatrick bool BeginSourceFileAction(clang::CompilerInstance& CI) override {
142e5dd7070Spatrick FixItOpts.reset(new FixItOptions);
143e5dd7070Spatrick Rewriter.reset(new FixItRewriter(CI.getDiagnostics(), CI.getSourceManager(),
144e5dd7070Spatrick CI.getLangOpts(), FixItOpts.get()));
145e5dd7070Spatrick return true;
146e5dd7070Spatrick }
147e5dd7070Spatrick };
148e5dd7070Spatrick
149a9ac8606Spatrick class DumpSyntaxTree : public clang::ASTFrontendAction {
150a9ac8606Spatrick public:
151a9ac8606Spatrick std::unique_ptr<clang::ASTConsumer>
CreateASTConsumer(clang::CompilerInstance & CI,StringRef InFile)152a9ac8606Spatrick CreateASTConsumer(clang::CompilerInstance &CI, StringRef InFile) override {
153a9ac8606Spatrick class Consumer : public clang::ASTConsumer {
154a9ac8606Spatrick public:
155a9ac8606Spatrick Consumer(clang::CompilerInstance &CI) : Collector(CI.getPreprocessor()) {}
156a9ac8606Spatrick
157a9ac8606Spatrick void HandleTranslationUnit(clang::ASTContext &AST) override {
158a9ac8606Spatrick clang::syntax::TokenBuffer TB = std::move(Collector).consume();
159a9ac8606Spatrick if (TokensDump)
160a9ac8606Spatrick llvm::outs() << TB.dumpForTests();
161*12c85518Srobert clang::syntax::TokenBufferTokenManager TBTM(TB, AST.getLangOpts(),
162a9ac8606Spatrick AST.getSourceManager());
163*12c85518Srobert clang::syntax::Arena A;
164*12c85518Srobert llvm::outs()
165*12c85518Srobert << clang::syntax::buildSyntaxTree(A, TBTM, AST)->dump(TBTM);
166a9ac8606Spatrick }
167a9ac8606Spatrick
168a9ac8606Spatrick private:
169a9ac8606Spatrick clang::syntax::TokenCollector Collector;
170a9ac8606Spatrick };
171a9ac8606Spatrick return std::make_unique<Consumer>(CI);
172a9ac8606Spatrick }
173a9ac8606Spatrick };
174a9ac8606Spatrick
175e5dd7070Spatrick class ClangCheckActionFactory {
176e5dd7070Spatrick public:
newASTConsumer()177e5dd7070Spatrick std::unique_ptr<clang::ASTConsumer> newASTConsumer() {
178e5dd7070Spatrick if (ASTList)
179e5dd7070Spatrick return clang::CreateASTDeclNodeLister();
180e5dd7070Spatrick if (ASTDump)
181e5dd7070Spatrick return clang::CreateASTDumper(nullptr /*Dump to stdout.*/, ASTDumpFilter,
182e5dd7070Spatrick /*DumpDecls=*/true,
183e5dd7070Spatrick /*Deserialize=*/false,
184e5dd7070Spatrick /*DumpLookups=*/false,
185ec727ea7Spatrick /*DumpDeclTypes=*/false,
186e5dd7070Spatrick clang::ADOF_Default);
187e5dd7070Spatrick if (ASTPrint)
188e5dd7070Spatrick return clang::CreateASTPrinter(nullptr, ASTDumpFilter);
189e5dd7070Spatrick return std::make_unique<clang::ASTConsumer>();
190e5dd7070Spatrick }
191e5dd7070Spatrick };
192e5dd7070Spatrick
193e5dd7070Spatrick } // namespace
194e5dd7070Spatrick
main(int argc,const char ** argv)195e5dd7070Spatrick int main(int argc, const char **argv) {
196e5dd7070Spatrick llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
197e5dd7070Spatrick
198e5dd7070Spatrick // Initialize targets for clang module support.
199e5dd7070Spatrick llvm::InitializeAllTargets();
200e5dd7070Spatrick llvm::InitializeAllTargetMCs();
201e5dd7070Spatrick llvm::InitializeAllAsmPrinters();
202e5dd7070Spatrick llvm::InitializeAllAsmParsers();
203e5dd7070Spatrick
204a9ac8606Spatrick auto ExpectedParser =
205a9ac8606Spatrick CommonOptionsParser::create(argc, argv, ClangCheckCategory);
206a9ac8606Spatrick if (!ExpectedParser) {
207a9ac8606Spatrick llvm::errs() << ExpectedParser.takeError();
208a9ac8606Spatrick return 1;
209a9ac8606Spatrick }
210a9ac8606Spatrick CommonOptionsParser &OptionsParser = ExpectedParser.get();
211e5dd7070Spatrick ClangTool Tool(OptionsParser.getCompilations(),
212e5dd7070Spatrick OptionsParser.getSourcePathList());
213e5dd7070Spatrick
214*12c85518Srobert if (Analyze) {
215*12c85518Srobert // Set output path if is provided by user.
216*12c85518Srobert //
217*12c85518Srobert // As the original -o options have been removed by default via the
218*12c85518Srobert // strip-output adjuster, we only need to add the analyzer -o options here
219*12c85518Srobert // when it is provided by users.
220*12c85518Srobert if (!AnalyzerOutput.empty())
221*12c85518Srobert Tool.appendArgumentsAdjuster(
222*12c85518Srobert getInsertArgumentAdjuster(CommandLineArguments{"-o", AnalyzerOutput},
223*12c85518Srobert ArgumentInsertPosition::END));
224e5dd7070Spatrick
225e5dd7070Spatrick // Running the analyzer requires --analyze. Other modes can work with the
226e5dd7070Spatrick // -fsyntax-only option.
227*12c85518Srobert //
228*12c85518Srobert // The syntax-only adjuster is installed by default.
229*12c85518Srobert // Good: It also strips options that trigger extra output, like -save-temps.
230*12c85518Srobert // Bad: We don't want the -fsyntax-only when executing the static analyzer.
231*12c85518Srobert //
232*12c85518Srobert // To enable the static analyzer, we first strip all -fsyntax-only options
233*12c85518Srobert // and then add an --analyze option to the front.
234*12c85518Srobert Tool.appendArgumentsAdjuster(
235*12c85518Srobert [&](const CommandLineArguments &Args, StringRef /*unused*/) {
236*12c85518Srobert CommandLineArguments AdjustedArgs;
237*12c85518Srobert for (const std::string &Arg : Args)
238*12c85518Srobert if (Arg != "-fsyntax-only")
239*12c85518Srobert AdjustedArgs.emplace_back(Arg);
240*12c85518Srobert return AdjustedArgs;
241*12c85518Srobert });
242*12c85518Srobert Tool.appendArgumentsAdjuster(
243*12c85518Srobert getInsertArgumentAdjuster("--analyze", ArgumentInsertPosition::BEGIN));
244*12c85518Srobert }
245e5dd7070Spatrick
246e5dd7070Spatrick ClangCheckActionFactory CheckFactory;
247e5dd7070Spatrick std::unique_ptr<FrontendActionFactory> FrontendFactory;
248e5dd7070Spatrick
249e5dd7070Spatrick // Choose the correct factory based on the selected mode.
250e5dd7070Spatrick if (Analyze)
251e5dd7070Spatrick FrontendFactory = newFrontendActionFactory<clang::ento::AnalysisAction>();
252e5dd7070Spatrick else if (Fixit)
253e5dd7070Spatrick FrontendFactory = newFrontendActionFactory<ClangCheckFixItAction>();
254a9ac8606Spatrick else if (SyntaxTreeDump || TokensDump)
255a9ac8606Spatrick FrontendFactory = newFrontendActionFactory<DumpSyntaxTree>();
256e5dd7070Spatrick else
257e5dd7070Spatrick FrontendFactory = newFrontendActionFactory(&CheckFactory);
258e5dd7070Spatrick
259e5dd7070Spatrick return Tool.run(FrontendFactory.get());
260e5dd7070Spatrick }
261