• 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/Driver/Options.h"
21 #include "clang/Frontend/ASTConsumers.h"
22 #include "clang/Frontend/CompilerInstance.h"
23 #include "clang/Rewrite/Frontend/FixItRewriter.h"
24 #include "clang/Rewrite/Frontend/FrontendActions.h"
25 #include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
26 #include "clang/Tooling/CommonOptionsParser.h"
27 #include "clang/Tooling/Tooling.h"
28 #include "llvm/Option/OptTable.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/Signals.h"
31 
32 using namespace clang::driver;
33 using namespace clang::tooling;
34 using namespace llvm;
35 
36 static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
37 static cl::extrahelp MoreHelp(
38     "\tFor example, to run clang-check on all files in a subtree of the\n"
39     "\tsource tree, use:\n"
40     "\n"
41     "\t  find path/in/subtree -name '*.cpp'|xargs clang-check\n"
42     "\n"
43     "\tor using a specific build path:\n"
44     "\n"
45     "\t  find path/in/subtree -name '*.cpp'|xargs clang-check -p build/path\n"
46     "\n"
47     "\tNote, that path/in/subtree and current directory should follow the\n"
48     "\trules described above.\n"
49     "\n"
50 );
51 
52 static cl::OptionCategory ClangCheckCategory("clang-check options");
53 static std::unique_ptr<opt::OptTable> Options(createDriverOptTable());
54 static cl::opt<bool>
55 ASTDump("ast-dump", cl::desc(Options->getOptionHelpText(options::OPT_ast_dump)),
56         cl::cat(ClangCheckCategory));
57 static cl::opt<bool>
58 ASTList("ast-list", cl::desc(Options->getOptionHelpText(options::OPT_ast_list)),
59         cl::cat(ClangCheckCategory));
60 static cl::opt<bool>
61 ASTPrint("ast-print",
62          cl::desc(Options->getOptionHelpText(options::OPT_ast_print)),
63          cl::cat(ClangCheckCategory));
64 static cl::opt<std::string> ASTDumpFilter(
65     "ast-dump-filter",
66     cl::desc(Options->getOptionHelpText(options::OPT_ast_dump_filter)),
67     cl::cat(ClangCheckCategory));
68 static cl::opt<bool>
69 Analyze("analyze", cl::desc(Options->getOptionHelpText(options::OPT_analyze)),
70         cl::cat(ClangCheckCategory));
71 
72 static cl::opt<bool>
73 Fixit("fixit", cl::desc(Options->getOptionHelpText(options::OPT_fixit)),
74       cl::cat(ClangCheckCategory));
75 static cl::opt<bool> FixWhatYouCan(
76     "fix-what-you-can",
77     cl::desc(Options->getOptionHelpText(options::OPT_fix_what_you_can)),
78     cl::cat(ClangCheckCategory));
79 
80 static cl::list<std::string> ArgsAfter(
81     "extra-arg",
82     cl::desc("Additional argument to append to the compiler command line"),
83     cl::cat(ClangCheckCategory));
84 static cl::list<std::string> ArgsBefore(
85     "extra-arg-before",
86     cl::desc("Additional argument to prepend to the compiler command line"),
87     cl::cat(ClangCheckCategory));
88 
89 namespace {
90 
91 // FIXME: Move FixItRewriteInPlace from lib/Rewrite/Frontend/FrontendActions.cpp
92 // into a header file and reuse that.
93 class FixItOptions : public clang::FixItOptions {
94 public:
FixItOptions()95   FixItOptions() {
96     FixWhatYouCan = ::FixWhatYouCan;
97   }
98 
RewriteFilename(const std::string & filename,int & fd)99   std::string RewriteFilename(const std::string& filename, int &fd) override {
100     assert(llvm::sys::path::is_absolute(filename) &&
101            "clang-fixit expects absolute paths only.");
102 
103     // We don't need to do permission checking here since clang will diagnose
104     // any I/O errors itself.
105 
106     fd = -1;  // No file descriptor for file.
107 
108     return filename;
109   }
110 };
111 
112 /// \brief Subclasses \c clang::FixItRewriter to not count fixed errors/warnings
113 /// in the final error counts.
114 ///
115 /// This has the side-effect that clang-check -fixit exits with code 0 on
116 /// successfully fixing all errors.
117 class FixItRewriter : public clang::FixItRewriter {
118 public:
FixItRewriter(clang::DiagnosticsEngine & Diags,clang::SourceManager & SourceMgr,const clang::LangOptions & LangOpts,clang::FixItOptions * FixItOpts)119   FixItRewriter(clang::DiagnosticsEngine& Diags,
120                 clang::SourceManager& SourceMgr,
121                 const clang::LangOptions& LangOpts,
122                 clang::FixItOptions* FixItOpts)
123       : clang::FixItRewriter(Diags, SourceMgr, LangOpts, FixItOpts) {
124   }
125 
IncludeInDiagnosticCounts() const126   bool IncludeInDiagnosticCounts() const override { return false; }
127 };
128 
129 /// \brief Subclasses \c clang::FixItAction so that we can install the custom
130 /// \c FixItRewriter.
131 class FixItAction : public clang::FixItAction {
132 public:
BeginSourceFileAction(clang::CompilerInstance & CI,StringRef Filename)133   bool BeginSourceFileAction(clang::CompilerInstance& CI,
134                              StringRef Filename) override {
135     FixItOpts.reset(new FixItOptions);
136     Rewriter.reset(new FixItRewriter(CI.getDiagnostics(), CI.getSourceManager(),
137                                      CI.getLangOpts(), FixItOpts.get()));
138     return true;
139   }
140 };
141 
142 class InsertAdjuster: public clang::tooling::ArgumentsAdjuster {
143 public:
144   enum Position { BEGIN, END };
145 
InsertAdjuster(const CommandLineArguments & Extra,Position Pos)146   InsertAdjuster(const CommandLineArguments &Extra, Position Pos)
147     : Extra(Extra), Pos(Pos) {
148   }
149 
InsertAdjuster(const char * Extra,Position Pos)150   InsertAdjuster(const char *Extra, Position Pos)
151     : Extra(1, std::string(Extra)), Pos(Pos) {
152   }
153 
154   virtual CommandLineArguments
Adjust(const CommandLineArguments & Args)155   Adjust(const CommandLineArguments &Args) override {
156     CommandLineArguments Return(Args);
157 
158     CommandLineArguments::iterator I;
159     if (Pos == END) {
160       I = Return.end();
161     } else {
162       I = Return.begin();
163       ++I; // To leave the program name in place
164     }
165 
166     Return.insert(I, Extra.begin(), Extra.end());
167     return Return;
168   }
169 
170 private:
171   const CommandLineArguments Extra;
172   const Position Pos;
173 };
174 
175 } // namespace
176 
177 // Anonymous namespace here causes problems with gcc <= 4.4 on MacOS 10.6.
178 // "Non-global symbol: ... can't be a weak_definition"
179 namespace clang_check {
180 class ClangCheckActionFactory {
181 public:
newASTConsumer()182   clang::ASTConsumer *newASTConsumer() {
183     if (ASTList)
184       return clang::CreateASTDeclNodeLister();
185     if (ASTDump)
186       return clang::CreateASTDumper(ASTDumpFilter);
187     if (ASTPrint)
188       return clang::CreateASTPrinter(&llvm::outs(), ASTDumpFilter);
189     return new clang::ASTConsumer();
190   }
191 };
192 }
193 
main(int argc,const char ** argv)194 int main(int argc, const char **argv) {
195   llvm::sys::PrintStackTraceOnErrorSignal();
196   CommonOptionsParser OptionsParser(argc, argv, ClangCheckCategory);
197   ClangTool Tool(OptionsParser.getCompilations(),
198                  OptionsParser.getSourcePathList());
199 
200   // Clear adjusters because -fsyntax-only is inserted by the default chain.
201   Tool.clearArgumentsAdjusters();
202   Tool.appendArgumentsAdjuster(new ClangStripOutputAdjuster());
203   if (ArgsAfter.size() > 0) {
204     Tool.appendArgumentsAdjuster(new InsertAdjuster(ArgsAfter,
205           InsertAdjuster::END));
206   }
207   if (ArgsBefore.size() > 0) {
208     Tool.appendArgumentsAdjuster(new InsertAdjuster(ArgsBefore,
209           InsertAdjuster::BEGIN));
210   }
211 
212   // Running the analyzer requires --analyze. Other modes can work with the
213   // -fsyntax-only option.
214   Tool.appendArgumentsAdjuster(new InsertAdjuster(
215         Analyze ? "--analyze" : "-fsyntax-only", InsertAdjuster::BEGIN));
216 
217   clang_check::ClangCheckActionFactory CheckFactory;
218   std::unique_ptr<FrontendActionFactory> FrontendFactory;
219 
220   // Choose the correct factory based on the selected mode.
221   if (Analyze)
222     FrontendFactory = newFrontendActionFactory<clang::ento::AnalysisAction>();
223   else if (Fixit)
224     FrontendFactory = newFrontendActionFactory<FixItAction>();
225   else
226     FrontendFactory = newFrontendActionFactory(&CheckFactory);
227 
228   return Tool.run(FrontendFactory.get());
229 }
230