22 #include "clang/AST/ASTConsumer.h" 23 #include "clang/AST/ASTContext.h" 24 #include "clang/AST/Decl.h" 25 #include "clang/ASTMatchers/ASTMatchFinder.h" 26 #include "clang/Config/config.h" 27 #include "clang/Format/Format.h" 28 #include "clang/Frontend/ASTConsumers.h" 29 #include "clang/Frontend/CompilerInstance.h" 30 #include "clang/Frontend/FrontendActions.h" 31 #include "clang/Frontend/FrontendDiagnostic.h" 32 #include "clang/Frontend/MultiplexConsumer.h" 33 #include "clang/Frontend/TextDiagnosticPrinter.h" 34 #include "clang/Lex/PPCallbacks.h" 35 #include "clang/Lex/Preprocessor.h" 36 #include "clang/Rewrite/Frontend/FixItRewriter.h" 37 #include "clang/Rewrite/Frontend/FrontendActions.h" 38 #include "clang/Tooling/Core/Diagnostic.h" 39 #if CLANG_ENABLE_STATIC_ANALYZER 40 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" 41 #include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h" 42 #endif // CLANG_ENABLE_STATIC_ANALYZER 43 #include "clang/Tooling/DiagnosticsYaml.h" 44 #include "clang/Tooling/Refactoring.h" 45 #include "clang/Tooling/ReplacementsYaml.h" 46 #include "clang/Tooling/Tooling.h" 47 #include "llvm/Support/Process.h" 48 #include "llvm/Support/Signals.h" 63 #if CLANG_ENABLE_STATIC_ANALYZER 64 static const char *AnalyzerCheckNamePrefix =
"clang-analyzer-";
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; }
93 ClangTidyContext &Context;
95 #endif // CLANG_ENABLE_STATIC_ANALYZER 99 ErrorReporter(ClangTidyContext &Context,
bool ApplyFixes,
100 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS)
101 :
Files(FileSystemOptions(), BaseFS), DiagOpts(new DiagnosticOptions()),
102 DiagPrinter(new TextDiagnosticPrinter(
llvm::outs(), &*DiagOpts)),
103 Diags(IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), &*DiagOpts,
105 SourceMgr(Diags,
Files), Context(Context), ApplyFixes(ApplyFixes),
107 DiagOpts->ShowColors = llvm::sys::Process::StandardOutHasColors();
108 DiagPrinter->BeginSourceFile(LangOpts);
111 SourceManager &getSourceManager() {
return SourceMgr; }
113 void reportDiagnostic(
const ClangTidyError &Error) {
114 const tooling::DiagnosticMessage &
Message = Error.Message;
115 SourceLocation
Loc = getLocation(Message.FilePath, Message.FileOffset);
118 SmallVector<std::pair<SourceLocation, bool>, 4> FixLocations;
120 auto Level =
static_cast<DiagnosticsEngine::Level
>(Error.DiagLevel);
121 std::string
Name = Error.DiagnosticName;
122 if (Error.IsWarningAsError) {
123 Name +=
",-warnings-as-errors";
124 Level = DiagnosticsEngine::Error;
127 auto Diag = Diags.Report(Loc, Diags.getCustomDiagID(Level,
"%0 [%1]"))
128 << Message.Message << Name;
130 const llvm::StringMap<Replacements> *ChosenFix = selectFirstFix(Error);
131 if (ApplyFixes && ChosenFix) {
132 for (
const auto &FileAndReplacements : *ChosenFix) {
133 for (
const auto &Repl : FileAndReplacements.second) {
135 bool CanBeApplied =
false;
136 if (!Repl.isApplicable())
138 SourceLocation FixLoc;
139 SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
140 Files.makeAbsolutePath(FixAbsoluteFilePath);
141 tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
142 Repl.getLength(), Repl.getReplacementText());
143 Replacements &Replacements = FileReplacements[R.getFilePath()];
144 llvm::Error Err = Replacements.add(R);
147 llvm::errs() <<
"Trying to resolve conflict: " 150 Replacements.getShiftedCodePosition(R.getOffset());
151 unsigned NewLength = Replacements.getShiftedCodePosition(
152 R.getOffset() + R.getLength()) -
154 if (NewLength == R.getLength()) {
155 R = Replacement(R.getFilePath(), NewOffset, NewLength,
156 R.getReplacementText());
157 Replacements = Replacements.merge(tooling::Replacements(R));
162 <<
"Can't resolve conflict, skipping the replacement.\n";
168 FixLoc = getLocation(FixAbsoluteFilePath, Repl.getOffset());
169 FixLocations.push_back(std::make_pair(FixLoc, CanBeApplied));
173 reportFix(Diag, Error.Message.Fix);
175 for (
auto Fix : FixLocations) {
176 Diags.Report(
Fix.first,
Fix.second ? diag::note_fixit_applied
177 : diag::note_fixit_failed);
179 for (
const auto &Note : Error.Notes)
184 if (ApplyFixes && TotalFixes > 0) {
185 Rewriter Rewrite(SourceMgr, LangOpts);
186 for (
const auto &FileAndReplacements : FileReplacements) {
187 StringRef File = FileAndReplacements.first();
188 llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
189 SourceMgr.getFileManager().getBufferForFile(File);
191 llvm::errs() <<
"Can't get buffer for file " << File <<
": " 192 << Buffer.getError().message() <<
"\n";
196 StringRef Code = Buffer.get()->getBuffer();
197 auto Style = format::getStyle(
198 *Context.getOptionsForFile(File).FormatStyle, File,
"none");
203 llvm::Expected<tooling::Replacements> Replacements =
204 format::cleanupAroundReplacements(Code, FileAndReplacements.second,
210 if (llvm::Expected<tooling::Replacements> FormattedReplacements =
211 format::formatReplacements(Code, *Replacements, *Style)) {
212 Replacements = std::move(FormattedReplacements);
214 llvm_unreachable(
"!Replacements");
217 <<
". Skipping formatting.\n";
219 if (!tooling::applyAllReplacements(Replacements.get(), Rewrite)) {
220 llvm::errs() <<
"Can't apply replacements for file " << File <<
"\n";
223 if (Rewrite.overwriteChangedFiles()) {
224 llvm::errs() <<
"clang-tidy failed to apply suggested fixes.\n";
226 llvm::errs() <<
"clang-tidy applied " << AppliedFixes <<
" of " 227 << TotalFixes <<
" suggested fixes.\n";
235 SourceLocation getLocation(StringRef FilePath,
unsigned Offset) {
236 if (FilePath.empty())
237 return SourceLocation();
239 const FileEntry *File = SourceMgr.getFileManager().getFile(FilePath);
240 FileID ID = SourceMgr.getOrCreateFileID(File, SrcMgr::C_User);
241 return SourceMgr.getLocForStartOfFile(ID).getLocWithOffset(Offset);
244 void reportFix(
const DiagnosticBuilder &Diag,
245 const llvm::StringMap<Replacements> &
Fix) {
246 for (
const auto &FileAndReplacements : Fix) {
247 for (
const auto &Repl : FileAndReplacements.second) {
248 if (!Repl.isApplicable())
250 SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
251 Files.makeAbsolutePath(FixAbsoluteFilePath);
252 SourceLocation FixLoc =
253 getLocation(FixAbsoluteFilePath, Repl.getOffset());
254 SourceLocation FixEndLoc = FixLoc.getLocWithOffset(Repl.getLength());
258 CharSourceRange
Range =
259 CharSourceRange::getCharRange(SourceRange(FixLoc, FixEndLoc));
260 Diag << FixItHint::CreateReplacement(Range, Repl.getReplacementText());
265 void reportNote(
const tooling::DiagnosticMessage &Message) {
266 SourceLocation Loc = getLocation(Message.FilePath, Message.FileOffset);
268 Diags.Report(Loc, Diags.getCustomDiagID(DiagnosticsEngine::Note,
"%0"))
270 reportFix(Diag, Message.Fix);
274 LangOptions LangOpts;
275 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
277 DiagnosticsEngine Diags;
278 SourceManager SourceMgr;
279 llvm::StringMap<Replacements> FileReplacements;
280 ClangTidyContext &Context;
283 unsigned AppliedFixes;
289 ClangTidyASTConsumer(std::vector<std::unique_ptr<ASTConsumer>> Consumers,
290 std::unique_ptr<ClangTidyProfiling> Profiling,
291 std::unique_ptr<ast_matchers::MatchFinder> Finder,
292 std::vector<std::unique_ptr<ClangTidyCheck>>
Checks)
294 Profiling(std::move(Profiling)), Finder(std::move(Finder)),
300 std::unique_ptr<ClangTidyProfiling> Profiling;
301 std::unique_ptr<ast_matchers::MatchFinder> Finder;
302 std::vector<std::unique_ptr<ClangTidyCheck>>
Checks;
307 ClangTidyASTConsumerFactory::ClangTidyASTConsumerFactory(
309 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS)
310 : Context(Context), OverlayFS(OverlayFS),
312 for (ClangTidyModuleRegistry::iterator I = ClangTidyModuleRegistry::begin(),
313 E = ClangTidyModuleRegistry::end();
315 std::unique_ptr<ClangTidyModule> Module(I->instantiate());
316 Module->addCheckFactories(*CheckFactories);
320 #if CLANG_ENABLE_STATIC_ANALYZER 322 AnalyzerOptionsRef AnalyzerOptions) {
323 StringRef AnalyzerPrefix(AnalyzerCheckNamePrefix);
325 StringRef OptName(Opt.first);
326 if (!OptName.startswith(AnalyzerPrefix))
328 AnalyzerOptions->Config[OptName.substr(AnalyzerPrefix.size())] = Opt.second;
332 typedef std::vector<std::pair<std::string, bool>> CheckersList;
335 bool IncludeExperimental) {
338 const auto &RegisteredCheckers =
339 AnalyzerOptions::getRegisteredCheckers(IncludeExperimental);
340 bool AnalyzerChecksEnabled =
false;
341 for (StringRef CheckName : RegisteredCheckers) {
342 std::string ClangTidyCheckName((AnalyzerCheckNamePrefix + CheckName).str());
343 AnalyzerChecksEnabled |= Context.
isCheckEnabled(ClangTidyCheckName);
346 if (!AnalyzerChecksEnabled)
354 for (StringRef CheckName : RegisteredCheckers) {
355 std::string ClangTidyCheckName((AnalyzerCheckNamePrefix + CheckName).str());
357 if (CheckName.startswith(
"core") ||
359 List.emplace_back(CheckName,
true);
364 #endif // CLANG_ENABLE_STATIC_ANALYZER 366 std::unique_ptr<clang::ASTConsumer>
368 clang::CompilerInstance &Compiler, StringRef File) {
371 SourceManager *SM = &Compiler.getSourceManager();
376 auto WorkingDir = Compiler.getSourceManager()
378 .getVirtualFileSystem()
379 .getCurrentWorkingDirectory();
383 std::vector<std::unique_ptr<ClangTidyCheck>>
Checks;
384 CheckFactories->createChecks(&Context, Checks);
386 ast_matchers::MatchFinder::MatchFinderOptions FinderOptions;
388 std::unique_ptr<ClangTidyProfiling> Profiling;
390 Profiling = llvm::make_unique<ClangTidyProfiling>(
392 FinderOptions.CheckProfiling.emplace(Profiling->Records);
395 std::unique_ptr<ast_matchers::MatchFinder> Finder(
396 new ast_matchers::MatchFinder(std::move(FinderOptions)));
398 Preprocessor *PP = &Compiler.getPreprocessor();
399 Preprocessor *ModuleExpanderPP = PP;
401 if (Context.
getLangOpts().Modules && OverlayFS !=
nullptr) {
402 auto ModuleExpander = llvm::make_unique<ExpandModularHeadersPPCallbacks>(
403 &Compiler, OverlayFS);
404 ModuleExpanderPP = ModuleExpander->getPreprocessor();
405 PP->addPPCallbacks(std::move(ModuleExpander));
408 for (
auto &Check : Checks) {
409 Check->registerMatchers(&*Finder);
410 Check->registerPPCallbacks(*SM, PP, ModuleExpanderPP);
413 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
415 Consumers.push_back(Finder->newASTConsumer());
417 #if CLANG_ENABLE_STATIC_ANALYZER 418 AnalyzerOptionsRef AnalyzerOptions = Compiler.getAnalyzerOpts();
419 AnalyzerOptions->CheckersControlList =
421 if (!AnalyzerOptions->CheckersControlList.empty()) {
422 setStaticAnalyzerCheckerOpts(Context.
getOptions(), AnalyzerOptions);
423 AnalyzerOptions->AnalysisStoreOpt = RegionStoreModel;
424 AnalyzerOptions->AnalysisDiagOpt = PD_NONE;
425 AnalyzerOptions->AnalyzeNestedBlocks =
true;
426 AnalyzerOptions->eagerlyAssumeBinOpBifurcation =
true;
427 std::unique_ptr<ento::AnalysisASTConsumer> AnalysisConsumer =
428 ento::CreateAnalysisConsumer(Compiler);
429 AnalysisConsumer->AddDiagnosticConsumer(
430 new AnalyzerDiagnosticConsumer(Context));
431 Consumers.push_back(std::move(AnalysisConsumer));
433 #endif // CLANG_ENABLE_STATIC_ANALYZER 434 return llvm::make_unique<ClangTidyASTConsumer>(
435 std::move(Consumers), std::move(Profiling), std::move(Finder),
440 std::vector<std::string> CheckNames;
441 for (
const auto &CheckFactory : *CheckFactories) {
443 CheckNames.push_back(CheckFactory.first);
446 #if CLANG_ENABLE_STATIC_ANALYZER 447 for (
const auto &AnalyzerCheck : getCheckersControlList(
449 CheckNames.push_back(AnalyzerCheckNamePrefix + AnalyzerCheck.first);
450 #endif // CLANG_ENABLE_STATIC_ANALYZER 452 std::sort(CheckNames.begin(), CheckNames.end());
458 std::vector<std::unique_ptr<ClangTidyCheck>>
Checks;
459 CheckFactories->createChecks(&Context, Checks);
460 for (
const auto &Check : Checks)
461 Check->storeOptions(Options);
465 std::vector<std::string>
471 AllowEnablingAnalyzerAlphaCheckers);
482 AllowEnablingAnalyzerAlphaCheckers);
487 std::vector<ClangTidyError>
489 const CompilationDatabase &Compilations,
490 ArrayRef<std::string> InputFiles,
491 llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
493 ClangTool Tool(Compilations, InputFiles,
494 std::make_shared<PCHContainerOperations>(), BaseFS);
497 ArgumentsAdjuster PerFileExtraArgumentsInserter =
498 [&Context](
const CommandLineArguments &Args, StringRef
Filename) {
500 CommandLineArguments AdjustedArgs = Args;
502 auto I = AdjustedArgs.begin();
503 if (I != AdjustedArgs.end() && !StringRef(*I).startswith(
"-"))
509 AdjustedArgs.insert(AdjustedArgs.end(), Opts.
ExtraArgs->begin(),
514 Tool.appendArgumentsAdjuster(PerFileExtraArgumentsInserter);
515 Tool.appendArgumentsAdjuster(getStripPluginsAdjuster());
520 DiagnosticsEngine DE(
new DiagnosticIDs(),
new DiagnosticOptions(),
521 &DiagConsumer,
false);
523 Tool.setDiagnosticConsumer(&DiagConsumer);
525 class ActionFactory :
public FrontendActionFactory {
528 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS)
529 : ConsumerFactory(Context, BaseFS) {}
530 FrontendAction *create()
override {
return new Action(&ConsumerFactory); }
532 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
534 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
539 Invocation->getFrontendOpts().ProgramAction = frontend::RunAnalysis;
540 return FrontendActionFactory::runInvocation(
541 Invocation, Files, PCHContainerOps, DiagConsumer);
545 class Action :
public ASTFrontendAction {
549 StringRef File)
override {
560 ActionFactory Factory(Context, BaseFS);
562 return DiagConsumer.
take();
567 unsigned &WarningsAsErrorsCount,
568 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
569 ErrorReporter Reporter(Context, Fix, BaseFS);
570 llvm::vfs::FileSystem &FileSystem =
571 Reporter.getSourceManager().getFileManager().getVirtualFileSystem();
572 auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();
573 if (!InitialWorkingDir)
574 llvm::report_fatal_error(
"Cannot get current working path.");
577 if (!Error.BuildDirectory.empty()) {
582 FileSystem.setCurrentWorkingDirectory(Error.BuildDirectory);
584 Reporter.reportDiagnostic(Error);
586 FileSystem.setCurrentWorkingDirectory(InitialWorkingDir.get());
589 WarningsAsErrorsCount += Reporter.getWarningsAsErrorsCount();
593 const std::vector<ClangTidyError> &Errors,
595 TranslationUnitDiagnostics TUD;
596 TUD.MainSourceFile = MainFilePath;
597 for (
const auto &Error : Errors) {
598 tooling::Diagnostic Diag = Error;
599 TUD.Diagnostics.insert(TUD.Diagnostics.end(), Diag);
602 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.
Some operations such as code completion produce a set of candidates.
bool canEnableAnalyzerAlphaCheckers() const
If the experimental alpha checkers from the static analyzer can be enabled.
ClangTidyOptions::OptionMap getCheckOptions()
Get the union of options from all checks.
bool isCheckEnabled(StringRef CheckName) const
Returns true if the check is enabled for the CurrentFile.
bool getEnableProfiling() const
static cl::opt< std::string > StoreCheckProfile("store-check-profile", cl::desc(R"(
By default reports are printed in tabulated
format to stderr. When this option is passed,
these per-TU profiles are instead stored as JSON.
)"), cl::value_desc("prefix"), cl::cat(ClangTidyCategory))
constexpr llvm::StringLiteral Message
static llvm::StringRef toString(SpecialMemberFunctionsCheck::SpecialMemberFunctionKind K)
Contains options for clang-tidy.
A collection of ClangTidyCheckFactory instances.
OptionMap CheckOptions
Key-value mapping used to store check-specific options.
std::vector< ClangTidyError > runClangTidy(clang::tidy::ClangTidyContext &Context, const CompilationDatabase &Compilations, ArrayRef< std::string > InputFiles, llvm::IntrusiveRefCntPtr< llvm::vfs::OverlayFileSystem > BaseFS, bool EnableCheckProfile, llvm::StringRef StoreCheckProfile)
void handleErrors(llvm::ArrayRef< ClangTidyError > Errors, ClangTidyContext &Context, bool Fix, unsigned &WarningsAsErrorsCount, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS)
Displays the found Errors to the users.
llvm::Optional< ArgList > ExtraArgsBefore
Add extra compilation arguments to the start of the list.
void setCurrentFile(StringRef File)
Should be called when starting to process new translation unit.
std::string Filename
Filename as a string.
static cl::opt< bool > AllowEnablingAnalyzerAlphaCheckers("allow-enabling-analyzer-alpha-checkers", cl::init(false), cl::Hidden, cl::cat(ClangTidyCategory))
This option allows enabling the experimental alpha checkers from the static analyzer.
std::vector< ClangTidyError > take()
llvm::unique_function< void()> Action
llvm::Optional< ClangTidyProfiling::StorageParams > getProfileStorageParams() const
const LangOptions & getLangOpts() const
Gets the language options from the AST context.
ClangTidyOptions getOptionsForFile(StringRef File) const
Returns options for File.
const ClangTidyOptions & getOptions() const
Returns options for CurrentFile.
void setASTContext(ASTContext *Context)
Sets ASTContext for the current translation unit.
static cl::opt< std::string > WarningsAsErrors("warnings-as-errors", cl::desc(R"(
Upgrades warnings to errors. Same format as
'-checks'.
This option's value is appended to the value of
the 'WarningsAsErrors' option in .clang-tidy
file, if any.
)"), cl::init(""), cl::cat(ClangTidyCategory))
A diagnostic consumer that turns each Diagnostic into a SourceManager-independent ClangTidyError...
static constexpr llvm::StringLiteral Name
std::map< std::string, std::string > OptionMap
void setProfileStoragePrefix(StringRef ProfilePrefix)
Control storage of profile date.
static cl::opt< bool > EnableCheckProfile("enable-check-profile", cl::desc(R"(
Enable per-check timing profiles, and print a
report to stderr.
)"), cl::init(false), cl::cat(ClangTidyCategory))
void setSourceManager(SourceManager *SourceMgr)
Sets the SourceManager of the used DiagnosticsEngine.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
void setDiagnosticsEngine(DiagnosticsEngine *DiagEngine)
Sets the DiagnosticsEngine that diag() will emit diagnostics to.
void exportReplacements(const llvm::StringRef MainFilePath, const std::vector< ClangTidyError > &Errors, raw_ostream &OS)
CharSourceRange Range
SourceRange for the file name.
A detected error complete with information to display diagnostic and automatic fix.
static cl::opt< std::string > Checks("checks", cl::desc(R"(
Comma-separated list of globs with optional '-'
prefix. Globs are processed in order of
appearance in the list. Globs without '-'
prefix add checks with matching names to the
set, globs with the '-' prefix remove checks
with matching names from the set of enabled
checks. This option's value is appended to the
value of the 'Checks' option in .clang-tidy
file, if any.
)"), cl::init(""), cl::cat(ClangTidyCategory))
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
llvm::Registry< ClangTidyModule > ClangTidyModuleRegistry
std::unique_ptr< clang::ASTConsumer > CreateASTConsumer(clang::CompilerInstance &Compiler, StringRef File)
Returns an ASTConsumer that runs the specified clang-tidy checks.
IgnoreDiagnostics DiagConsumer
static cl::opt< bool > Fix("fix", cl::desc(R"(
Apply suggested fixes. Without -fix-errors
clang-tidy will bail out if any compilation
errors were found.
)"), cl::init(false), cl::cat(ClangTidyCategory))
void setCurrentBuildDirectory(StringRef BuildDirectory)
Should be called when starting to process new translation unit.
void setEnableProfiling(bool Profile)
Control profile collection in clang-tidy.
llvm::StringMap< std::string > Files