blob: d357cdaa5f68385ae717d9e0d37addf0d06f9fcd [file] [log] [blame]
Daniel Jasperd07c8402013-07-29 08:19:241//===--- 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:2425#include "clang/Frontend/ASTConsumers.h"
26#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/FrontendActions.h"
Alexander Kornienko175fefb2014-01-03 09:31:5728#include "clang/Frontend/MultiplexConsumer.h"
Daniel Jasperd07c8402013-07-29 08:19:2429#include "clang/Frontend/TextDiagnosticPrinter.h"
Chandler Carruth85e6e872014-01-07 20:05:0130#include "clang/Lex/PPCallbacks.h"
31#include "clang/Lex/Preprocessor.h"
Daniel Jasperd07c8402013-07-29 08:19:2432#include "clang/Rewrite/Frontend/FixItRewriter.h"
33#include "clang/Rewrite/Frontend/FrontendActions.h"
Alexander Kornienkod1199cb2014-01-03 17:24:2034#include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
Daniel Jasperd07c8402013-07-29 08:19:2435#include "clang/Tooling/Refactoring.h"
Chandler Carruth85e6e872014-01-07 20:05:0136#include "clang/Tooling/Tooling.h"
Daniel Jasperd07c8402013-07-29 08:19:2437#include "llvm/Support/Path.h"
Alexander Kornienko54461eb2014-02-06 14:50:1038#include "llvm/Support/Process.h"
Daniel Jasperd07c8402013-07-29 08:19:2439#include "llvm/Support/Signals.h"
Alexander Kornienkofb9e92b2013-12-19 19:57:0540#include <algorithm>
Daniel Jasperd07c8402013-07-29 08:19:2441#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:5750
Daniel Jasperd07c8402013-07-29 08:19:2451namespace {
Alexander Kornienko54461eb2014-02-06 14:50:1052static const char *AnalyzerCheckNamePrefix = "clang-analyzer-";
Manuel Klimek814f9bd2013-11-14 15:49:4453
Alexander Kornienko54461eb2014-02-06 14:50:1054static StringRef StaticAnalyzerChecks[] = {
Alexander Kornienkofb9e92b2013-12-19 19:57:0555#define GET_CHECKERS
56#define CHECKER(FULLNAME, CLASS, DESCFILE, HELPTEXT, GROUPINDEX, HIDDEN) \
57 FULLNAME,
NAKAMURA Takumi321b7d32014-01-03 10:24:5158#include "../../../lib/StaticAnalyzer/Checkers/Checkers.inc"
Alexander Kornienkofb9e92b2013-12-19 19:57:0559#undef CHECKER
60#undef GET_CHECKERS
61};
62
Alexander Kornienko54461eb2014-02-06 14:50:1063class AnalyzerDiagnosticConsumer : public ento::PathDiagnosticConsumer {
64public:
65 AnalyzerDiagnosticConsumer(ClangTidyContext &Context) : Context(Context) {}
66
Alexander Kornienkocb9272f2014-02-27 13:14:5167 void FlushDiagnosticsImpl(std::vector<const ento::PathDiagnostic *> &Diags,
68 FilesMade *filesMade) LLVM_OVERRIDE {
Alexander Kornienko54461eb2014-02-06 14:50:1069 for (std::vector<const ento::PathDiagnostic *>::iterator I = Diags.begin(),
70 E = Diags.end();
71 I != E; ++I) {
72 const ento::PathDiagnostic *PD = *I;
Alexander Kornienkod1afc702014-02-12 09:52:0773 SmallString<64> CheckName(AnalyzerCheckNamePrefix);
74 CheckName += PD->getCheckName();
Alexander Kornienko54461eb2014-02-06 14:50:1075 addRanges(Context.diag(CheckName, PD->getLocation().asLocation(),
76 PD->getShortDescription()),
77 PD->path.back()->getRanges());
78
79 ento::PathPieces FlatPath =
80 PD->path.flatten(/*ShouldFlattenMacros=*/true);
81 for (ento::PathPieces::const_iterator PI = FlatPath.begin(),
82 PE = FlatPath.end();
83 PI != PE; ++PI) {
84 addRanges(Context.diag(CheckName, (*PI)->getLocation().asLocation(),
85 (*PI)->getString(), DiagnosticIDs::Note),
86 (*PI)->getRanges());
87 }
88 }
89 }
90
Alexander Kornienkocb9272f2014-02-27 13:14:5191 StringRef getName() const LLVM_OVERRIDE { return "ClangTidyDiags"; }
92 bool supportsLogicalOpControlFlow() const LLVM_OVERRIDE { return true; }
93 bool supportsCrossFileDiagnostics() const LLVM_OVERRIDE { return true; }
Alexander Kornienko54461eb2014-02-06 14:50:1094
95private:
96 ClangTidyContext &Context;
97
98 // FIXME: Convert to operator<<(DiagnosticBuilder&, ArrayRef<SourceRange>).
99 static const DiagnosticBuilder &addRanges(const DiagnosticBuilder &DB,
100 ArrayRef<SourceRange> Ranges) {
101 for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
102 I != E; ++I)
103 DB << *I;
104 return DB;
105 }
106};
107
Alexander Kornienko175fefb2014-01-03 09:31:57108} // namespace
Alexander Kornienkofb9e92b2013-12-19 19:57:05109
Alexander Kornienko175fefb2014-01-03 09:31:57110ClangTidyASTConsumerFactory::ClangTidyASTConsumerFactory(
111 StringRef EnableChecksRegex, StringRef DisableChecksRegex,
112 ClangTidyContext &Context)
113 : Filter(EnableChecksRegex, DisableChecksRegex), Context(Context),
114 CheckFactories(new ClangTidyCheckFactories) {
115 for (ClangTidyModuleRegistry::iterator I = ClangTidyModuleRegistry::begin(),
116 E = ClangTidyModuleRegistry::end();
117 I != E; ++I) {
118 OwningPtr<ClangTidyModule> Module(I->instantiate());
119 Module->addCheckFactories(*CheckFactories);
120 }
Alexander Kornienkofb9e92b2013-12-19 19:57:05121
Alexander Kornienko175fefb2014-01-03 09:31:57122 CheckFactories->createChecks(Filter, Checks);
Alexander Kornienkofb9e92b2013-12-19 19:57:05123
Alexander Kornienko175fefb2014-01-03 09:31:57124 for (SmallVectorImpl<ClangTidyCheck *>::iterator I = Checks.begin(),
125 E = Checks.end();
126 I != E; ++I) {
127 (*I)->setContext(&Context);
128 (*I)->registerMatchers(&Finder);
129 }
130}
Alexander Kornienkofb9e92b2013-12-19 19:57:05131
Alexander Kornienko175fefb2014-01-03 09:31:57132ClangTidyASTConsumerFactory::~ClangTidyASTConsumerFactory() {
133 for (SmallVectorImpl<ClangTidyCheck *>::iterator I = Checks.begin(),
134 E = Checks.end();
135 I != E; ++I)
136 delete *I;
137}
Alexander Kornienkofb9e92b2013-12-19 19:57:05138
Alexander Kornienko175fefb2014-01-03 09:31:57139clang::ASTConsumer *ClangTidyASTConsumerFactory::CreateASTConsumer(
140 clang::CompilerInstance &Compiler, StringRef File) {
141 // FIXME: Move this to a separate method, so that CreateASTConsumer doesn't
142 // modify Compiler.
143 Context.setSourceManager(&Compiler.getSourceManager());
144 for (SmallVectorImpl<ClangTidyCheck *>::iterator I = Checks.begin(),
145 E = Checks.end();
146 I != E; ++I)
147 (*I)->registerPPCallbacks(Compiler);
148
Alexander Kornienko298b3822014-02-13 16:10:47149 SmallVector<ASTConsumer *, 2> Consumers;
Alexander Kornienkod68aa4c2014-02-13 16:29:39150 if (!CheckFactories->empty())
Alexander Kornienko298b3822014-02-13 16:10:47151 Consumers.push_back(Finder.newASTConsumer());
152
Alexander Kornienko175fefb2014-01-03 09:31:57153 AnalyzerOptionsRef Options = Compiler.getAnalyzerOpts();
154 Options->CheckersControlList = getCheckersControlList();
Alexander Kornienko298b3822014-02-13 16:10:47155 if (!Options->CheckersControlList.empty()) {
156 Options->AnalysisStoreOpt = RegionStoreModel;
157 Options->AnalysisDiagOpt = PD_NONE;
158 Options->AnalyzeNestedBlocks = true;
159 Options->eagerlyAssumeBinOpBifurcation = true;
160 ento::AnalysisASTConsumer *AnalysisConsumer = ento::CreateAnalysisConsumer(
161 Compiler.getPreprocessor(), Compiler.getFrontendOpts().OutputFile,
162 Options, Compiler.getFrontendOpts().Plugins);
163 AnalysisConsumer->AddDiagnosticConsumer(
164 new AnalyzerDiagnosticConsumer(Context));
165 Consumers.push_back(AnalysisConsumer);
166 }
Alexander Kornienko175fefb2014-01-03 09:31:57167 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:10184 CheckNames.push_back(AnalyzerCheckNamePrefix + I->first);
Alexander Kornienko175fefb2014-01-03 09:31:57185
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:10193 ArrayRef<StringRef> Checks(StaticAnalyzerChecks);
Alexander Kornienko175fefb2014-01-03 09:31:57194
195 bool AnalyzerChecksEnabled = false;
Alexander Kornienko54461eb2014-02-06 14:50:10196 for (unsigned i = 0; i < Checks.size(); ++i) {
197 std::string Checker((AnalyzerCheckNamePrefix + Checks[i]).str());
Alexander Kornienko175fefb2014-01-03 09:31:57198 AnalyzerChecksEnabled |=
Alexander Kornienko54461eb2014-02-06 14:50:10199 Filter.IsCheckEnabled(Checker) && !Checks[i].startswith("debug");
Alexander Kornienko175fefb2014-01-03 09:31:57200 }
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:05207 // Always add all core checkers if any other static analyzer checks are
Alexander Kornienko175fefb2014-01-03 09:31:57208 // enabled. This is currently necessary, as other path sensitive checks
209 // rely on the core checkers.
Alexander Kornienko54461eb2014-02-06 14:50:10210 for (unsigned i = 0; i < Checks.size(); ++i) {
211 std::string Checker((AnalyzerCheckNamePrefix + Checks[i]).str());
Alexander Kornienkofb9e92b2013-12-19 19:57:05212
Alexander Kornienko54461eb2014-02-06 14:50:10213 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:05216 }
217 }
Alexander Kornienko175fefb2014-01-03 09:31:57218 return List;
219}
Daniel Jasperd07c8402013-07-29 08:19:24220
Alexander Kornienkofb9e92b2013-12-19 19:57:05221ChecksFilter::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:51229DiagnosticBuilder ClangTidyCheck::diag(SourceLocation Loc, StringRef Message) {
230 return Context->diag(CheckName, Loc, Message);
231}
232
Daniel Jasperd07c8402013-07-29 08:19:24233void ClangTidyCheck::run(const ast_matchers::MatchFinder::MatchResult &Result) {
234 Context->setSourceManager(Result.SourceManager);
235 check(Result);
236}
237
Alexander Kornienko41bfe8d2014-01-13 10:50:51238void ClangTidyCheck::setName(StringRef Name) {
239 assert(CheckName.empty());
240 CheckName = Name.str();
241}
242
Alexander Kornienkofb9e92b2013-12-19 19:57:05243std::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:57247 ClangTidyASTConsumerFactory Factory(EnableChecksRegex, DisableChecksRegex,
248 Context);
Alexander Kornienkofb9e92b2013-12-19 19:57:05249 return Factory.getCheckNames();
250}
251
252void runClangTidy(StringRef EnableChecksRegex, StringRef DisableChecksRegex,
Daniel Jasperd07c8402013-07-29 08:19:24253 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:44261
262 Tool.setDiagnosticConsumer(&DiagConsumer);
Alexander Kornienko175fefb2014-01-03 09:31:57263
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:44290}
291
Alexander Kornienko54461eb2014-02-06 14:50:10292static 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:44302static void reportDiagnostic(const ClangTidyMessage &Message,
303 SourceManager &SourceMgr,
304 DiagnosticsEngine::Level Level,
Alexander Kornienko41bfe8d2014-01-13 10:50:51305 DiagnosticsEngine &Diags,
Alexander Kornienko54461eb2014-02-06 14:50:10306 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:24321 }
Daniel Jasperd07c8402013-07-29 08:19:24322}
323
324void handleErrors(SmallVectorImpl<ClangTidyError> &Errors, bool Fix) {
325 FileManager Files((FileSystemOptions()));
Nick Lewyckyccf8e292014-02-06 22:57:16326 LangOptions LangOpts; // FIXME: use langopts from each original file
Daniel Jasperd07c8402013-07-29 08:19:24327 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Alexander Kornienko54461eb2014-02-06 14:50:10328 DiagOpts->ShowColors = llvm::sys::Process::StandardErrHasColors();
Daniel Jasperd07c8402013-07-29 08:19:24329 DiagnosticConsumer *DiagPrinter =
330 new TextDiagnosticPrinter(llvm::outs(), &*DiagOpts);
331 DiagnosticsEngine Diags(IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
332 &*DiagOpts, DiagPrinter);
Nick Lewyckyccf8e292014-02-06 22:57:16333 DiagPrinter->BeginSourceFile(LangOpts);
Daniel Jasperd07c8402013-07-29 08:19:24334 SourceManager SourceMgr(Diags, Files);
Nick Lewyckyccf8e292014-02-06 22:57:16335 Rewriter Rewrite(SourceMgr, LangOpts);
Daniel Jasperd07c8402013-07-29 08:19:24336 for (SmallVectorImpl<ClangTidyError>::iterator I = Errors.begin(),
337 E = Errors.end();
338 I != E; ++I) {
Alexander Kornienko41bfe8d2014-01-13 10:50:51339 reportDiagnostic(I->Message, SourceMgr, DiagnosticsEngine::Warning, Diags,
Alexander Kornienko54461eb2014-02-06 14:50:10340 &I->Fix);
Manuel Klimek814f9bd2013-11-14 15:49:44341 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:24344 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:24351} // namespace tidy
352} // namespace clang