1 //===--- tools/clang-check/ClangCheck.cpp - Clang check tool --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a clang-check tool that runs clang based on the info
11 // stored in a compilation database.
12 //
13 // This tool uses the Clang Tooling infrastructure, see
14 // http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
15 // for details on setting it up with LLVM source tree.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "clang/AST/ASTConsumer.h"
20 #include "clang/CodeGen/ObjectFilePCHContainerOperations.h"
21 #include "clang/Driver/Options.h"
22 #include "clang/Frontend/ASTConsumers.h"
23 #include "clang/Frontend/CompilerInstance.h"
24 #include "clang/Rewrite/Frontend/FixItRewriter.h"
25 #include "clang/Rewrite/Frontend/FrontendActions.h"
26 #include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
27 #include "clang/Tooling/CommonOptionsParser.h"
28 #include "clang/Tooling/Tooling.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/Option/OptTable.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/Signals.h"
33 #include "llvm/Support/TargetSelect.h"
34
35 using namespace clang::driver;
36 using namespace clang::tooling;
37 using namespace llvm;
38
39 static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
40 static cl::extrahelp MoreHelp(
41 "\tFor example, to run clang-check on all files in a subtree of the\n"
42 "\tsource tree, use:\n"
43 "\n"
44 "\t find path/in/subtree -name '*.cpp'|xargs clang-check\n"
45 "\n"
46 "\tor using a specific build path:\n"
47 "\n"
48 "\t find path/in/subtree -name '*.cpp'|xargs clang-check -p build/path\n"
49 "\n"
50 "\tNote, that path/in/subtree and current directory should follow the\n"
51 "\trules described above.\n"
52 "\n"
53 );
54
55 static cl::OptionCategory ClangCheckCategory("clang-check options");
56 static std::unique_ptr<opt::OptTable> Options(createDriverOptTable());
57 static cl::opt<bool>
58 ASTDump("ast-dump", cl::desc(Options->getOptionHelpText(options::OPT_ast_dump)),
59 cl::cat(ClangCheckCategory));
60 static cl::opt<bool>
61 ASTList("ast-list", cl::desc(Options->getOptionHelpText(options::OPT_ast_list)),
62 cl::cat(ClangCheckCategory));
63 static cl::opt<bool>
64 ASTPrint("ast-print",
65 cl::desc(Options->getOptionHelpText(options::OPT_ast_print)),
66 cl::cat(ClangCheckCategory));
67 static cl::opt<std::string> ASTDumpFilter(
68 "ast-dump-filter",
69 cl::desc(Options->getOptionHelpText(options::OPT_ast_dump_filter)),
70 cl::cat(ClangCheckCategory));
71 static cl::opt<bool>
72 Analyze("analyze", cl::desc(Options->getOptionHelpText(options::OPT_analyze)),
73 cl::cat(ClangCheckCategory));
74
75 static cl::opt<bool>
76 Fixit("fixit", cl::desc(Options->getOptionHelpText(options::OPT_fixit)),
77 cl::cat(ClangCheckCategory));
78 static cl::opt<bool> FixWhatYouCan(
79 "fix-what-you-can",
80 cl::desc(Options->getOptionHelpText(options::OPT_fix_what_you_can)),
81 cl::cat(ClangCheckCategory));
82
83 namespace {
84
85 // FIXME: Move FixItRewriteInPlace from lib/Rewrite/Frontend/FrontendActions.cpp
86 // into a header file and reuse that.
87 class FixItOptions : public clang::FixItOptions {
88 public:
FixItOptions()89 FixItOptions() {
90 FixWhatYouCan = ::FixWhatYouCan;
91 }
92
RewriteFilename(const std::string & filename,int & fd)93 std::string RewriteFilename(const std::string& filename, int &fd) override {
94 assert(llvm::sys::path::is_absolute(filename) &&
95 "clang-fixit expects absolute paths only.");
96
97 // We don't need to do permission checking here since clang will diagnose
98 // any I/O errors itself.
99
100 fd = -1; // No file descriptor for file.
101
102 return filename;
103 }
104 };
105
106 /// Subclasses \c clang::FixItRewriter to not count fixed errors/warnings
107 /// in the final error counts.
108 ///
109 /// This has the side-effect that clang-check -fixit exits with code 0 on
110 /// successfully fixing all errors.
111 class FixItRewriter : public clang::FixItRewriter {
112 public:
FixItRewriter(clang::DiagnosticsEngine & Diags,clang::SourceManager & SourceMgr,const clang::LangOptions & LangOpts,clang::FixItOptions * FixItOpts)113 FixItRewriter(clang::DiagnosticsEngine& Diags,
114 clang::SourceManager& SourceMgr,
115 const clang::LangOptions& LangOpts,
116 clang::FixItOptions* FixItOpts)
117 : clang::FixItRewriter(Diags, SourceMgr, LangOpts, FixItOpts) {
118 }
119
IncludeInDiagnosticCounts() const120 bool IncludeInDiagnosticCounts() const override { return false; }
121 };
122
123 /// Subclasses \c clang::FixItAction so that we can install the custom
124 /// \c FixItRewriter.
125 class ClangCheckFixItAction : public clang::FixItAction {
126 public:
BeginSourceFileAction(clang::CompilerInstance & CI)127 bool BeginSourceFileAction(clang::CompilerInstance& CI) override {
128 FixItOpts.reset(new FixItOptions);
129 Rewriter.reset(new FixItRewriter(CI.getDiagnostics(), CI.getSourceManager(),
130 CI.getLangOpts(), FixItOpts.get()));
131 return true;
132 }
133 };
134
135 class ClangCheckActionFactory {
136 public:
newASTConsumer()137 std::unique_ptr<clang::ASTConsumer> newASTConsumer() {
138 if (ASTList)
139 return clang::CreateASTDeclNodeLister();
140 if (ASTDump)
141 return clang::CreateASTDumper(nullptr /*Dump to stdout.*/,
142 ASTDumpFilter,
143 /*DumpDecls=*/true,
144 /*Deserialize=*/false,
145 /*DumpLookups=*/false);
146 if (ASTPrint)
147 return clang::CreateASTPrinter(nullptr, ASTDumpFilter);
148 return llvm::make_unique<clang::ASTConsumer>();
149 }
150 };
151
152 } // namespace
153
main(int argc,const char ** argv)154 int main(int argc, const char **argv) {
155 llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
156
157 // Initialize targets for clang module support.
158 llvm::InitializeAllTargets();
159 llvm::InitializeAllTargetMCs();
160 llvm::InitializeAllAsmPrinters();
161 llvm::InitializeAllAsmParsers();
162
163 CommonOptionsParser OptionsParser(argc, argv, ClangCheckCategory);
164 ClangTool Tool(OptionsParser.getCompilations(),
165 OptionsParser.getSourcePathList());
166
167 // Clear adjusters because -fsyntax-only is inserted by the default chain.
168 Tool.clearArgumentsAdjusters();
169 Tool.appendArgumentsAdjuster(getClangStripOutputAdjuster());
170 Tool.appendArgumentsAdjuster(getClangStripDependencyFileAdjuster());
171
172 // Running the analyzer requires --analyze. Other modes can work with the
173 // -fsyntax-only option.
174 Tool.appendArgumentsAdjuster(getInsertArgumentAdjuster(
175 Analyze ? "--analyze" : "-fsyntax-only", ArgumentInsertPosition::BEGIN));
176
177 ClangCheckActionFactory CheckFactory;
178 std::unique_ptr<FrontendActionFactory> FrontendFactory;
179
180 // Choose the correct factory based on the selected mode.
181 if (Analyze)
182 FrontendFactory = newFrontendActionFactory<clang::ento::AnalysisAction>();
183 else if (Fixit)
184 FrontendFactory = newFrontendActionFactory<ClangCheckFixItAction>();
185 else
186 FrontendFactory = newFrontendActionFactory(&CheckFactory);
187
188 return Tool.run(FrontendFactory.get());
189 }
190