blob: aec2d98a2f7d2c31642606cfcc88e57c6e8f391a [file] [log] [blame]
Daniel Jasperd07c8402013-07-29 08:19:24 +00001//===--- tools/extra/clang-tidy/ClangTidy.cpp - Clang tidy 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/// \file This file implements a clang-tidy tool.
11///
12/// This tool uses the Clang Tooling infrastructure, see
13/// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
14/// for details on setting it up with LLVM source tree.
15///
16//===----------------------------------------------------------------------===//
17
18#include "ClangTidy.h"
19#include "ClangTidyDiagnosticConsumer.h"
20#include "ClangTidyModuleRegistry.h"
21#include "clang/AST/ASTConsumer.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/Decl.h"
24#include "clang/ASTMatchers/ASTMatchFinder.h"
Daniel Jasperd07c8402013-07-29 08:19:24 +000025#include "clang/Frontend/ASTConsumers.h"
26#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/FrontendActions.h"
Alexander Kornienko175fefb2014-01-03 09:31:57 +000028#include "clang/Frontend/MultiplexConsumer.h"
Daniel Jasperd07c8402013-07-29 08:19:24 +000029#include "clang/Frontend/TextDiagnosticPrinter.h"
Chandler Carruth85e6e872014-01-07 20:05:01 +000030#include "clang/Lex/PPCallbacks.h"
31#include "clang/Lex/Preprocessor.h"
Daniel Jasperd07c8402013-07-29 08:19:24 +000032#include "clang/Rewrite/Frontend/FixItRewriter.h"
33#include "clang/Rewrite/Frontend/FrontendActions.h"
Alexander Kornienkod1199cb2014-01-03 17:24:20 +000034#include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
Daniel Jasperd07c8402013-07-29 08:19:24 +000035#include "clang/Tooling/Refactoring.h"
Chandler Carruth85e6e872014-01-07 20:05:01 +000036#include "clang/Tooling/Tooling.h"
Daniel Jasperd07c8402013-07-29 08:19:24 +000037#include "llvm/Support/Path.h"
Alexander Kornienko54461eb2014-02-06 14:50:10 +000038#include "llvm/Support/Process.h"
Daniel Jasperd07c8402013-07-29 08:19:24 +000039#include "llvm/Support/Signals.h"
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +000040#include <algorithm>
Daniel Jasperd07c8402013-07-29 08:19:24 +000041#include <vector>
42
43using namespace clang::ast_matchers;
44using namespace clang::driver;
45using namespace clang::tooling;
46using namespace llvm;
47
48namespace clang {
49namespace tidy {
Alexander Kornienko175fefb2014-01-03 09:31:57 +000050
Daniel Jasperd07c8402013-07-29 08:19:24 +000051namespace {
Alexander Kornienko54461eb2014-02-06 14:50:10 +000052static const char *AnalyzerCheckNamePrefix = "clang-analyzer-";
Manuel Klimek814f9bd2013-11-14 15:49:44 +000053
Alexander Kornienko54461eb2014-02-06 14:50:10 +000054static StringRef StaticAnalyzerChecks[] = {
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +000055#define GET_CHECKERS
56#define CHECKER(FULLNAME, CLASS, DESCFILE, HELPTEXT, GROUPINDEX, HIDDEN) \
57 FULLNAME,
NAKAMURA Takumi321b7d32014-01-03 10:24:51 +000058#include "../../../lib/StaticAnalyzer/Checkers/Checkers.inc"
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +000059#undef CHECKER
60#undef GET_CHECKERS
61};
62
Alexander Kornienko54461eb2014-02-06 14:50:10 +000063class AnalyzerDiagnosticConsumer : public ento::PathDiagnosticConsumer {
64public:
65 AnalyzerDiagnosticConsumer(ClangTidyContext &Context) : Context(Context) {}
66
67 virtual void
68 FlushDiagnosticsImpl(std::vector<const ento::PathDiagnostic *> &Diags,
69 FilesMade *filesMade) LLVM_OVERRIDE {
70 for (std::vector<const ento::PathDiagnostic *>::iterator I = Diags.begin(),
71 E = Diags.end();
72 I != E; ++I) {
73 const ento::PathDiagnostic *PD = *I;
Alexander Kornienkod1afc702014-02-12 09:52:07 +000074 SmallString<64> CheckName(AnalyzerCheckNamePrefix);
75 CheckName += PD->getCheckName();
Alexander Kornienko54461eb2014-02-06 14:50:10 +000076 addRanges(Context.diag(CheckName, PD->getLocation().asLocation(),
77 PD->getShortDescription()),
78 PD->path.back()->getRanges());
79
80 ento::PathPieces FlatPath =
81 PD->path.flatten(/*ShouldFlattenMacros=*/true);
82 for (ento::PathPieces::const_iterator PI = FlatPath.begin(),
83 PE = FlatPath.end();
84 PI != PE; ++PI) {
85 addRanges(Context.diag(CheckName, (*PI)->getLocation().asLocation(),
86 (*PI)->getString(), DiagnosticIDs::Note),
87 (*PI)->getRanges());
88 }
89 }
90 }
91
92 virtual StringRef getName() const { return "ClangTidyDiags"; }
93
94 virtual bool supportsLogicalOpControlFlow() const LLVM_OVERRIDE {
95 return true;
96 }
97 virtual bool supportsCrossFileDiagnostics() const LLVM_OVERRIDE {
98 return true;
99 }
100
101private:
102 ClangTidyContext &Context;
103
104 // FIXME: Convert to operator<<(DiagnosticBuilder&, ArrayRef<SourceRange>).
105 static const DiagnosticBuilder &addRanges(const DiagnosticBuilder &DB,
106 ArrayRef<SourceRange> Ranges) {
107 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
108 I != E; ++I)
109 DB << *I;
110 return DB;
111 }
112};
113
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000114} // namespace
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000115
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000116ClangTidyASTConsumerFactory::ClangTidyASTConsumerFactory(
117 StringRef EnableChecksRegex, StringRef DisableChecksRegex,
118 ClangTidyContext &Context)
119 : Filter(EnableChecksRegex, DisableChecksRegex), Context(Context),
120 CheckFactories(new ClangTidyCheckFactories) {
121 for (ClangTidyModuleRegistry::iterator I = ClangTidyModuleRegistry::begin(),
122 E = ClangTidyModuleRegistry::end();
123 I != E; ++I) {
124 OwningPtr<ClangTidyModule> Module(I->instantiate());
125 Module->addCheckFactories(*CheckFactories);
126 }
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000127
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000128 CheckFactories->createChecks(Filter, Checks);
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000129
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000130 for (SmallVectorImpl<ClangTidyCheck *>::iterator I = Checks.begin(),
131 E = Checks.end();
132 I != E; ++I) {
133 (*I)->setContext(&Context);
134 (*I)->registerMatchers(&Finder);
135 }
136}
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000137
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000138ClangTidyASTConsumerFactory::~ClangTidyASTConsumerFactory() {
139 for (SmallVectorImpl<ClangTidyCheck *>::iterator I = Checks.begin(),
140 E = Checks.end();
141 I != E; ++I)
142 delete *I;
143}
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000144
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000145clang::ASTConsumer *ClangTidyASTConsumerFactory::CreateASTConsumer(
146 clang::CompilerInstance &Compiler, StringRef File) {
147 // FIXME: Move this to a separate method, so that CreateASTConsumer doesn't
148 // modify Compiler.
149 Context.setSourceManager(&Compiler.getSourceManager());
150 for (SmallVectorImpl<ClangTidyCheck *>::iterator I = Checks.begin(),
151 E = Checks.end();
152 I != E; ++I)
153 (*I)->registerPPCallbacks(Compiler);
154
155 AnalyzerOptionsRef Options = Compiler.getAnalyzerOpts();
156 Options->CheckersControlList = getCheckersControlList();
157 Options->AnalysisStoreOpt = RegionStoreModel;
Alexander Kornienko54461eb2014-02-06 14:50:10 +0000158 Options->AnalysisDiagOpt = PD_NONE;
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000159 Options->AnalyzeNestedBlocks = true;
160 Options->eagerlyAssumeBinOpBifurcation = true;
Alexander Kornienko54461eb2014-02-06 14:50:10 +0000161 ento::AnalysisASTConsumer *AnalysisConsumer = ento::CreateAnalysisConsumer(
162 Compiler.getPreprocessor(), Compiler.getFrontendOpts().OutputFile,
163 Options, Compiler.getFrontendOpts().Plugins);
164 AnalysisConsumer->AddDiagnosticConsumer(
165 new AnalyzerDiagnosticConsumer(Context));
166 ASTConsumer *Consumers[] = { Finder.newASTConsumer(), AnalysisConsumer };
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000167 return new MultiplexConsumer(Consumers);
168}
169
170std::vector<std::string> ClangTidyASTConsumerFactory::getCheckNames() {
171 std::vector<std::string> CheckNames;
172 for (ClangTidyCheckFactories::FactoryMap::const_iterator
173 I = CheckFactories->begin(),
174 E = CheckFactories->end();
175 I != E; ++I) {
176 if (Filter.IsCheckEnabled(I->first))
177 CheckNames.push_back(I->first);
178 }
179
180 CheckersList AnalyzerChecks = getCheckersControlList();
181 for (CheckersList::const_iterator I = AnalyzerChecks.begin(),
182 E = AnalyzerChecks.end();
183 I != E; ++I)
Alexander Kornienko54461eb2014-02-06 14:50:10 +0000184 CheckNames.push_back(AnalyzerCheckNamePrefix + I->first);
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000185
186 std::sort(CheckNames.begin(), CheckNames.end());
187 return CheckNames;
188}
189
190ClangTidyASTConsumerFactory::CheckersList
191ClangTidyASTConsumerFactory::getCheckersControlList() {
192 CheckersList List;
Alexander Kornienko54461eb2014-02-06 14:50:10 +0000193 ArrayRef<StringRef> Checks(StaticAnalyzerChecks);
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000194
195 bool AnalyzerChecksEnabled = false;
Alexander Kornienko54461eb2014-02-06 14:50:10 +0000196 for (unsigned i = 0; i < Checks.size(); ++i) {
197 std::string Checker((AnalyzerCheckNamePrefix + Checks[i]).str());
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000198 AnalyzerChecksEnabled |=
Alexander Kornienko54461eb2014-02-06 14:50:10 +0000199 Filter.IsCheckEnabled(Checker) && !Checks[i].startswith("debug");
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000200 }
201
202 if (AnalyzerChecksEnabled) {
203 // Run our regex against all possible static analyzer checkers. Note that
204 // debug checkers print values / run programs to visualize the CFG and are
205 // thus not applicable to clang-tidy in general.
206 //
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000207 // Always add all core checkers if any other static analyzer checks are
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000208 // enabled. This is currently necessary, as other path sensitive checks
209 // rely on the core checkers.
Alexander Kornienko54461eb2014-02-06 14:50:10 +0000210 for (unsigned i = 0; i < Checks.size(); ++i) {
211 std::string Checker((AnalyzerCheckNamePrefix + Checks[i]).str());
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000212
Alexander Kornienko54461eb2014-02-06 14:50:10 +0000213 if (Checks[i].startswith("core") ||
214 (!Checks[i].startswith("debug") && Filter.IsCheckEnabled(Checker)))
215 List.push_back(std::make_pair(Checks[i], true));
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000216 }
217 }
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000218 return List;
219}
Daniel Jasperd07c8402013-07-29 08:19:24 +0000220
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000221ChecksFilter::ChecksFilter(StringRef EnableChecksRegex,
222 StringRef DisableChecksRegex)
223 : EnableChecks(EnableChecksRegex), DisableChecks(DisableChecksRegex) {}
224
225bool ChecksFilter::IsCheckEnabled(StringRef Name) {
226 return EnableChecks.match(Name) && !DisableChecks.match(Name);
227}
228
Alexander Kornienko41bfe8d2014-01-13 10:50:51 +0000229DiagnosticBuilder ClangTidyCheck::diag(SourceLocation Loc, StringRef Message) {
230 return Context->diag(CheckName, Loc, Message);
231}
232
Daniel Jasperd07c8402013-07-29 08:19:24 +0000233void ClangTidyCheck::run(const ast_matchers::MatchFinder::MatchResult &Result) {
234 Context->setSourceManager(Result.SourceManager);
235 check(Result);
236}
237
Alexander Kornienko41bfe8d2014-01-13 10:50:51 +0000238void ClangTidyCheck::setName(StringRef Name) {
239 assert(CheckName.empty());
240 CheckName = Name.str();
241}
242
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000243std::vector<std::string> getCheckNames(StringRef EnableChecksRegex,
244 StringRef DisableChecksRegex) {
245 SmallVector<ClangTidyError, 8> Errors;
246 clang::tidy::ClangTidyContext Context(&Errors);
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000247 ClangTidyASTConsumerFactory Factory(EnableChecksRegex, DisableChecksRegex,
248 Context);
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000249 return Factory.getCheckNames();
250}
251
252void runClangTidy(StringRef EnableChecksRegex, StringRef DisableChecksRegex,
Daniel Jasperd07c8402013-07-29 08:19:24 +0000253 const tooling::CompilationDatabase &Compilations,
254 ArrayRef<std::string> Ranges,
255 SmallVectorImpl<ClangTidyError> *Errors) {
256 // FIXME: Ranges are currently full files. Support selecting specific
257 // (line-)ranges.
258 ClangTool Tool(Compilations, Ranges);
259 clang::tidy::ClangTidyContext Context(Errors);
260 ClangTidyDiagnosticConsumer DiagConsumer(Context);
Manuel Klimek814f9bd2013-11-14 15:49:44 +0000261
262 Tool.setDiagnosticConsumer(&DiagConsumer);
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000263
264 class ActionFactory : public FrontendActionFactory {
265 public:
266 ActionFactory(ClangTidyASTConsumerFactory *ConsumerFactory)
267 : ConsumerFactory(ConsumerFactory) {}
268 FrontendAction *create() LLVM_OVERRIDE {
269 return new Action(ConsumerFactory);
270 }
271
272 private:
273 class Action : public ASTFrontendAction {
274 public:
275 Action(ClangTidyASTConsumerFactory *Factory) : Factory(Factory) {}
276 ASTConsumer *CreateASTConsumer(CompilerInstance &Compiler,
277 StringRef File) LLVM_OVERRIDE {
278 return Factory->CreateASTConsumer(Compiler, File);
279 }
280
281 private:
282 ClangTidyASTConsumerFactory *Factory;
283 };
284
285 ClangTidyASTConsumerFactory *ConsumerFactory;
286 };
287
288 Tool.run(new ActionFactory(new ClangTidyASTConsumerFactory(
289 EnableChecksRegex, DisableChecksRegex, Context)));
Manuel Klimek814f9bd2013-11-14 15:49:44 +0000290}
291
Alexander Kornienko54461eb2014-02-06 14:50:10 +0000292static SourceLocation getLocation(SourceManager &SourceMgr, StringRef FilePath,
293 unsigned Offset) {
294 if (FilePath.empty())
295 return SourceLocation();
296
297 const FileEntry *File = SourceMgr.getFileManager().getFile(FilePath);
298 FileID ID = SourceMgr.createFileID(File, SourceLocation(), SrcMgr::C_User);
299 return SourceMgr.getLocForStartOfFile(ID).getLocWithOffset(Offset);
300}
301
Manuel Klimek814f9bd2013-11-14 15:49:44 +0000302static void reportDiagnostic(const ClangTidyMessage &Message,
303 SourceManager &SourceMgr,
304 DiagnosticsEngine::Level Level,
Alexander Kornienko41bfe8d2014-01-13 10:50:51 +0000305 DiagnosticsEngine &Diags,
Alexander Kornienko54461eb2014-02-06 14:50:10 +0000306 tooling::Replacements *Fixes = NULL) {
307 SourceLocation Loc =
308 getLocation(SourceMgr, Message.FilePath, Message.FileOffset);
309 DiagnosticBuilder Diag = Diags.Report(Loc, Diags.getCustomDiagID(Level, "%0"))
310 << Message.Message;
311 if (Fixes != NULL) {
312 for (tooling::Replacements::const_iterator I = Fixes->begin(),
313 E = Fixes->end();
314 I != E; ++I) {
315 SourceLocation FixLoc =
316 getLocation(SourceMgr, I->getFilePath(), I->getOffset());
317 Diag << FixItHint::CreateReplacement(
318 SourceRange(FixLoc, FixLoc.getLocWithOffset(I->getLength())),
319 I->getReplacementText());
320 }
Daniel Jasperd07c8402013-07-29 08:19:24 +0000321 }
Daniel Jasperd07c8402013-07-29 08:19:24 +0000322}
323
324void handleErrors(SmallVectorImpl<ClangTidyError> &Errors, bool Fix) {
325 FileManager Files((FileSystemOptions()));
Nick Lewyckyccf8e292014-02-06 22:57:16 +0000326 LangOptions LangOpts; // FIXME: use langopts from each original file
Daniel Jasperd07c8402013-07-29 08:19:24 +0000327 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko54461eb2014-02-06 14:50:10 +0000328 DiagOpts->ShowColors = llvm::sys::Process::StandardErrHasColors();
Daniel Jasperd07c8402013-07-29 08:19:24 +0000329 DiagnosticConsumer *DiagPrinter =
330 new TextDiagnosticPrinter(llvm::outs(), &*DiagOpts);
331 DiagnosticsEngine Diags(IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
332 &*DiagOpts, DiagPrinter);
Nick Lewyckyccf8e292014-02-06 22:57:16 +0000333 DiagPrinter->BeginSourceFile(LangOpts);
Daniel Jasperd07c8402013-07-29 08:19:24 +0000334 SourceManager SourceMgr(Diags, Files);
Nick Lewyckyccf8e292014-02-06 22:57:16 +0000335 Rewriter Rewrite(SourceMgr, LangOpts);
Daniel Jasperd07c8402013-07-29 08:19:24 +0000336 for (SmallVectorImpl<ClangTidyError>::iterator I = Errors.begin(),
337 E = Errors.end();
338 I != E; ++I) {
Alexander Kornienko41bfe8d2014-01-13 10:50:51 +0000339 reportDiagnostic(I->Message, SourceMgr, DiagnosticsEngine::Warning, Diags,
Alexander Kornienko54461eb2014-02-06 14:50:10 +0000340 &I->Fix);
Manuel Klimek814f9bd2013-11-14 15:49:44 +0000341 for (unsigned i = 0, e = I->Notes.size(); i != e; ++i) {
342 reportDiagnostic(I->Notes[i], SourceMgr, DiagnosticsEngine::Note, Diags);
343 }
Daniel Jasperd07c8402013-07-29 08:19:24 +0000344 tooling::applyAllReplacements(I->Fix, Rewrite);
345 }
346 // FIXME: Run clang-format on changes.
347 if (Fix)
348 Rewrite.overwriteChangedFiles();
349}
350
Daniel Jasperd07c8402013-07-29 08:19:24 +0000351} // namespace tidy
352} // namespace clang