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/Format/Format.h"
28#include "clang/Frontend/ASTConsumers.h"
29#include "clang/Frontend/CompilerInstance.h"
30#include "clang/Frontend/MultiplexConsumer.h"
31#include "clang/Frontend/TextDiagnosticPrinter.h"
32#include "clang/Lex/Preprocessor.h"
33#include "clang/Lex/PreprocessorOptions.h"
34#include "clang/Rewrite/Frontend/FixItRewriter.h"
35#include "clang/Tooling/Core/Diagnostic.h"
36#include "clang/Tooling/DiagnosticsYaml.h"
37#include "clang/Tooling/Refactoring.h"
38#include "clang/Tooling/Tooling.h"
39#include "llvm/Support/Process.h"
43#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
44#include "clang/Analysis/PathDiagnostic.h"
45#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
46#include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
50using namespace clang::driver;
58#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
61 ClangTidyCheckFactories &Factories) =
nullptr;
66#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
67#define ANALYZER_CHECK_NAME_PREFIX "clang-analyzer-"
68static constexpr StringRef AnalyzerCheckNamePrefix = ANALYZER_CHECK_NAME_PREFIX;
70class AnalyzerDiagnosticConsumer :
public ento::PathDiagnosticConsumer {
72 AnalyzerDiagnosticConsumer(ClangTidyContext &Context) : Context(Context) {}
74 void FlushDiagnosticsImpl(std::vector<const ento::PathDiagnostic *> &Diags,
75 FilesMade *FilesMade)
override {
76 for (
const ento::PathDiagnostic *PD : Diags) {
77 SmallString<64> CheckName(AnalyzerCheckNamePrefix);
78 CheckName += PD->getCheckerName();
79 Context.diag(CheckName, PD->getLocation().asLocation(),
80 PD->getShortDescription())
81 << PD->path.back()->getRanges();
83 for (
const auto &DiagPiece :
84 PD->path.flatten(
true)) {
85 Context.diag(CheckName, DiagPiece->getLocation().asLocation(),
86 DiagPiece->getString(), DiagnosticIDs::Note)
87 << DiagPiece->getRanges();
92 StringRef getName()
const override {
return "ClangTidyDiags"; }
93 bool supportsLogicalOpControlFlow()
const override {
return true; }
94 bool supportsCrossFileDiagnostics()
const override {
return true; }
97 ClangTidyContext &Context;
103 ErrorReporter(ClangTidyContext &Context,
FixBehaviour ApplyFixes,
104 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS)
105 : Files(FileSystemOptions(), std::move(BaseFS)),
106 DiagPrinter(new TextDiagnosticPrinter(llvm::outs(), DiagOpts)),
107 Diags(DiagnosticIDs::create(), DiagOpts, DiagPrinter),
108 SourceMgr(Diags, Files), Context(Context), ApplyFixes(ApplyFixes) {
109 DiagOpts.setShowColors(Context.getOptions().UseColor.value_or(
110 llvm::sys::Process::StandardOutHasColors())
112 : ShowColorsKind::Off);
113 DiagPrinter->BeginSourceFile(LangOpts);
114 if (DiagOpts.showColors(llvm::sys::Process::StandardOutHasColors()) &&
115 !llvm::sys::Process::StandardOutIsDisplayed())
116 llvm::sys::Process::UseANSIEscapeCodes(
true);
119 SourceManager &getSourceManager() {
return SourceMgr; }
121 void reportDiagnostic(
const ClangTidyError &Error) {
122 const tooling::DiagnosticMessage &Message =
Error.Message;
123 const SourceLocation Loc =
124 getLocation(Message.FilePath, Message.FileOffset);
127 SmallVector<std::pair<SourceLocation, bool>, 4> FixLocations;
129 auto Level =
static_cast<DiagnosticsEngine::Level
>(
Error.DiagLevel);
130 std::string Name =
Error.DiagnosticName;
131 if (!
Error.EnabledDiagnosticAliases.empty())
132 Name +=
"," + llvm::join(
Error.EnabledDiagnosticAliases,
",");
133 if (
Error.IsWarningAsError) {
134 Name +=
",-warnings-as-errors";
135 Level = DiagnosticsEngine::Error;
139 Diags.Report(Loc, Diags.getCustomDiagID(Level,
"%0 [%1]"))
140 << Message.Message << Name;
141 for (
const FileByteRange &FBR :
Error.Message.Ranges)
142 Diag << getRange(FBR);
144 const llvm::StringMap<Replacements> *ChosenFix =
nullptr;
147 for (
const auto &FileAndReplacements : *ChosenFix) {
148 for (
const auto &Repl : FileAndReplacements.second) {
150 bool CanBeApplied =
false;
151 if (!Repl.isApplicable())
153 SourceLocation FixLoc;
154 SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
155 Files.makeAbsolutePath(FixAbsoluteFilePath);
156 tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
157 Repl.getLength(), Repl.getReplacementText());
158 auto &Entry = FileReplacements[R.getFilePath()];
159 Replacements &Replacements = Entry.Replaces;
160 llvm::Error Err = Replacements.add(R);
163 llvm::errs() <<
"Trying to resolve conflict: "
164 << llvm::toString(std::move(Err)) <<
"\n";
165 const unsigned NewOffset =
166 Replacements.getShiftedCodePosition(R.getOffset());
167 const unsigned NewLength = Replacements.getShiftedCodePosition(
168 R.getOffset() + R.getLength()) -
170 if (NewLength == R.getLength()) {
171 R = Replacement(R.getFilePath(), NewOffset, NewLength,
172 R.getReplacementText());
173 Replacements = Replacements.merge(tooling::Replacements(R));
178 <<
"Can't resolve conflict, skipping the replacement.\n";
184 FixLoc = getLocation(FixAbsoluteFilePath, Repl.getOffset());
185 FixLocations.emplace_back(FixLoc, CanBeApplied);
186 Entry.BuildDir =
Error.BuildDirectory;
190 reportFix(Diag,
Error.Message.Fix);
192 for (
const auto &
Fix : FixLocations) {
193 Diags.Report(
Fix.first,
Fix.second ? diag::note_fixit_applied
194 : diag::note_fixit_failed);
196 for (
const auto &Note :
Error.Notes)
201 if (TotalFixes > 0) {
202 auto &VFS = Files.getVirtualFileSystem();
203 auto OriginalCWD = VFS.getCurrentWorkingDirectory();
204 bool AnyNotWritten =
false;
206 for (
const auto &FileAndReplacements : FileReplacements) {
207 Rewriter Rewrite(SourceMgr, LangOpts);
208 const StringRef
File = FileAndReplacements.first();
209 VFS.setCurrentWorkingDirectory(FileAndReplacements.second.BuildDir);
210 llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
211 SourceMgr.getFileManager().getBufferForFile(File);
213 llvm::errs() <<
"Can't get buffer for file " <<
File <<
": "
214 << Buffer.getError().message() <<
"\n";
218 const StringRef Code = Buffer.get()->getBuffer();
219 auto Style = format::getStyle(
220 Context.getOptionsForFile(File).FormatStyle.value_or(
"none"), File,
223 llvm::errs() << llvm::toString(Style.takeError()) <<
"\n";
226 llvm::Expected<tooling::Replacements> Replacements =
227 format::cleanupAroundReplacements(
228 Code, FileAndReplacements.second.Replaces, *Style);
230 llvm::errs() << llvm::toString(Replacements.takeError()) <<
"\n";
233 if (llvm::Expected<tooling::Replacements> FormattedReplacements =
234 format::formatReplacements(Code, *Replacements, *Style)) {
235 Replacements = std::move(FormattedReplacements);
237 llvm_unreachable(
"!Replacements");
239 llvm::errs() << llvm::toString(FormattedReplacements.takeError())
240 <<
". Skipping formatting.\n";
242 if (!tooling::applyAllReplacements(Replacements.get(), Rewrite))
243 llvm::errs() <<
"Can't apply replacements for file " <<
File <<
"\n";
244 AnyNotWritten |= Rewrite.overwriteChangedFiles();
248 llvm::errs() <<
"clang-tidy failed to apply suggested fixes.\n";
250 llvm::errs() <<
"clang-tidy applied " << AppliedFixes <<
" of "
251 << TotalFixes <<
" suggested fixes.\n";
255 VFS.setCurrentWorkingDirectory(*OriginalCWD);
259 unsigned getWarningsAsErrorsCount()
const {
return WarningsAsErrors; }
262 SourceLocation getLocation(StringRef FilePath,
unsigned Offset) {
263 if (FilePath.empty())
266 auto File = SourceMgr.getFileManager().getOptionalFileRef(FilePath);
270 const FileID ID = SourceMgr.getOrCreateFileID(*File, SrcMgr::C_User);
271 return SourceMgr.getLocForStartOfFile(ID).getLocWithOffset(Offset);
274 void reportFix(
const DiagnosticBuilder &Diag,
275 const llvm::StringMap<Replacements> &
Fix) {
276 for (
const auto &FileAndReplacements :
Fix) {
277 for (
const auto &Repl : FileAndReplacements.second) {
278 if (!Repl.isApplicable())
281 FBR.FilePath = Repl.getFilePath().str();
282 FBR.FileOffset = Repl.getOffset();
283 FBR.Length = Repl.getLength();
285 Diag << FixItHint::CreateReplacement(getRange(FBR),
286 Repl.getReplacementText());
291 void reportNote(
const tooling::DiagnosticMessage &Message) {
292 const SourceLocation Loc =
293 getLocation(Message.FilePath, Message.FileOffset);
295 Diags.Report(Loc, Diags.getCustomDiagID(DiagnosticsEngine::Note,
"%0"))
297 for (
const FileByteRange &FBR : Message.Ranges)
298 Diag << getRange(FBR);
299 reportFix(Diag, Message.Fix);
302 CharSourceRange getRange(
const FileByteRange &Range) {
303 SmallString<128> AbsoluteFilePath{Range.FilePath};
304 Files.makeAbsolutePath(AbsoluteFilePath);
305 const SourceLocation BeginLoc =
306 getLocation(AbsoluteFilePath, Range.FileOffset);
307 const SourceLocation EndLoc = BeginLoc.getLocWithOffset(Range.Length);
311 return CharSourceRange::getCharRange(BeginLoc, EndLoc);
314 struct ReplacementsWithBuildDir {
316 Replacements Replaces;
320 LangOptions LangOpts;
321 DiagnosticOptions DiagOpts;
322 DiagnosticConsumer *DiagPrinter;
323 DiagnosticsEngine Diags;
324 SourceManager SourceMgr;
325 llvm::StringMap<ReplacementsWithBuildDir> FileReplacements;
326 ClangTidyContext &Context;
328 unsigned TotalFixes = 0U;
329 unsigned AppliedFixes = 0U;
330 unsigned WarningsAsErrors = 0U;
333class ClangTidyASTConsumer :
public MultiplexConsumer {
335 ClangTidyASTConsumer(std::vector<std::unique_ptr<ASTConsumer>> Consumers,
336 std::unique_ptr<ClangTidyProfiling> Profiling,
337 std::unique_ptr<ast_matchers::MatchFinder> Finder,
338 std::vector<std::unique_ptr<ClangTidyCheck>> Checks)
339 : MultiplexConsumer(std::move(Consumers)),
340 Profiling(std::move(Profiling)), Finder(std::move(Finder)),
341 Checks(std::move(Checks)) {}
346 std::unique_ptr<ClangTidyProfiling> Profiling;
347 std::unique_ptr<ast_matchers::MatchFinder> Finder;
348 std::vector<std::unique_ptr<ClangTidyCheck>> Checks;
349 void anchor()
override {}
356 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS)
357 : Context(Context), OverlayFS(std::
move(OverlayFS)),
359#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
363 for (
const ClangTidyModuleRegistry::entry E :
364 ClangTidyModuleRegistry::entries()) {
365 std::unique_ptr<ClangTidyModule> Module = E.instantiate();
366 Module->addCheckFactories(*CheckFactories);
370#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
372 AnalyzerOptions &AnalyzerOptions) {
374 StringRef OptName(Opt.getKey());
375 if (!OptName.consume_front(AnalyzerCheckNamePrefix))
378 AnalyzerOptions.Config[OptName] = Opt.getValue().Value;
382using CheckersList = std::vector<std::pair<std::string, bool>>;
384static CheckersList getAnalyzerCheckersAndPackages(ClangTidyContext &Context,
385 bool IncludeExperimental) {
388 const auto &RegisteredCheckers =
389 AnalyzerOptions::getRegisteredCheckers(IncludeExperimental);
390 const bool AnalyzerChecksEnabled =
391 llvm::any_of(RegisteredCheckers, [&](StringRef CheckName) ->
bool {
392 return Context.isCheckEnabled(
393 (AnalyzerCheckNamePrefix + CheckName).str());
396 if (!AnalyzerChecksEnabled)
404 for (
const StringRef CheckName : RegisteredCheckers) {
405 const std::string ClangTidyCheckName(
406 (AnalyzerCheckNamePrefix + CheckName).str());
408 if (CheckName.starts_with(
"core") ||
409 Context.isCheckEnabled(ClangTidyCheckName)) {
410 List.emplace_back(std::string(CheckName),
true);
417std::unique_ptr<ASTConsumer>
422 SourceManager *SM = &Compiler.getSourceManager();
423 Context.setSourceManager(SM);
424 Context.setCurrentFile(File);
425 Context.setASTContext(&Compiler.getASTContext());
427 auto WorkingDir = Compiler.getSourceManager()
429 .getVirtualFileSystem()
430 .getCurrentWorkingDirectory();
432 Context.setCurrentBuildDirectory(WorkingDir.get());
433#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
437 std::vector<std::unique_ptr<ClangTidyCheck>>
Checks =
438 CheckFactories->createChecksForLanguage(&Context);
440 ast_matchers::MatchFinder::MatchFinderOptions FinderOptions;
443 FinderOptions.SkipDeclsInModules =
true;
445 std::unique_ptr<ClangTidyProfiling> Profiling;
446 if (Context.getEnableProfiling()) {
448 std::make_unique<ClangTidyProfiling>(Context.getProfileStorageParams());
449 FinderOptions.CheckProfiling.emplace(Profiling->Records);
453 if (!Context.getOptions().SystemHeaders.value_or(
false))
454 FinderOptions.IgnoreSystemHeaders =
true;
457 std::make_unique<ast_matchers::MatchFinder>(std::move(FinderOptions));
459 Preprocessor *PP = &Compiler.getPreprocessor();
460 Preprocessor *ModuleExpanderPP = PP;
462 if (Context.canEnableModuleHeadersParsing() &&
463 Context.getLangOpts().Modules && OverlayFS !=
nullptr) {
464 auto ModuleExpander = std::make_unique<ExpandModularHeadersPPCallbacks>(
465 &Compiler, *OverlayFS);
466 ModuleExpanderPP = ModuleExpander->getPreprocessor();
467 PP->addPPCallbacks(std::move(ModuleExpander));
470 for (
auto &Check :
Checks) {
471 Check->registerMatchers(&*Finder);
472 Check->registerPPCallbacks(*SM, PP, ModuleExpanderPP);
475 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
477 Consumers.push_back(Finder->newASTConsumer());
479#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
480 AnalyzerOptions &AnalyzerOptions = Compiler.getAnalyzerOpts();
481 AnalyzerOptions.CheckersAndPackages = getAnalyzerCheckersAndPackages(
482 Context, Context.canEnableAnalyzerAlphaCheckers());
483 if (!AnalyzerOptions.CheckersAndPackages.empty()) {
484 setStaticAnalyzerCheckerOpts(Context.getOptions(), AnalyzerOptions);
485 AnalyzerOptions.AnalysisDiagOpt = PD_NONE;
486 std::unique_ptr<ento::AnalysisASTConsumer> AnalysisConsumer =
487 ento::CreateAnalysisConsumer(Compiler);
488 AnalysisConsumer->AddDiagnosticConsumer(
489 std::make_unique<AnalyzerDiagnosticConsumer>(Context));
490 Consumers.push_back(std::move(AnalysisConsumer));
493 return std::make_unique<ClangTidyASTConsumer>(
494 std::move(Consumers), std::move(Profiling), std::move(Finder),
499 std::vector<std::string> CheckNames;
500 for (
const auto &CheckFactory : *CheckFactories)
501 if (Context.isCheckEnabled(CheckFactory.getKey()))
502 CheckNames.emplace_back(CheckFactory.getKey());
504#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
505 for (
const auto &AnalyzerCheck : getAnalyzerCheckersAndPackages(
506 Context, Context.canEnableAnalyzerAlphaCheckers()))
507 CheckNames.emplace_back(
508 (AnalyzerCheckNamePrefix + AnalyzerCheck.first).str());
511 llvm::sort(CheckNames);
517 const std::vector<std::unique_ptr<ClangTidyCheck>>
Checks =
518 CheckFactories->createChecks(&Context);
519 for (
const auto &Check :
Checks)
520 Check->storeOptions(Options);
536 const std::vector<std::string> &EnabledChecks) {
538 for (
const auto &[OptionName, Value] : Options.
CheckOptions) {
539 const size_t CheckNameEndPos = OptionName.find(
'.');
540 if (CheckNameEndPos == StringRef::npos)
542 const StringRef CheckName = OptionName.substr(0, CheckNameEndPos);
543 if (llvm::binary_search(EnabledChecks, CheckName))
544 FilteredOptions[OptionName] = Value;
558 auto DiagOpts = std::make_unique<DiagnosticOptions>();
559 DiagnosticsEngine DE(llvm::makeIntrusiveRefCnt<DiagnosticIDs>(), *DiagOpts,
560 &DiagConsumer,
false);
566std::vector<ClangTidyError>
568 ArrayRef<std::string> InputFiles,
569 llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
572 ClangTool Tool(Compilations, InputFiles,
573 std::make_shared<PCHContainerOperations>(), BaseFS);
576 const ArgumentsAdjuster PerFileExtraArgumentsInserter =
577 [&Context](
const CommandLineArguments &Args, StringRef Filename) {
579 CommandLineArguments AdjustedArgs = Args;
581 auto I = AdjustedArgs.begin();
582 if (I != AdjustedArgs.end() && !StringRef(*I).starts_with(
'-'))
588 AdjustedArgs.insert(AdjustedArgs.end(), Opts.
ExtraArgs->begin(),
594 const ArgumentsAdjuster PerFileArgumentRemover =
595 [&Context](
const CommandLineArguments &Args, StringRef Filename) {
597 CommandLineArguments AdjustedArgs = Args;
600 for (
const StringRef ArgToRemove : *Opts.
RemovedArgs) {
601 AdjustedArgs.erase(std::remove(AdjustedArgs.begin(),
602 AdjustedArgs.end(), ArgToRemove),
610 Tool.appendArgumentsAdjuster(PerFileArgumentRemover);
611 Tool.appendArgumentsAdjuster(PerFileExtraArgumentsInserter);
612 Tool.appendArgumentsAdjuster(getStripPluginsAdjuster());
617 auto DiagOpts = std::make_unique<DiagnosticOptions>();
618 DiagnosticsEngine DE(DiagnosticIDs::create(), *DiagOpts, &DiagConsumer,
621 Tool.setDiagnosticConsumer(&DiagConsumer);
626 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
628 : ConsumerFactory(Context, std::move(BaseFS)),
Quiet(
Quiet) {}
629 std::unique_ptr<FrontendAction> create()
override {
630 return std::make_unique<Action>(&ConsumerFactory);
633 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
635 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
638 Invocation->getPreprocessorOpts().SetUpStaticAnalyzer =
true;
640 Invocation->getDiagnosticOpts().ShowCarets =
false;
641 return FrontendActionFactory::runInvocation(
642 Invocation, Files, PCHContainerOps, DiagConsumer);
646 class Action :
public ASTFrontendAction {
653 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
654 StringRef File)
override {
663 ActionFactory Factory(Context, std::move(BaseFS),
Quiet);
665 return DiagConsumer.
take();
670 unsigned &WarningsAsErrorsCount,
671 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
672 ErrorReporter Reporter(Context,
Fix, std::move(BaseFS));
673 llvm::vfs::FileSystem &FileSystem =
674 Reporter.getSourceManager().getFileManager().getVirtualFileSystem();
675 auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();
676 if (!InitialWorkingDir)
677 llvm::report_fatal_error(
"Cannot get current working path.");
680 if (!Error.BuildDirectory.empty()) {
685 FileSystem.setCurrentWorkingDirectory(Error.BuildDirectory);
687 Reporter.reportDiagnostic(Error);
689 FileSystem.setCurrentWorkingDirectory(InitialWorkingDir.get());
692 WarningsAsErrorsCount += Reporter.getWarningsAsErrorsCount();
696 const std::vector<ClangTidyError> &Errors,
698 TranslationUnitDiagnostics TUD;
699 TUD.MainSourceFile = std::string(MainFilePath);
700 for (
const auto &Error : Errors) {
701 tooling::Diagnostic Diag = Error;
702 if (Error.IsWarningAsError)
703 Diag.DiagLevel = tooling::Diagnostic::Error;
704 TUD.Diagnostics.insert(TUD.Diagnostics.end(), Diag);
707 yaml::Output YAML(OS);
720#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
724 for (
const ClangTidyModuleRegistry::entry &Module :
725 ClangTidyModuleRegistry::entries()) {
726 Module.instantiate()->addCheckFactories(Factories);
729 for (
const auto &Factory : Factories)
730 Result.
Checks.insert(Factory.getKey());
732#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
733 SmallString<64> Buffer(AnalyzerCheckNamePrefix);
734 const size_t DefSize = Buffer.size();
735 for (
const auto &AnalyzerCheck : AnalyzerOptions::getRegisteredCheckers(
737 Buffer.truncate(DefSize);
738 Buffer.append(AnalyzerCheck);
739 Result.
Checks.insert(Buffer);
742 static constexpr StringRef OptionNames[] = {
743#define GET_CHECKER_OPTIONS
744#define CHECKER_OPTION(TYPE, CHECKER, OPTION_NAME, DESCRIPTION, DEFAULT, \
746 ANALYZER_CHECK_NAME_PREFIX CHECKER ":" OPTION_NAME,
748#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
750#undef GET_CHECKER_OPTIONS
753 Result.
Options.insert_range(OptionNames);
757 for (
const auto &Factory : Factories)
758 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
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 handleErrors(llvm::ArrayRef< ClangTidyError > Errors, ClangTidyContext &Context, FixBehaviour Fix, unsigned &WarningsAsErrorsCount, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS)
Displays the found Errors to the users.
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.