• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 /// \brief 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 /// \brief Subclasses \c clang::FixItAction so that we can install the custom
124 /// \c FixItRewriter.
125 class FixItAction : public clang::FixItAction {
126 public:
BeginSourceFileAction(clang::CompilerInstance & CI,StringRef Filename)127   bool BeginSourceFileAction(clang::CompilerInstance& CI,
128                              StringRef Filename) override {
129     FixItOpts.reset(new FixItOptions);
130     Rewriter.reset(new FixItRewriter(CI.getDiagnostics(), CI.getSourceManager(),
131                                      CI.getLangOpts(), FixItOpts.get()));
132     return true;
133   }
134 };
135 
136 class ClangCheckActionFactory {
137 public:
newASTConsumer()138   std::unique_ptr<clang::ASTConsumer> newASTConsumer() {
139     if (ASTList)
140       return clang::CreateASTDeclNodeLister();
141     if (ASTDump)
142       return clang::CreateASTDumper(ASTDumpFilter, /*DumpDecls=*/true,
143                                     /*DumpLookups=*/false);
144     if (ASTPrint)
145       return clang::CreateASTPrinter(&llvm::outs(), ASTDumpFilter);
146     return llvm::make_unique<clang::ASTConsumer>();
147   }
148 };
149 
150 } // namespace
151 
main(int argc,const char ** argv)152 int main(int argc, const char **argv) {
153   llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
154 
155   // Initialize targets for clang module support.
156   llvm::InitializeAllTargets();
157   llvm::InitializeAllTargetMCs();
158   llvm::InitializeAllAsmPrinters();
159   llvm::InitializeAllAsmParsers();
160 
161   CommonOptionsParser OptionsParser(argc, argv, ClangCheckCategory);
162   ClangTool Tool(OptionsParser.getCompilations(),
163                  OptionsParser.getSourcePathList());
164 
165   // Clear adjusters because -fsyntax-only is inserted by the default chain.
166   Tool.clearArgumentsAdjusters();
167   Tool.appendArgumentsAdjuster(getClangStripOutputAdjuster());
168 
169   // Running the analyzer requires --analyze. Other modes can work with the
170   // -fsyntax-only option.
171   Tool.appendArgumentsAdjuster(getInsertArgumentAdjuster(
172       Analyze ? "--analyze" : "-fsyntax-only", ArgumentInsertPosition::BEGIN));
173 
174   ClangCheckActionFactory CheckFactory;
175   std::unique_ptr<FrontendActionFactory> FrontendFactory;
176 
177   // Choose the correct factory based on the selected mode.
178   if (Analyze)
179     FrontendFactory = newFrontendActionFactory<clang::ento::AnalysisAction>();
180   else if (Fixit)
181     FrontendFactory = newFrontendActionFactory<FixItAction>();
182   else
183     FrontendFactory = newFrontendActionFactory(&CheckFactory);
184 
185   return Tool.run(FrontendFactory.get());
186 }
187