blob: d0a20760cb6f30d5e6bb33deda2213e370fc5b84 [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
Alexander Kornienkocb9272f2014-02-27 13:14:51 +000067 void FlushDiagnosticsImpl(std::vector<const ento::PathDiagnostic *> &Diags,
Craig Toppera3dbe842014-03-02 10:20:11 +000068 FilesMade *filesMade) override {
Alexander Kornienkodf1e3cb2014-03-06 10:17:46 +000069 for (const ento::PathDiagnostic *PD : Diags) {
Alexander Kornienkod1afc702014-02-12 09:52:07 +000070 SmallString<64> CheckName(AnalyzerCheckNamePrefix);
71 CheckName += PD->getCheckName();
Alexander Kornienko95cd50f2014-03-06 13:24:28 +000072 Context.diag(CheckName, PD->getLocation().asLocation(),
73 PD->getShortDescription())
74 << PD->path.back()->getRanges();
Alexander Kornienko54461eb2014-02-06 14:50:10 +000075
Alexander Kornienkodf1e3cb2014-03-06 10:17:46 +000076 for (const auto &DiagPiece :
77 PD->path.flatten(/*ShouldFlattenMacros=*/true)) {
Alexander Kornienko95cd50f2014-03-06 13:24:28 +000078 Context.diag(CheckName, DiagPiece->getLocation().asLocation(),
79 DiagPiece->getString(), DiagnosticIDs::Note)
80 << DiagPiece->getRanges();
Alexander Kornienko54461eb2014-02-06 14:50:10 +000081 }
82 }
83 }
84
Craig Toppera3dbe842014-03-02 10:20:11 +000085 StringRef getName() const override { return "ClangTidyDiags"; }
86 bool supportsLogicalOpControlFlow() const override { return true; }
87 bool supportsCrossFileDiagnostics() const override { return true; }
Alexander Kornienko54461eb2014-02-06 14:50:10 +000088
89private:
90 ClangTidyContext &Context;
Alexander Kornienko54461eb2014-02-06 14:50:10 +000091};
92
Alexander Kornienko175fefb2014-01-03 09:31:57 +000093} // namespace
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +000094
Alexander Kornienko175fefb2014-01-03 09:31:57 +000095ClangTidyASTConsumerFactory::ClangTidyASTConsumerFactory(
96 StringRef EnableChecksRegex, StringRef DisableChecksRegex,
97 ClangTidyContext &Context)
98 : Filter(EnableChecksRegex, DisableChecksRegex), Context(Context),
99 CheckFactories(new ClangTidyCheckFactories) {
100 for (ClangTidyModuleRegistry::iterator I = ClangTidyModuleRegistry::begin(),
101 E = ClangTidyModuleRegistry::end();
102 I != E; ++I) {
Ahmed Charles6a2dc5c2014-03-09 09:24:40 +0000103 std::unique_ptr<ClangTidyModule> Module(I->instantiate());
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000104 Module->addCheckFactories(*CheckFactories);
105 }
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000106
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000107 CheckFactories->createChecks(Filter, Checks);
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000108
Alexander Kornienkodf1e3cb2014-03-06 10:17:46 +0000109 for (ClangTidyCheck *Check : Checks) {
110 Check->setContext(&Context);
111 Check->registerMatchers(&Finder);
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000112 }
113}
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000114
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000115ClangTidyASTConsumerFactory::~ClangTidyASTConsumerFactory() {
Alexander Kornienkodf1e3cb2014-03-06 10:17:46 +0000116 for (ClangTidyCheck *Check : Checks)
117 delete Check;
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000118}
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000119
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000120clang::ASTConsumer *ClangTidyASTConsumerFactory::CreateASTConsumer(
121 clang::CompilerInstance &Compiler, StringRef File) {
122 // FIXME: Move this to a separate method, so that CreateASTConsumer doesn't
123 // modify Compiler.
124 Context.setSourceManager(&Compiler.getSourceManager());
Alexander Kornienkodf1e3cb2014-03-06 10:17:46 +0000125 for (ClangTidyCheck *Check : Checks)
126 Check->registerPPCallbacks(Compiler);
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000127
Alexander Kornienko298b3822014-02-13 16:10:47 +0000128 SmallVector<ASTConsumer *, 2> Consumers;
Alexander Kornienkod68aa4c2014-02-13 16:29:39 +0000129 if (!CheckFactories->empty())
Alexander Kornienko298b3822014-02-13 16:10:47 +0000130 Consumers.push_back(Finder.newASTConsumer());
131
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000132 AnalyzerOptionsRef Options = Compiler.getAnalyzerOpts();
133 Options->CheckersControlList = getCheckersControlList();
Alexander Kornienko298b3822014-02-13 16:10:47 +0000134 if (!Options->CheckersControlList.empty()) {
135 Options->AnalysisStoreOpt = RegionStoreModel;
136 Options->AnalysisDiagOpt = PD_NONE;
137 Options->AnalyzeNestedBlocks = true;
138 Options->eagerlyAssumeBinOpBifurcation = true;
139 ento::AnalysisASTConsumer *AnalysisConsumer = ento::CreateAnalysisConsumer(
140 Compiler.getPreprocessor(), Compiler.getFrontendOpts().OutputFile,
141 Options, Compiler.getFrontendOpts().Plugins);
142 AnalysisConsumer->AddDiagnosticConsumer(
143 new AnalyzerDiagnosticConsumer(Context));
144 Consumers.push_back(AnalysisConsumer);
145 }
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000146 return new MultiplexConsumer(Consumers);
147}
148
149std::vector<std::string> ClangTidyASTConsumerFactory::getCheckNames() {
150 std::vector<std::string> CheckNames;
Alexander Kornienkodf1e3cb2014-03-06 10:17:46 +0000151 for (const auto &CheckFactory : *CheckFactories) {
152 if (Filter.IsCheckEnabled(CheckFactory.first))
153 CheckNames.push_back(CheckFactory.first);
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000154 }
155
Alexander Kornienkodf1e3cb2014-03-06 10:17:46 +0000156 for (const auto &AnalyzerCheck : getCheckersControlList())
157 CheckNames.push_back(AnalyzerCheckNamePrefix + AnalyzerCheck.first);
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000158
159 std::sort(CheckNames.begin(), CheckNames.end());
160 return CheckNames;
161}
162
163ClangTidyASTConsumerFactory::CheckersList
164ClangTidyASTConsumerFactory::getCheckersControlList() {
165 CheckersList List;
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000166
167 bool AnalyzerChecksEnabled = false;
Alexander Kornienkodf1e3cb2014-03-06 10:17:46 +0000168 for (StringRef CheckName : StaticAnalyzerChecks) {
169 std::string Checker((AnalyzerCheckNamePrefix + CheckName).str());
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000170 AnalyzerChecksEnabled |=
Alexander Kornienkodf1e3cb2014-03-06 10:17:46 +0000171 Filter.IsCheckEnabled(Checker) && !CheckName.startswith("debug");
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000172 }
173
174 if (AnalyzerChecksEnabled) {
175 // Run our regex against all possible static analyzer checkers. Note that
176 // debug checkers print values / run programs to visualize the CFG and are
177 // thus not applicable to clang-tidy in general.
178 //
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000179 // Always add all core checkers if any other static analyzer checks are
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000180 // enabled. This is currently necessary, as other path sensitive checks
181 // rely on the core checkers.
Alexander Kornienkodf1e3cb2014-03-06 10:17:46 +0000182 for (StringRef CheckName : StaticAnalyzerChecks) {
183 std::string Checker((AnalyzerCheckNamePrefix + CheckName).str());
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000184
Alexander Kornienkodf1e3cb2014-03-06 10:17:46 +0000185 if (CheckName.startswith("core") ||
186 (!CheckName.startswith("debug") && Filter.IsCheckEnabled(Checker)))
187 List.push_back(std::make_pair(CheckName, true));
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000188 }
189 }
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000190 return List;
191}
Daniel Jasperd07c8402013-07-29 08:19:24 +0000192
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000193ChecksFilter::ChecksFilter(StringRef EnableChecksRegex,
194 StringRef DisableChecksRegex)
195 : EnableChecks(EnableChecksRegex), DisableChecks(DisableChecksRegex) {}
196
197bool ChecksFilter::IsCheckEnabled(StringRef Name) {
198 return EnableChecks.match(Name) && !DisableChecks.match(Name);
199}
200
Peter Collingbourneb17a3b32014-03-02 23:34:48 +0000201DiagnosticBuilder ClangTidyCheck::diag(SourceLocation Loc, StringRef Message,
202 DiagnosticIDs::Level Level) {
203 return Context->diag(CheckName, Loc, Message, Level);
Alexander Kornienko41bfe8d2014-01-13 10:50:51 +0000204}
205
Daniel Jasperd07c8402013-07-29 08:19:24 +0000206void ClangTidyCheck::run(const ast_matchers::MatchFinder::MatchResult &Result) {
207 Context->setSourceManager(Result.SourceManager);
208 check(Result);
209}
210
Alexander Kornienko41bfe8d2014-01-13 10:50:51 +0000211void ClangTidyCheck::setName(StringRef Name) {
212 assert(CheckName.empty());
213 CheckName = Name.str();
214}
215
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000216std::vector<std::string> getCheckNames(StringRef EnableChecksRegex,
217 StringRef DisableChecksRegex) {
218 SmallVector<ClangTidyError, 8> Errors;
219 clang::tidy::ClangTidyContext Context(&Errors);
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000220 ClangTidyASTConsumerFactory Factory(EnableChecksRegex, DisableChecksRegex,
221 Context);
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000222 return Factory.getCheckNames();
223}
224
225void runClangTidy(StringRef EnableChecksRegex, StringRef DisableChecksRegex,
Daniel Jasperd07c8402013-07-29 08:19:24 +0000226 const tooling::CompilationDatabase &Compilations,
227 ArrayRef<std::string> Ranges,
228 SmallVectorImpl<ClangTidyError> *Errors) {
229 // FIXME: Ranges are currently full files. Support selecting specific
230 // (line-)ranges.
231 ClangTool Tool(Compilations, Ranges);
232 clang::tidy::ClangTidyContext Context(Errors);
233 ClangTidyDiagnosticConsumer DiagConsumer(Context);
Manuel Klimek814f9bd2013-11-14 15:49:44 +0000234
235 Tool.setDiagnosticConsumer(&DiagConsumer);
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000236
237 class ActionFactory : public FrontendActionFactory {
238 public:
239 ActionFactory(ClangTidyASTConsumerFactory *ConsumerFactory)
240 : ConsumerFactory(ConsumerFactory) {}
Alexander Kornienko21f3b772014-03-05 13:01:24 +0000241 FrontendAction *create() override { return new Action(ConsumerFactory); }
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000242
243 private:
244 class Action : public ASTFrontendAction {
245 public:
246 Action(ClangTidyASTConsumerFactory *Factory) : Factory(Factory) {}
247 ASTConsumer *CreateASTConsumer(CompilerInstance &Compiler,
Craig Toppera3dbe842014-03-02 10:20:11 +0000248 StringRef File) override {
Alexander Kornienko175fefb2014-01-03 09:31:57 +0000249 return Factory->CreateASTConsumer(Compiler, File);
250 }
251
252 private:
253 ClangTidyASTConsumerFactory *Factory;
254 };
255
256 ClangTidyASTConsumerFactory *ConsumerFactory;
257 };
258
259 Tool.run(new ActionFactory(new ClangTidyASTConsumerFactory(
260 EnableChecksRegex, DisableChecksRegex, Context)));
Manuel Klimek814f9bd2013-11-14 15:49:44 +0000261}
262
Alexander Kornienko54461eb2014-02-06 14:50:10 +0000263static SourceLocation getLocation(SourceManager &SourceMgr, StringRef FilePath,
264 unsigned Offset) {
265 if (FilePath.empty())
266 return SourceLocation();
267
268 const FileEntry *File = SourceMgr.getFileManager().getFile(FilePath);
269 FileID ID = SourceMgr.createFileID(File, SourceLocation(), SrcMgr::C_User);
270 return SourceMgr.getLocForStartOfFile(ID).getLocWithOffset(Offset);
271}
272
Manuel Klimek814f9bd2013-11-14 15:49:44 +0000273static void reportDiagnostic(const ClangTidyMessage &Message,
274 SourceManager &SourceMgr,
275 DiagnosticsEngine::Level Level,
Alexander Kornienko41bfe8d2014-01-13 10:50:51 +0000276 DiagnosticsEngine &Diags,
Alexander Kornienkodf1e3cb2014-03-06 10:17:46 +0000277 const tooling::Replacements *Fixes = NULL) {
Alexander Kornienko54461eb2014-02-06 14:50:10 +0000278 SourceLocation Loc =
279 getLocation(SourceMgr, Message.FilePath, Message.FileOffset);
280 DiagnosticBuilder Diag = Diags.Report(Loc, Diags.getCustomDiagID(Level, "%0"))
281 << Message.Message;
282 if (Fixes != NULL) {
Alexander Kornienkodf1e3cb2014-03-06 10:17:46 +0000283 for (const tooling::Replacement &Fix : *Fixes) {
Alexander Kornienko54461eb2014-02-06 14:50:10 +0000284 SourceLocation FixLoc =
Alexander Kornienkodf1e3cb2014-03-06 10:17:46 +0000285 getLocation(SourceMgr, Fix.getFilePath(), Fix.getOffset());
Alexander Kornienko54461eb2014-02-06 14:50:10 +0000286 Diag << FixItHint::CreateReplacement(
Alexander Kornienkodf1e3cb2014-03-06 10:17:46 +0000287 SourceRange(FixLoc, FixLoc.getLocWithOffset(Fix.getLength())),
288 Fix.getReplacementText());
Alexander Kornienko54461eb2014-02-06 14:50:10 +0000289 }
Daniel Jasperd07c8402013-07-29 08:19:24 +0000290 }
Daniel Jasperd07c8402013-07-29 08:19:24 +0000291}
292
293void handleErrors(SmallVectorImpl<ClangTidyError> &Errors, bool Fix) {
294 FileManager Files((FileSystemOptions()));
Nick Lewyckyccf8e292014-02-06 22:57:16 +0000295 LangOptions LangOpts; // FIXME: use langopts from each original file
Daniel Jasperd07c8402013-07-29 08:19:24 +0000296 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Craig Topper6d73f442014-03-03 07:37:42 +0000297 DiagOpts->ShowColors = llvm::sys::Process::StandardOutHasColors();
Daniel Jasperd07c8402013-07-29 08:19:24 +0000298 DiagnosticConsumer *DiagPrinter =
299 new TextDiagnosticPrinter(llvm::outs(), &*DiagOpts);
300 DiagnosticsEngine Diags(IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
301 &*DiagOpts, DiagPrinter);
Nick Lewyckyccf8e292014-02-06 22:57:16 +0000302 DiagPrinter->BeginSourceFile(LangOpts);
Daniel Jasperd07c8402013-07-29 08:19:24 +0000303 SourceManager SourceMgr(Diags, Files);
Nick Lewyckyccf8e292014-02-06 22:57:16 +0000304 Rewriter Rewrite(SourceMgr, LangOpts);
Alexander Kornienkodf1e3cb2014-03-06 10:17:46 +0000305 for (const ClangTidyError &Error : Errors) {
306 reportDiagnostic(Error.Message, SourceMgr, DiagnosticsEngine::Warning, Diags,
307 &Error.Fix);
308 for (const ClangTidyMessage &Note : Error.Notes)
309 reportDiagnostic(Note, SourceMgr, DiagnosticsEngine::Note, Diags);
310
311 tooling::applyAllReplacements(Error.Fix, Rewrite);
Daniel Jasperd07c8402013-07-29 08:19:24 +0000312 }
313 // FIXME: Run clang-format on changes.
314 if (Fix)
315 Rewrite.overwriteChangedFiles();
316}
317
Daniel Jasperd07c8402013-07-29 08:19:24 +0000318} // namespace tidy
319} // namespace clang