23#include "clang-tidy-config.h"
24#include "clang/AST/ASTConsumer.h"
25#include "clang/ASTMatchers/ASTMatchFinder.h"
26#include "clang/Basic/DiagnosticFrontend.h"
27#include "clang/Basic/Sarif.h"
28#include "clang/Format/Format.h"
29#include "clang/Frontend/ASTConsumers.h"
30#include "clang/Frontend/CompilerInstance.h"
31#include "clang/Frontend/MultiplexConsumer.h"
32#include "clang/Frontend/SARIFDiagnostic.h"
33#include "clang/Frontend/TextDiagnosticPrinter.h"
34#include "clang/Lex/Preprocessor.h"
35#include "clang/Lex/PreprocessorOptions.h"
36#include "clang/Rewrite/Frontend/FixItRewriter.h"
37#include "clang/Tooling/Core/Diagnostic.h"
38#include "clang/Tooling/DiagnosticsYaml.h"
39#include "clang/Tooling/Refactoring.h"
40#include "clang/Tooling/Tooling.h"
41#include "llvm/Support/Error.h"
42#include "llvm/Support/FileSystem.h"
43#include "llvm/Support/FormatVariadic.h"
44#include "llvm/Support/Process.h"
45#include "llvm/Support/raw_ostream.h"
49#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
50#include "clang/Analysis/PathDiagnostic.h"
51#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
52#include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
56using namespace clang::driver;
64#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
67 ClangTidyCheckFactories &Factories) =
nullptr;
72#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
73#define ANALYZER_CHECK_NAME_PREFIX "clang-analyzer-"
74static constexpr StringRef AnalyzerCheckNamePrefix = ANALYZER_CHECK_NAME_PREFIX;
76class AnalyzerDiagnosticConsumer :
public ento::PathDiagnosticConsumer {
78 AnalyzerDiagnosticConsumer(ClangTidyContext &Context) : Context(Context) {}
80 void FlushDiagnosticsImpl(std::vector<const ento::PathDiagnostic *> &Diags,
81 FilesMade *FilesMade)
override {
82 for (
const ento::PathDiagnostic *PD : Diags) {
83 SmallString<64> CheckName(AnalyzerCheckNamePrefix);
84 CheckName += PD->getCheckerName();
85 Context.diag(CheckName, PD->getLocation().asLocation(),
86 PD->getShortDescription())
87 << PD->path.back()->getRanges();
89 for (
const auto &DiagPiece :
90 PD->path.flatten(
true)) {
91 Context.diag(CheckName, DiagPiece->getLocation().asLocation(),
92 DiagPiece->getString(), DiagnosticIDs::Note)
93 << DiagPiece->getRanges();
98 StringRef getName()
const override {
return "ClangTidyDiags"; }
99 bool supportsLogicalOpControlFlow()
const override {
return true; }
100 bool supportsCrossFileDiagnostics()
const override {
return true; }
103 ClangTidyContext &Context;
109 ErrorReporter(ClangTidyContext &Context,
FixBehaviour ApplyFixes,
110 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
111 StringRef SarifExportPath)
112 : Files(FileSystemOptions(), std::move(BaseFS)),
114 SarifExportPath ==
"-"
115 ? static_cast<DiagnosticConsumer *>(new IgnoringDiagConsumer())
116 : new TextDiagnosticPrinter(llvm::outs(), DiagOpts)),
117 Diags(DiagnosticIDs::create(), DiagOpts, DiagPrinter),
118 SourceMgr(Diags, Files), Context(Context), ApplyFixes(ApplyFixes),
119 SarifExportPath(SarifExportPath) {
120 if (!SarifExportPath.empty()) {
121 SarifWriter.emplace(SourceMgr);
122 SarifWriter->createRun(
"clang-tidy",
"clang-tidy", CLANG_VERSION_STRING,
123 "https://clang.llvm.org/extra/clang-tidy/");
126 DiagOpts.setShowColors(Context.getOptions().UseColor.value_or(
127 llvm::sys::Process::StandardOutHasColors())
129 : ShowColorsKind::Off);
130 DiagPrinter->BeginSourceFile(LangOpts);
131 if (DiagOpts.showColors(llvm::sys::Process::StandardOutHasColors()) &&
132 !llvm::sys::Process::StandardOutIsDisplayed())
133 llvm::sys::Process::UseANSIEscapeCodes(
true);
136 SourceManager &getSourceManager() {
return SourceMgr; }
138 void reportDiagnostic(
const ClangTidyError &Error) {
139 const tooling::DiagnosticMessage &Message =
Error.Message;
140 const SourceLocation Loc =
141 getLocation(Message.FilePath, Message.FileOffset);
144 SmallVector<std::pair<SourceLocation, bool>, 4> FixLocations;
146 auto Level =
static_cast<DiagnosticsEngine::Level
>(
Error.DiagLevel);
147 std::string Name =
Error.DiagnosticName;
148 if (!
Error.EnabledDiagnosticAliases.empty())
149 Name +=
"," + llvm::join(
Error.EnabledDiagnosticAliases,
",");
150 if (
Error.IsWarningAsError) {
151 Name +=
",-warnings-as-errors";
152 Level = DiagnosticsEngine::Error;
156 Diags.Report(Loc, Diags.getCustomDiagID(Level,
"%0 [%1]"))
157 << Message.Message << Name;
158 for (
const FileByteRange &FBR :
Error.Message.Ranges)
159 Diag << getRange(FBR);
161 const llvm::StringMap<Replacements> *ChosenFix =
nullptr;
164 for (
const auto &FileAndReplacements : *ChosenFix) {
165 for (
const auto &Repl : FileAndReplacements.second) {
167 bool CanBeApplied =
false;
168 if (!Repl.isApplicable())
170 SourceLocation FixLoc;
171 SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
172 Files.makeAbsolutePath(FixAbsoluteFilePath);
173 tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
174 Repl.getLength(), Repl.getReplacementText());
175 auto &Entry = FileReplacements[R.getFilePath()];
176 Replacements &Replacements = Entry.Replaces;
177 llvm::Error Err = Replacements.add(R);
180 llvm::errs() <<
"Trying to resolve conflict: "
181 << llvm::toString(std::move(Err)) <<
"\n";
182 const unsigned NewOffset =
183 Replacements.getShiftedCodePosition(R.getOffset());
184 const unsigned NewLength = Replacements.getShiftedCodePosition(
185 R.getOffset() + R.getLength()) -
187 if (NewLength == R.getLength()) {
188 R = Replacement(R.getFilePath(), NewOffset, NewLength,
189 R.getReplacementText());
190 Replacements = Replacements.merge(tooling::Replacements(R));
195 <<
"Can't resolve conflict, skipping the replacement.\n";
201 FixLoc = getLocation(FixAbsoluteFilePath, Repl.getOffset());
202 FixLocations.emplace_back(FixLoc, CanBeApplied);
203 Entry.BuildDir =
Error.BuildDirectory;
207 reportFix(Diag,
Error.Message.Fix);
209 for (
const auto &
Fix : FixLocations) {
210 Diags.Report(
Fix.first,
Fix.second ? diag::note_fixit_applied
211 : diag::note_fixit_failed);
213 for (
const auto &Note :
Error.Notes)
217 exportSarifResult(Error, Loc);
220 CharSourceRange getNoteRange(
const tooling::DiagnosticMessage &Note) {
221 const SourceLocation Loc = getLocation(Note.FilePath, Note.FileOffset);
222 return Loc.isValid() ? getOffsetRange(SourceMgr, Loc) : CharSourceRange();
225 SmallVector<ThreadFlow> createNotesThreadFlows(
const ClangTidyError &Error) {
226 SmallVector<ThreadFlow> Flows;
227 Flows.reserve(
Error.Notes.size());
228 for (
const tooling::DiagnosticMessage &Note :
Error.Notes) {
229 Flows.push_back(ThreadFlow::create()
230 .setRange(getNoteRange(Note))
231 .setMessage(Note.Message));
236 void exportSarifResult(
const ClangTidyError &Error,
237 const SourceLocation Loc) {
238 assert(SarifWriter &&
"SARIF writer must be initialized");
240 const auto [RuleIndexEntryIt, Inserted] =
241 SarifRuleIdx.try_emplace(
Error.DiagnosticName, 0);
242 size_t &RuleIndex = RuleIndexEntryIt->second;
244 const DiagnosticsEngine::Level EffectiveLevel =
245 Error.IsWarningAsError
246 ? DiagnosticsEngine::Error
247 :
static_cast<DiagnosticsEngine::Level
>(
Error.DiagLevel);
250 const StringRef Name =
Error.DiagnosticName;
251 SarifRule Rule = SarifRule::create().setRuleId(Name).setName(Name);
252 Rule = addDiagnosticLevelToRule(Rule, EffectiveLevel);
253 RuleIndex = SarifWriter->createRule(Rule);
257 SarifResult::create(RuleIndex)
258 .setDiagnosticMessage(
Error.Message.Message)
259 .setDiagnosticLevel(getSarifResultLevel(EffectiveLevel));
264 (Loc.isValid() ? Result.addLocations(getOffsetRange(SourceMgr, Loc))
265 : Result.addLocations(getResultRanges(Error)));
270 if (!
Error.EnabledDiagnosticAliases.empty())
271 Result = Result.addProperty(
272 "enabledAliases", llvm::join(
Error.EnabledDiagnosticAliases,
","));
278 if (StringRef(
Error.DiagnosticName).starts_with(
"clang-analyzer-"))
279 Result = Result.setThreadFlows(createNotesThreadFlows(Error));
281 for (
const tooling::DiagnosticMessage &Note :
Error.Notes)
282 Result = Result.addRelatedLocations(getNoteRange(Note), Note.Message);
283 SarifWriter->appendResult(Result);
287 CharSourceRange getOffsetRange(SourceManager &SM, SourceLocation Loc) {
288 const auto [FileId, Offset] = SM.getDecomposedLoc(Loc);
289 return CharSourceRange::getCharRange(
290 Loc, Loc.getLocWithOffset(Offset < SM.getFileIDSize(FileId) ? 1 : 0));
293 SmallVector<CharSourceRange> getResultRanges(
const ClangTidyError &Error) {
294 SmallVector<CharSourceRange> Ranges;
295 Ranges.reserve(
Error.Message.Ranges.size());
296 for (
const FileByteRange &FBR :
Error.Message.Ranges)
297 Ranges.push_back(getRange(FBR));
302 if (TotalFixes > 0) {
303 auto &VFS = Files.getVirtualFileSystem();
304 auto OriginalCWD = VFS.getCurrentWorkingDirectory();
305 bool AnyNotWritten =
false;
307 for (
const auto &FileAndReplacements : FileReplacements) {
308 Rewriter Rewrite(SourceMgr, LangOpts);
309 const StringRef
File = FileAndReplacements.first();
310 VFS.setCurrentWorkingDirectory(FileAndReplacements.second.BuildDir);
311 llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
312 SourceMgr.getFileManager().getBufferForFile(File);
314 llvm::errs() <<
"Can't get buffer for file " <<
File <<
": "
315 << Buffer.getError().message() <<
"\n";
319 const StringRef Code = Buffer.get()->getBuffer();
320 auto Style = format::getStyle(
321 Context.getOptionsForFile(File).FormatStyle.value_or(
"none"), File,
324 llvm::errs() << llvm::toString(Style.takeError()) <<
"\n";
327 llvm::Expected<tooling::Replacements> Replacements =
328 format::cleanupAroundReplacements(
329 Code, FileAndReplacements.second.Replaces, *Style);
331 llvm::errs() << llvm::toString(Replacements.takeError()) <<
"\n";
334 if (llvm::Expected<tooling::Replacements> FormattedReplacements =
335 format::formatReplacements(Code, *Replacements, *Style)) {
336 Replacements = std::move(FormattedReplacements);
338 llvm_unreachable(
"!Replacements");
340 llvm::errs() << llvm::toString(FormattedReplacements.takeError())
341 <<
". Skipping formatting.\n";
343 if (!tooling::applyAllReplacements(Replacements.get(), Rewrite))
344 llvm::errs() <<
"Can't apply replacements for file " <<
File <<
"\n";
345 AnyNotWritten |= Rewrite.overwriteChangedFiles();
349 llvm::errs() <<
"clang-tidy failed to apply suggested fixes.\n";
351 llvm::errs() <<
"clang-tidy applied " << AppliedFixes <<
" of "
352 << TotalFixes <<
" suggested fixes.\n";
356 VFS.setCurrentWorkingDirectory(*OriginalCWD);
362 unsigned getWarningsAsErrorsCount()
const {
return WarningsAsErrors; }
365 SourceLocation getLocation(StringRef FilePath,
unsigned Offset) {
366 if (FilePath.empty())
369 auto File = SourceMgr.getFileManager().getOptionalFileRef(FilePath);
373 const FileID ID = SourceMgr.getOrCreateFileID(*File, SrcMgr::C_User);
374 return SourceMgr.getLocForStartOfFile(ID).getLocWithOffset(Offset);
377 void finalizeSarif() {
378 assert(SarifWriter &&
"SARIF writer must be initialized");
379 const llvm::json::Value Document = SarifWriter->createDocument();
380 if (SarifExportPath ==
"-") {
381 llvm::outs() << llvm::formatv(
"{0:2}", Document);
386 llvm::raw_fd_ostream SarifOS(SarifExportPath, EC, llvm::sys::fs::OF_Text);
388 llvm::errs() <<
"Error opening SARIF export file '" << SarifExportPath
389 <<
"': " << EC.message() <<
"\n";
392 SarifOS << llvm::formatv(
"{0:2}", Document);
395 void reportFix(
const DiagnosticBuilder &Diag,
396 const llvm::StringMap<Replacements> &
Fix) {
397 for (
const auto &FileAndReplacements :
Fix) {
398 for (
const auto &Repl : FileAndReplacements.second) {
399 if (!Repl.isApplicable())
402 FBR.FilePath = Repl.getFilePath().str();
403 FBR.FileOffset = Repl.getOffset();
404 FBR.Length = Repl.getLength();
406 Diag << FixItHint::CreateReplacement(getRange(FBR),
407 Repl.getReplacementText());
412 void reportNote(
const tooling::DiagnosticMessage &Message) {
413 const SourceLocation Loc =
414 getLocation(Message.FilePath, Message.FileOffset);
416 Diags.Report(Loc, Diags.getCustomDiagID(DiagnosticsEngine::Note,
"%0"))
418 for (
const FileByteRange &FBR : Message.Ranges)
419 Diag << getRange(FBR);
420 reportFix(Diag, Message.Fix);
423 CharSourceRange getRange(
const FileByteRange &Range) {
424 SmallString<128> AbsoluteFilePath{Range.FilePath};
425 Files.makeAbsolutePath(AbsoluteFilePath);
426 const SourceLocation BeginLoc =
427 getLocation(AbsoluteFilePath, Range.FileOffset);
428 const SourceLocation EndLoc = BeginLoc.getLocWithOffset(Range.Length);
432 return CharSourceRange::getCharRange(BeginLoc, EndLoc);
435 struct ReplacementsWithBuildDir {
437 Replacements Replaces;
441 LangOptions LangOpts;
442 DiagnosticOptions DiagOpts;
443 DiagnosticConsumer *DiagPrinter;
444 DiagnosticsEngine Diags;
445 SourceManager SourceMgr;
446 llvm::StringMap<ReplacementsWithBuildDir> FileReplacements;
447 ClangTidyContext &Context;
449 unsigned TotalFixes = 0U;
450 unsigned AppliedFixes = 0U;
451 unsigned WarningsAsErrors = 0U;
452 std::string SarifExportPath;
453 std::optional<SarifDocumentWriter> SarifWriter;
456 llvm::StringMap<size_t> SarifRuleIdx;
459class ClangTidyASTConsumer :
public MultiplexConsumer {
461 ClangTidyASTConsumer(std::vector<std::unique_ptr<ASTConsumer>> Consumers,
462 std::unique_ptr<ClangTidyProfiling> Profiling,
463 std::unique_ptr<ast_matchers::MatchFinder> Finder,
464 std::vector<std::unique_ptr<ClangTidyCheck>> Checks)
465 : MultiplexConsumer(std::move(Consumers)),
466 Profiling(std::move(Profiling)), Finder(std::move(Finder)),
467 Checks(std::move(Checks)) {}
472 std::unique_ptr<ClangTidyProfiling> Profiling;
473 std::unique_ptr<ast_matchers::MatchFinder> Finder;
474 std::vector<std::unique_ptr<ClangTidyCheck>> Checks;
475 void anchor()
override {}
482 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS)
483 : Context(Context), OverlayFS(std::
move(OverlayFS)),
485#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
489 for (
const ClangTidyModuleRegistry::entry E :
490 ClangTidyModuleRegistry::entries()) {
491 std::unique_ptr<ClangTidyModule> Module = E.instantiate();
492 Module->addCheckFactories(*CheckFactories);
496#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
498 AnalyzerOptions &AnalyzerOptions) {
500 StringRef OptName(Opt.getKey());
501 if (!OptName.consume_front(AnalyzerCheckNamePrefix))
504 AnalyzerOptions.Config[OptName] = Opt.getValue().Value;
508using CheckersList = std::vector<std::pair<std::string, bool>>;
510static CheckersList getAnalyzerCheckersAndPackages(ClangTidyContext &Context,
511 bool IncludeExperimental) {
514 const auto &RegisteredCheckers =
515 AnalyzerOptions::getRegisteredCheckers(IncludeExperimental);
516 const bool AnalyzerChecksEnabled =
517 llvm::any_of(RegisteredCheckers, [&](StringRef CheckName) ->
bool {
518 return Context.isCheckEnabled(
519 (AnalyzerCheckNamePrefix + CheckName).str());
522 if (!AnalyzerChecksEnabled)
530 for (
const StringRef CheckName : RegisteredCheckers) {
531 const std::string ClangTidyCheckName(
532 (AnalyzerCheckNamePrefix + CheckName).str());
534 if (CheckName.starts_with(
"core") ||
535 Context.isCheckEnabled(ClangTidyCheckName)) {
536 List.emplace_back(std::string(CheckName),
true);
543std::unique_ptr<ASTConsumer>
548 SourceManager *SM = &Compiler.getSourceManager();
549 Context.setSourceManager(SM);
550 Context.setCurrentFile(File);
551 Context.setASTContext(&Compiler.getASTContext());
553 auto WorkingDir = Compiler.getSourceManager()
555 .getVirtualFileSystem()
556 .getCurrentWorkingDirectory();
558 Context.setCurrentBuildDirectory(WorkingDir.get());
559#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
563 std::vector<std::unique_ptr<ClangTidyCheck>>
Checks =
564 CheckFactories->createChecksForLanguage(&Context);
566 ast_matchers::MatchFinder::MatchFinderOptions FinderOptions;
569 FinderOptions.SkipDeclsInModules =
true;
571 std::unique_ptr<ClangTidyProfiling> Profiling;
572 if (Context.getEnableProfiling()) {
574 std::make_unique<ClangTidyProfiling>(Context.getProfileStorageParams());
575 FinderOptions.CheckProfiling.emplace(Profiling->Records);
579 if (!Context.getOptions().SystemHeaders.value_or(
false))
580 FinderOptions.IgnoreSystemHeaders =
true;
583 std::make_unique<ast_matchers::MatchFinder>(std::move(FinderOptions));
585 Preprocessor *PP = &Compiler.getPreprocessor();
586 Preprocessor *ModuleExpanderPP = PP;
588 if (Context.canEnableModuleHeadersParsing() &&
589 Context.getLangOpts().Modules && OverlayFS !=
nullptr) {
590 auto ModuleExpander = std::make_unique<ExpandModularHeadersPPCallbacks>(
591 &Compiler, *OverlayFS);
592 ModuleExpanderPP = ModuleExpander->getPreprocessor();
593 PP->addPPCallbacks(std::move(ModuleExpander));
596 for (
auto &Check :
Checks) {
597 Check->registerMatchers(&*Finder);
598 Check->registerPPCallbacks(*SM, PP, ModuleExpanderPP);
601 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
603 Consumers.push_back(Finder->newASTConsumer());
605#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
606 AnalyzerOptions &AnalyzerOptions = Compiler.getAnalyzerOpts();
607 AnalyzerOptions.CheckersAndPackages = getAnalyzerCheckersAndPackages(
608 Context, Context.canEnableAnalyzerAlphaCheckers());
609 if (!AnalyzerOptions.CheckersAndPackages.empty()) {
610 setStaticAnalyzerCheckerOpts(Context.getOptions(), AnalyzerOptions);
611 AnalyzerOptions.AnalysisDiagOpt = PD_NONE;
612 std::unique_ptr<ento::AnalysisASTConsumer> AnalysisConsumer =
613 ento::CreateAnalysisConsumer(Compiler);
614 AnalysisConsumer->AddDiagnosticConsumer(
615 std::make_unique<AnalyzerDiagnosticConsumer>(Context));
616 Consumers.push_back(std::move(AnalysisConsumer));
619 return std::make_unique<ClangTidyASTConsumer>(
620 std::move(Consumers), std::move(Profiling), std::move(Finder),
625 std::vector<std::string> CheckNames;
626 for (
const auto &CheckFactory : *CheckFactories)
627 if (Context.isCheckEnabled(CheckFactory.getKey()))
628 CheckNames.emplace_back(CheckFactory.getKey());
630#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
631 for (
const auto &AnalyzerCheck : getAnalyzerCheckersAndPackages(
632 Context, Context.canEnableAnalyzerAlphaCheckers()))
633 CheckNames.emplace_back(
634 (AnalyzerCheckNamePrefix + AnalyzerCheck.first).str());
637 llvm::sort(CheckNames);
643 const std::vector<std::unique_ptr<ClangTidyCheck>>
Checks =
644 CheckFactories->createChecks(&Context);
645 for (
const auto &Check :
Checks)
646 Check->storeOptions(Options);
662 const std::vector<std::string> &EnabledChecks) {
664 for (
const auto &[OptionName, Value] : Options.
CheckOptions) {
665 const size_t CheckNameEndPos = OptionName.find(
'.');
666 if (CheckNameEndPos == StringRef::npos)
668 const StringRef CheckName = OptionName.substr(0, CheckNameEndPos);
669 if (llvm::binary_search(EnabledChecks, CheckName))
670 FilteredOptions[OptionName] = Value;
684 auto DiagOpts = std::make_unique<DiagnosticOptions>();
685 DiagnosticsEngine DE(llvm::makeIntrusiveRefCnt<DiagnosticIDs>(), *DiagOpts,
686 &DiagConsumer,
false);
692std::vector<ClangTidyError>
694 ArrayRef<std::string> InputFiles,
695 llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
698 ClangTool Tool(Compilations, InputFiles,
699 std::make_shared<PCHContainerOperations>(), BaseFS);
702 const ArgumentsAdjuster PerFileExtraArgumentsInserter =
703 [&Context](
const CommandLineArguments &Args, StringRef Filename) {
705 CommandLineArguments AdjustedArgs = Args;
707 auto I = AdjustedArgs.begin();
708 if (I != AdjustedArgs.end() && !StringRef(*I).starts_with(
'-'))
714 AdjustedArgs.insert(AdjustedArgs.end(), Opts.
ExtraArgs->begin(),
720 const ArgumentsAdjuster PerFileArgumentRemover =
721 [&Context](
const CommandLineArguments &Args, StringRef Filename) {
723 CommandLineArguments AdjustedArgs = Args;
726 for (
const StringRef ArgToRemove : *Opts.
RemovedArgs) {
727 AdjustedArgs.erase(std::remove(AdjustedArgs.begin(),
728 AdjustedArgs.end(), ArgToRemove),
736 Tool.appendArgumentsAdjuster(PerFileArgumentRemover);
737 Tool.appendArgumentsAdjuster(PerFileExtraArgumentsInserter);
738 Tool.appendArgumentsAdjuster(getStripPluginsAdjuster());
744 auto DiagOpts = std::make_unique<DiagnosticOptions>();
745 DiagnosticsEngine DE(DiagnosticIDs::create(), *DiagOpts, &DiagConsumer,
748 Tool.setDiagnosticConsumer(&DiagConsumer);
753 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
755 : ConsumerFactory(Context, std::move(BaseFS)),
Quiet(
Quiet) {}
756 std::unique_ptr<FrontendAction> create()
override {
757 return std::make_unique<Action>(&ConsumerFactory);
760 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
762 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
765 Invocation->getPreprocessorOpts().SetUpStaticAnalyzer =
true;
767 Invocation->getDiagnosticOpts().ShowCarets =
false;
768 return FrontendActionFactory::runInvocation(
769 Invocation, Files, PCHContainerOps, DiagConsumer);
773 class Action :
public ASTFrontendAction {
780 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
781 StringRef File)
override {
790 ActionFactory Factory(Context, std::move(BaseFS),
Quiet);
792 return DiagConsumer.
take();
797 unsigned &WarningsAsErrorsCount,
798 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS,
799 StringRef SarifExportPath) {
800 ErrorReporter Reporter(Context,
Fix, std::move(BaseFS), SarifExportPath);
801 llvm::vfs::FileSystem &FileSystem =
802 Reporter.getSourceManager().getFileManager().getVirtualFileSystem();
803 auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();
804 if (!InitialWorkingDir)
805 llvm::report_fatal_error(
"Cannot get current working path.");
808 if (!Error.BuildDirectory.empty()) {
813 FileSystem.setCurrentWorkingDirectory(Error.BuildDirectory);
815 Reporter.reportDiagnostic(Error);
817 FileSystem.setCurrentWorkingDirectory(InitialWorkingDir.get());
820 WarningsAsErrorsCount += Reporter.getWarningsAsErrorsCount();
824 const std::vector<ClangTidyError> &Errors,
826 TranslationUnitDiagnostics TUD;
827 TUD.MainSourceFile = std::string(MainFilePath);
828 for (
const auto &Error : Errors) {
829 tooling::Diagnostic Diag = Error;
830 if (Error.IsWarningAsError)
831 Diag.DiagLevel = tooling::Diagnostic::Error;
832 TUD.Diagnostics.insert(TUD.Diagnostics.end(), Diag);
835 yaml::Output YAML(OS);
848#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
852 for (
const ClangTidyModuleRegistry::entry &Module :
853 ClangTidyModuleRegistry::entries()) {
854 Module.instantiate()->addCheckFactories(Factories);
857 for (
const auto &Factory : Factories)
858 Result.
Checks.insert(Factory.getKey());
860#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
861 SmallString<64> Buffer(AnalyzerCheckNamePrefix);
862 const size_t DefSize = Buffer.size();
863 for (
const auto &AnalyzerCheck : AnalyzerOptions::getRegisteredCheckers(
865 Buffer.truncate(DefSize);
866 Buffer.append(AnalyzerCheck);
867 Result.
Checks.insert(Buffer);
870 static constexpr StringRef OptionNames[] = {
871#define GET_CHECKER_OPTIONS
872#define CHECKER_OPTION(TYPE, CHECKER, OPTION_NAME, DESCRIPTION, DEFAULT, \
874 ANALYZER_CHECK_NAME_PREFIX CHECKER ":" OPTION_NAME,
876#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
878#undef GET_CHECKER_OPTIONS
881 Result.
Options.insert_range(OptionNames);
885 for (
const auto &Factory : Factories)
886 Factory.getValue()(Factory.getKey(), &Context);
static cl::opt< bool > EnableCheckProfile("enable-check-profile", desc(R"(
Enable per-check timing profiles, and print a
report to stderr.
)"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< bool > Fix("fix", 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))
static cl::opt< bool > ExperimentalCustomChecks("experimental-custom-checks", desc(R"(
Enable experimental clang-query based
custom checks.
see https://clang.llvm.org/extra/clang-tidy/QueryBasedCustomChecks.html.
)"), cl::init(false), cl::cat(ClangTidyCategory))
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.
static cl::opt< std::string > Checks("checks", 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))
static cl::opt< bool > Quiet("quiet", desc(R"(
Run clang-tidy in quiet mode. This suppresses
printing statistics about ignored warnings and
warnings treated as errors if the respective
options are specified.
)"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< std::string > StoreCheckProfile("store-check-profile", 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))
std::unique_ptr< ASTConsumer > createASTConsumer(CompilerInstance &Compiler, StringRef File)
Returns an ASTConsumer that runs the specified clang-tidy checks.
ClangTidyOptions::OptionMap getCheckOptions()
Get the union of options from all checks.
ClangTidyASTConsumerFactory(ClangTidyContext &Context, IntrusiveRefCntPtr< llvm::vfs::OverlayFileSystem > OverlayFS=nullptr)
std::vector< std::string > getCheckNames()
Get the list of enabled checks.
A collection of ClangTidyCheckFactory instances.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void setOptionsCollector(llvm::StringSet<> *Collector)
const ClangTidyOptions & getOptions() const
Returns options for CurrentFile.
void setProfileStoragePrefix(StringRef ProfilePrefix)
Control storage of profile date.
void setEnableProfiling(bool Profile)
Control profile collection in clang-tidy.
void setDiagnosticsEngine(std::unique_ptr< DiagnosticOptions > DiagOpts, DiagnosticsEngine *DiagEngine)
Sets the DiagnosticsEngine that diag() will emit diagnostics to.
ClangTidyOptions getOptionsForFile(StringRef File) const
Returns options for File.
A diagnostic consumer that turns each Diagnostic into a SourceManager-independent ClangTidyError.
std::vector< ClangTidyError > take()
void(* RegisterCustomChecks)(const ClangTidyOptions &O, ClangTidyCheckFactories &Factories)
const llvm::StringMap< tooling::Replacements > * getFixIt(const tooling::Diagnostic &Diagnostic, bool AnyFix)
Gets the Fix attached to Diagnostic.
ChecksAndOptions getAllChecksAndOptions(bool AllowEnablingAnalyzerAlphaCheckers, bool ExperimentalCustomChecks)
FixBehaviour
Controls what kind of fixes clang-tidy is allowed to apply.
@ FB_NoFix
Don't try to apply any fix.
@ FB_FixNotes
Apply fixes found in notes.
std::vector< std::string > getCheckNames(const ClangTidyOptions &Options, bool AllowEnablingAnalyzerAlphaCheckers, bool ExperimentalCustomChecks)
Fills the list of check names that are enabled when the provided filters are applied.
llvm::Registry< ClangTidyModule > ClangTidyModuleRegistry
void handleErrors(llvm::ArrayRef< ClangTidyError > Errors, ClangTidyContext &Context, FixBehaviour Fix, unsigned &WarningsAsErrorsCount, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS, StringRef SarifExportPath)
Displays the found Errors to the users.
ClangTidyOptions::OptionMap getCheckOptions(const ClangTidyOptions &Options, bool AllowEnablingAnalyzerAlphaCheckers, bool ExperimentalCustomChecks)
Returns the effective check-specific options.
void exportReplacements(const StringRef MainFilePath, const std::vector< ClangTidyError > &Errors, raw_ostream &OS)
Serializes replacements into YAML and writes them to the specified output stream.
void filterCheckOptions(ClangTidyOptions &Options, const std::vector< std::string > &EnabledChecks)
Filters CheckOptions in Options to only include options specified in the EnabledChecks which is a sor...
std::vector< ClangTidyError > runClangTidy(ClangTidyContext &Context, const CompilationDatabase &Compilations, ArrayRef< std::string > InputFiles, llvm::IntrusiveRefCntPtr< llvm::vfs::OverlayFileSystem > BaseFS, bool ApplyAnyFix, bool EnableCheckProfile, StringRef StoreCheckProfile, bool Quiet)
Some operations such as code completion produce a set of candidates.
llvm::StringMap< ClangTidyValue > OptionMap
A detected error complete with information to display diagnostic and automatic fix.
Contains options for clang-tidy.
OptionMap CheckOptions
Key-value mapping used to store check-specific options.
llvm::StringMap< ClangTidyValue > OptionMap
std::optional< std::string > Checks
Checks filter.
std::optional< ArgList > RemovedArgs
Remove command line arguments sent to the compiler matching this.
std::optional< ArgList > ExtraArgsBefore
Add extra compilation arguments to the start of the list.
std::optional< ArgList > ExtraArgs
Add extra compilation arguments to the end of the list.