21 #include "clang/AST/ASTConsumer.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/Decl.h"
24 #include "clang/ASTMatchers/ASTMatchFinder.h"
25 #include "clang/Frontend/ASTConsumers.h"
26 #include "clang/Frontend/CompilerInstance.h"
27 #include "clang/Frontend/FrontendActions.h"
28 #include "clang/Frontend/FrontendDiagnostic.h"
29 #include "clang/Frontend/MultiplexConsumer.h"
30 #include "clang/Frontend/TextDiagnosticPrinter.h"
31 #include "clang/Lex/PPCallbacks.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Rewrite/Frontend/FixItRewriter.h"
34 #include "clang/Rewrite/Frontend/FrontendActions.h"
35 #include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
36 #include "clang/Tooling/Refactoring.h"
37 #include "clang/Tooling/ReplacementsYaml.h"
38 #include "clang/Tooling/Tooling.h"
39 #include "llvm/Support/Process.h"
40 #include "llvm/Support/Signals.h"
44 using namespace clang::ast_matchers;
45 using namespace clang::driver;
46 using namespace clang::tooling;
49 template class llvm::Registry<clang::tidy::ClangTidyModule>;
55 static const char *AnalyzerCheckNamePrefix =
"clang-analyzer-";
57 static const StringRef StaticAnalyzerChecks[] = {
59 #define CHECKER(FULLNAME, CLASS, DESCFILE, HELPTEXT, GROUPINDEX, HIDDEN) \
61 #include "../../../lib/StaticAnalyzer/Checkers/Checkers.inc"
66 class AnalyzerDiagnosticConsumer :
public ento::PathDiagnosticConsumer {
68 AnalyzerDiagnosticConsumer(ClangTidyContext &
Context) : Context(Context) {}
70 void FlushDiagnosticsImpl(std::vector<const ento::PathDiagnostic *> &
Diags,
71 FilesMade *filesMade)
override {
72 for (
const ento::PathDiagnostic *PD : Diags) {
73 SmallString<64> CheckName(AnalyzerCheckNamePrefix);
74 CheckName += PD->getCheckName();
75 Context.diag(CheckName, PD->getLocation().asLocation(),
76 PD->getShortDescription())
77 << PD->path.back()->getRanges();
79 for (
const auto &DiagPiece :
80 PD->path.flatten(
true)) {
81 Context.diag(CheckName, DiagPiece->getLocation().asLocation(),
82 DiagPiece->getString(), DiagnosticIDs::Note)
83 << DiagPiece->getRanges();
88 StringRef getName()
const override {
return "ClangTidyDiags"; }
89 bool supportsLogicalOpControlFlow()
const override {
return true; }
90 bool supportsCrossFileDiagnostics()
const override {
return true; }
99 :
Files(FileSystemOptions()),
DiagOpts(
new DiagnosticOptions()),
101 Diags(IntrusiveRefCntPtr<DiagnosticIDs>(
new DiagnosticIDs), &*
DiagOpts,
105 DiagOpts->ShowColors = llvm::sys::Process::StandardOutHasColors();
109 void reportDiagnostic(
const ClangTidyError &Error) {
110 const ClangTidyMessage &Message = Error.Message;
111 SourceLocation
Loc = getLocation(Message.FilePath, Message.FileOffset);
114 SmallVector<std::pair<SourceLocation, bool>, 4> FixLocations;
116 auto Level =
static_cast<DiagnosticsEngine::Level
>(Error.DiagLevel);
117 auto Diag = Diags.Report(Loc, Diags.getCustomDiagID(Level,
"%0 [%1]"))
118 << Message.Message << Error.CheckName;
119 for (
const tooling::Replacement &
Fix : Error.Fix) {
120 SourceLocation FixLoc = getLocation(Fix.getFilePath(), Fix.getOffset());
121 SourceLocation FixEndLoc = FixLoc.getLocWithOffset(Fix.getLength());
122 Diag << FixItHint::CreateReplacement(SourceRange(FixLoc, FixEndLoc),
123 Fix.getReplacementText());
126 bool Success = Fix.isApplicable() && Fix.apply(
Rewrite);
129 FixLocations.push_back(std::make_pair(FixLoc, Success));
133 for (
auto Fix : FixLocations) {
134 Diags.Report(Fix.first, Fix.second ? diag::note_fixit_applied
135 : diag::note_fixit_failed);
137 for (
const ClangTidyMessage &Note : Error.Notes)
143 if (ApplyFixes && TotalFixes > 0) {
144 llvm::errs() <<
"clang-tidy applied " <<
AppliedFixes <<
" of "
145 << TotalFixes <<
" suggested fixes.\n";
146 Rewrite.overwriteChangedFiles();
151 SourceLocation getLocation(StringRef FilePath,
unsigned Offset) {
152 if (FilePath.empty())
153 return SourceLocation();
155 const FileEntry *
File =
SourceMgr.getFileManager().getFile(FilePath);
156 FileID ID =
SourceMgr.createFileID(File, SourceLocation(), SrcMgr::C_User);
157 return SourceMgr.getLocForStartOfFile(ID).getLocWithOffset(Offset);
160 void reportNote(
const ClangTidyMessage &Message) {
161 SourceLocation Loc = getLocation(Message.FilePath, Message.FileOffset);
162 DiagnosticBuilder Diag =
163 Diags.Report(Loc, Diags.getCustomDiagID(DiagnosticsEngine::Note,
"%0"))
179 class ClangTidyASTConsumer :
public MultiplexConsumer {
181 ClangTidyASTConsumer(std::vector<std::unique_ptr<ASTConsumer>> Consumers,
182 std::unique_ptr<ast_matchers::MatchFinder>
Finder,
183 std::vector<std::unique_ptr<ClangTidyCheck>>
Checks)
184 : MultiplexConsumer(std::move(Consumers)),
Finder(std::move(Finder)),
188 std::unique_ptr<ast_matchers::MatchFinder>
Finder;
189 std::vector<std::unique_ptr<ClangTidyCheck>>
Checks;
194 ClangTidyASTConsumerFactory::ClangTidyASTConsumerFactory(
197 for (ClangTidyModuleRegistry::iterator I = ClangTidyModuleRegistry::begin(),
198 E = ClangTidyModuleRegistry::end();
200 std::unique_ptr<ClangTidyModule> Module(I->instantiate());
201 Module->addCheckFactories(*CheckFactories);
206 AnalyzerOptionsRef AnalyzerOptions) {
207 StringRef AnalyzerPrefix(AnalyzerCheckNamePrefix);
209 StringRef OptName(Opt.first);
210 if (!OptName.startswith(AnalyzerPrefix))
212 AnalyzerOptions->Config[OptName.substr(AnalyzerPrefix.size())] = Opt.second;
216 std::unique_ptr<clang::ASTConsumer>
218 clang::CompilerInstance &Compiler, StringRef File) {
225 std::vector<std::unique_ptr<ClangTidyCheck>>
Checks;
226 CheckFactories->createChecks(&Context, Checks);
228 ast_matchers::MatchFinder::MatchFinderOptions FinderOptions;
230 FinderOptions.CheckProfiling.emplace(P->Records);
232 std::unique_ptr<ast_matchers::MatchFinder>
Finder(
233 new ast_matchers::MatchFinder(std::move(FinderOptions)));
235 for (
auto &
Check : Checks) {
236 Check->registerMatchers(&*Finder);
237 Check->registerPPCallbacks(Compiler);
240 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
242 Consumers.push_back(Finder->newASTConsumer());
244 AnalyzerOptionsRef AnalyzerOptions = Compiler.getAnalyzerOpts();
247 AnalyzerOptions->Config[
"cfg-temporary-dtors"] =
251 AnalyzerOptions->CheckersControlList = getCheckersControlList(Filter);
252 if (!AnalyzerOptions->CheckersControlList.empty()) {
254 AnalyzerOptions->AnalysisStoreOpt = RegionStoreModel;
255 AnalyzerOptions->AnalysisDiagOpt = PD_NONE;
256 AnalyzerOptions->AnalyzeNestedBlocks =
true;
257 AnalyzerOptions->eagerlyAssumeBinOpBifurcation =
true;
258 std::unique_ptr<ento::AnalysisASTConsumer> AnalysisConsumer =
259 ento::CreateAnalysisConsumer(Compiler);
260 AnalysisConsumer->AddDiagnosticConsumer(
261 new AnalyzerDiagnosticConsumer(Context));
262 Consumers.push_back(std::move(AnalysisConsumer));
264 return llvm::make_unique<ClangTidyASTConsumer>(
265 std::move(Consumers), std::move(Finder), std::move(Checks));
269 std::vector<std::string> CheckNames;
271 for (
const auto &CheckFactory : *CheckFactories) {
272 if (Filter.
contains(CheckFactory.first))
273 CheckNames.push_back(CheckFactory.first);
276 for (
const auto &AnalyzerCheck : getCheckersControlList(Filter))
277 CheckNames.push_back(AnalyzerCheckNamePrefix + AnalyzerCheck.first);
279 std::sort(CheckNames.begin(), CheckNames.end());
285 std::vector<std::unique_ptr<ClangTidyCheck>>
Checks;
286 CheckFactories->createChecks(&Context, Checks);
287 for (
const auto &
Check : Checks)
288 Check->storeOptions(Options);
292 ClangTidyASTConsumerFactory::CheckersList
293 ClangTidyASTConsumerFactory::getCheckersControlList(
GlobList &Filter) {
296 bool AnalyzerChecksEnabled =
false;
297 for (StringRef CheckName : StaticAnalyzerChecks) {
298 std::string Checker((AnalyzerCheckNamePrefix + CheckName).str());
299 AnalyzerChecksEnabled =
300 AnalyzerChecksEnabled ||
301 (!CheckName.startswith(
"debug") && Filter.
contains(Checker));
304 if (AnalyzerChecksEnabled) {
312 for (StringRef CheckName : StaticAnalyzerChecks) {
313 std::string Checker((AnalyzerCheckNamePrefix + CheckName).str());
315 if (CheckName.startswith(
"core") ||
316 (!CheckName.startswith(
"debug") && Filter.
contains(Checker)))
317 List.push_back(std::make_pair(CheckName,
true));
324 DiagnosticIDs::Level Level) {
325 return Context->
diag(CheckName, Loc, Message, Level);
328 void ClangTidyCheck::run(
const ast_matchers::MatchFinder::MatchResult &
Result) {
335 : NamePrefix(CheckName.str() +
"."), CheckOptions(CheckOptions) {}
338 const auto &Iter = CheckOptions.find(NamePrefix + LocalName.str());
339 if (Iter != CheckOptions.end())
345 StringRef LocalName, StringRef Value)
const {
346 Options[NamePrefix + LocalName.str()] = Value;
350 StringRef LocalName, int64_t Value)
const {
351 store(Options, LocalName, llvm::itostr(Value));
371 runClangTidy(std::unique_ptr<ClangTidyOptionsProvider> OptionsProvider,
372 const tooling::CompilationDatabase &Compilations,
373 ArrayRef<std::string> InputFiles,
374 std::vector<ClangTidyError> *Errors,
ProfileData *Profile) {
375 ClangTool Tool(Compilations, InputFiles);
377 ArgumentsAdjuster PerFileExtraArgumentsInserter = [&
Context](
378 const CommandLineArguments &Args, StringRef
Filename) {
380 CommandLineArguments AdjustedArgs;
383 AdjustedArgs.insert(AdjustedArgs.begin(), Args.begin(), Args.end());
385 AdjustedArgs.insert(AdjustedArgs.end(), Opts.
ExtraArgs->begin(),
389 Tool.appendArgumentsAdjuster(PerFileExtraArgumentsInserter);
395 Tool.setDiagnosticConsumer(&DiagConsumer);
400 FrontendAction *create()
override {
return new Action(&ConsumerFactory); }
403 class Action :
public ASTFrontendAction {
406 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
407 StringRef File)
override {
418 ActionFactory Factory(Context);
424 void handleErrors(
const std::vector<ClangTidyError> &Errors,
bool Fix) {
425 ErrorReporter Reporter(Fix);
427 Reporter.reportDiagnostic(Error);
433 tooling::TranslationUnitReplacements TUR;
435 TUR.Replacements.insert(TUR.Replacements.end(), Error.Fix.begin(),
438 yaml::Output YAML(OS);
SourceLocation Loc
'#' location in the include directive
std::vector< std::string > getCheckNames()
Get the list of enabled checks.
llvm::Optional< ArgList > ExtraArgs
Add extra compilation arguments to the end of the list.
std::string get(StringRef LocalName, std::string Default) const
Read a named option from the Context.
Read-only set of strings represented as a list of positive and negative globs.
std::unique_ptr< ast_matchers::MatchFinder > Finder
ClangTidyOptions::OptionMap getCheckOptions()
Get the union of options from all checks.
std::vector< std::unique_ptr< ClangTidyCheck > > Checks
bool contains(StringRef S)
Returns true if the pattern matches S.
ClangTidyOptions::OptionMap getCheckOptions(const ClangTidyOptions &Options)
Returns the effective check-specific options.
Contains options for clang-tidy.
ProfileData * getCheckProfileData() const
A collection of ClangTidyCheckFactory instances.
const std::vector< ClangTidyError > & getErrors() const
Returns all collected errors.
OptionMap CheckOptions
Key-value mapping used to store check-specific options.
llvm::Optional< ArgList > ExtraArgsBefore
Add extra compilation arguments to the start of the list.
ClangTidyOptions getOptionsForFile(StringRef File) const
Returns options for File.
void exportReplacements(const std::vector< ClangTidyError > &Errors, raw_ostream &OS)
Serializes replacements into YAML and writes them to the specified output stream. ...
void handleErrors(const std::vector< ClangTidyError > &Errors, bool Fix)
Displays the found Errors to the users.
void setCurrentFile(StringRef File)
Should be called when starting to process new translation unit.
const ClangTidyOptions & getOptions() const
Returns options for CurrentFile.
std::string Filename
Filename as a string.
DiagnosticBuilder diag(StringRef CheckName, SourceLocation Loc, StringRef Message, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Report any errors detected using this method.
void setCheckProfileData(ProfileData *Profile)
Set the output struct for profile data.
void setASTContext(ASTContext *Context)
Sets ASTContext for the current translation unit.
A diagnostic consumer that turns each Diagnostic into a SourceManager-independent ClangTidyError...
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
std::map< std::string, std::string > OptionMap
std::vector< std::string > getCheckNames(const ClangTidyOptions &Options)
Fills the list of check names that are enabled when the provided filters are applied.
ClangTidyStats runClangTidy(std::unique_ptr< ClangTidyOptionsProvider > OptionsProvider, const tooling::CompilationDatabase &Compilations, ArrayRef< std::string > InputFiles, std::vector< ClangTidyError > *Errors, ProfileData *Profile)
Run a set of clang-tidy checks on a set of files.
static void setStaticAnalyzerCheckerOpts(const ClangTidyOptions &Opts, AnalyzerOptionsRef AnalyzerOptions)
void setSourceManager(SourceManager *SourceMgr)
Sets the SourceManager of the used DiagnosticsEngine.
OptionsView(StringRef CheckName, const ClangTidyOptions::OptionMap &CheckOptions)
Initializes the instance using CheckName + "." as a prefix.
llvm::Optional< bool > AnalyzeTemporaryDtors
Turns on temporary destructor-based analysis.
const ClangTidyStats & getStats() const
Returns ClangTidyStats containing issued and ignored diagnostic counters.
A detected error complete with information to display diagnostic and automatic fix.
IntrusiveRefCntPtr< DiagnosticOptions > DiagOpts
ClangTidyContext & Context
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
std::unique_ptr< clang::ASTConsumer > CreateASTConsumer(clang::CompilerInstance &Compiler, StringRef File)
Returns an ASTConsumer that runs the specified clang-tidy checks.
static cl::opt< bool > Fix("fix", cl::desc("Apply suggested fixes. Without -fix-errors\n""clang-tidy will bail out if any compilation\n""errors were found."), cl::init(false), cl::cat(ClangTidyCategory))
virtual void check(const ast_matchers::MatchFinder::MatchResult &Result)
ClangTidyChecks that register ASTMatchers should do the actual work in here.
GlobList & getChecksFilter()
Returns check filter for the CurrentFile.
Container for clang-tidy profiling data.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
DiagnosticConsumer * DiagPrinter