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/Frontend/AnalysisConsumer.h"
49using namespace clang::driver;
57#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
60 ClangTidyCheckFactories &Factories) =
nullptr;
65#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
66#define ANALYZER_CHECK_NAME_PREFIX "clang-analyzer-"
67static constexpr StringRef AnalyzerCheckNamePrefix = ANALYZER_CHECK_NAME_PREFIX;
69class AnalyzerDiagnosticConsumer :
public ento::PathDiagnosticConsumer {
71 AnalyzerDiagnosticConsumer(ClangTidyContext &Context) : Context(Context) {}
73 void FlushDiagnosticsImpl(std::vector<const ento::PathDiagnostic *> &Diags,
74 FilesMade *FilesMade)
override {
75 for (
const ento::PathDiagnostic *PD : Diags) {
76 SmallString<64> CheckName(AnalyzerCheckNamePrefix);
77 CheckName += PD->getCheckerName();
78 Context.diag(CheckName, PD->getLocation().asLocation(),
79 PD->getShortDescription())
80 << PD->path.back()->getRanges();
82 for (
const auto &DiagPiece :
83 PD->path.flatten(
true)) {
84 Context.diag(CheckName, DiagPiece->getLocation().asLocation(),
85 DiagPiece->getString(), DiagnosticIDs::Note)
86 << DiagPiece->getRanges();
91 StringRef getName()
const override {
return "ClangTidyDiags"; }
92 bool supportsLogicalOpControlFlow()
const override {
return true; }
93 bool supportsCrossFileDiagnostics()
const override {
return true; }
96 ClangTidyContext &Context;
102 ErrorReporter(ClangTidyContext &Context,
FixBehaviour ApplyFixes,
103 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS)
104 : Files(FileSystemOptions(), std::move(BaseFS)),
105 DiagPrinter(new TextDiagnosticPrinter(llvm::outs(), DiagOpts)),
106 Diags(DiagnosticIDs::create(), DiagOpts, DiagPrinter),
107 SourceMgr(Diags, Files), Context(Context), ApplyFixes(ApplyFixes) {
108 DiagOpts.ShowColors = Context.getOptions().
UseColor.value_or(
109 llvm::sys::Process::StandardOutHasColors());
110 DiagPrinter->BeginSourceFile(LangOpts);
111 if (DiagOpts.ShowColors && !llvm::sys::Process::StandardOutIsDisplayed())
112 llvm::sys::Process::UseANSIEscapeCodes(
true);
115 SourceManager &getSourceManager() {
return SourceMgr; }
117 void reportDiagnostic(
const ClangTidyError &Error) {
118 const tooling::DiagnosticMessage &Message =
Error.Message;
119 const SourceLocation Loc =
120 getLocation(Message.FilePath, Message.FileOffset);
123 SmallVector<std::pair<SourceLocation, bool>, 4> FixLocations;
125 auto Level =
static_cast<DiagnosticsEngine::Level
>(
Error.DiagLevel);
126 std::string Name =
Error.DiagnosticName;
127 if (!
Error.EnabledDiagnosticAliases.empty())
128 Name +=
"," + llvm::join(
Error.EnabledDiagnosticAliases,
",");
129 if (
Error.IsWarningAsError) {
130 Name +=
",-warnings-as-errors";
131 Level = DiagnosticsEngine::Error;
134 auto Diag = Diags.Report(Loc, Diags.getCustomDiagID(Level,
"%0 [%1]"))
135 << Message.Message << Name;
136 for (
const FileByteRange &FBR :
Error.Message.Ranges)
137 Diag << getRange(FBR);
139 const llvm::StringMap<Replacements> *ChosenFix =
nullptr;
142 for (
const auto &FileAndReplacements : *ChosenFix) {
143 for (
const auto &Repl : FileAndReplacements.second) {
145 bool CanBeApplied =
false;
146 if (!Repl.isApplicable())
148 SourceLocation FixLoc;
149 SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
150 Files.makeAbsolutePath(FixAbsoluteFilePath);
151 tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
152 Repl.getLength(), Repl.getReplacementText());
153 auto &Entry = FileReplacements[R.getFilePath()];
154 Replacements &Replacements = Entry.Replaces;
155 llvm::Error Err = Replacements.add(R);
158 llvm::errs() <<
"Trying to resolve conflict: "
159 << llvm::toString(std::move(Err)) <<
"\n";
160 const unsigned NewOffset =
161 Replacements.getShiftedCodePosition(R.getOffset());
162 const unsigned NewLength = Replacements.getShiftedCodePosition(
163 R.getOffset() + R.getLength()) -
165 if (NewLength == R.getLength()) {
166 R = Replacement(R.getFilePath(), NewOffset, NewLength,
167 R.getReplacementText());
168 Replacements = Replacements.merge(tooling::Replacements(R));
173 <<
"Can't resolve conflict, skipping the replacement.\n";
179 FixLoc = getLocation(FixAbsoluteFilePath, Repl.getOffset());
180 FixLocations.emplace_back(FixLoc, CanBeApplied);
181 Entry.BuildDir =
Error.BuildDirectory;
185 reportFix(Diag,
Error.Message.Fix);
187 for (
auto Fix : FixLocations) {
188 Diags.Report(
Fix.first,
Fix.second ? diag::note_fixit_applied
189 : diag::note_fixit_failed);
191 for (
const auto &Note :
Error.Notes)
196 if (TotalFixes > 0) {
197 auto &VFS = Files.getVirtualFileSystem();
198 auto OriginalCWD = VFS.getCurrentWorkingDirectory();
199 bool AnyNotWritten =
false;
201 for (
const auto &FileAndReplacements : FileReplacements) {
202 Rewriter Rewrite(SourceMgr, LangOpts);
203 const StringRef
File = FileAndReplacements.first();
204 VFS.setCurrentWorkingDirectory(FileAndReplacements.second.BuildDir);
205 llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
206 SourceMgr.getFileManager().getBufferForFile(File);
208 llvm::errs() <<
"Can't get buffer for file " <<
File <<
": "
209 << Buffer.getError().message() <<
"\n";
213 const StringRef Code = Buffer.get()->getBuffer();
214 auto Style = format::getStyle(
215 Context.getOptionsForFile(File).FormatStyle.value_or(
"none"), File,
218 llvm::errs() << llvm::toString(Style.takeError()) <<
"\n";
221 llvm::Expected<tooling::Replacements> Replacements =
222 format::cleanupAroundReplacements(
223 Code, FileAndReplacements.second.Replaces, *Style);
225 llvm::errs() << llvm::toString(Replacements.takeError()) <<
"\n";
228 if (llvm::Expected<tooling::Replacements> FormattedReplacements =
229 format::formatReplacements(Code, *Replacements, *Style)) {
230 Replacements = std::move(FormattedReplacements);
232 llvm_unreachable(
"!Replacements");
234 llvm::errs() << llvm::toString(FormattedReplacements.takeError())
235 <<
". Skipping formatting.\n";
237 if (!tooling::applyAllReplacements(Replacements.get(), Rewrite))
238 llvm::errs() <<
"Can't apply replacements for file " <<
File <<
"\n";
239 AnyNotWritten |= Rewrite.overwriteChangedFiles();
243 llvm::errs() <<
"clang-tidy failed to apply suggested fixes.\n";
245 llvm::errs() <<
"clang-tidy applied " << AppliedFixes <<
" of "
246 << TotalFixes <<
" suggested fixes.\n";
250 VFS.setCurrentWorkingDirectory(*OriginalCWD);
254 unsigned getWarningsAsErrorsCount()
const {
return WarningsAsErrors; }
257 SourceLocation getLocation(StringRef FilePath,
unsigned Offset) {
258 if (FilePath.empty())
261 auto File = SourceMgr.getFileManager().getOptionalFileRef(FilePath);
265 const FileID ID = SourceMgr.getOrCreateFileID(*File, SrcMgr::C_User);
266 return SourceMgr.getLocForStartOfFile(ID).getLocWithOffset(Offset);
269 void reportFix(
const DiagnosticBuilder &Diag,
270 const llvm::StringMap<Replacements> &
Fix) {
271 for (
const auto &FileAndReplacements :
Fix) {
272 for (
const auto &Repl : FileAndReplacements.second) {
273 if (!Repl.isApplicable())
276 FBR.FilePath = Repl.getFilePath().str();
277 FBR.FileOffset = Repl.getOffset();
278 FBR.Length = Repl.getLength();
280 Diag << FixItHint::CreateReplacement(getRange(FBR),
281 Repl.getReplacementText());
286 void reportNote(
const tooling::DiagnosticMessage &Message) {
287 const SourceLocation Loc =
288 getLocation(Message.FilePath, Message.FileOffset);
290 Diags.Report(Loc, Diags.getCustomDiagID(DiagnosticsEngine::Note,
"%0"))
292 for (
const FileByteRange &FBR : Message.Ranges)
293 Diag << getRange(FBR);
294 reportFix(Diag, Message.Fix);
297 CharSourceRange getRange(
const FileByteRange &Range) {
298 SmallString<128> AbsoluteFilePath{Range.FilePath};
299 Files.makeAbsolutePath(AbsoluteFilePath);
300 const SourceLocation BeginLoc =
301 getLocation(AbsoluteFilePath, Range.FileOffset);
302 const SourceLocation EndLoc = BeginLoc.getLocWithOffset(Range.Length);
306 return CharSourceRange::getCharRange(BeginLoc, EndLoc);
309 struct ReplacementsWithBuildDir {
311 Replacements Replaces;
315 LangOptions LangOpts;
316 DiagnosticOptions DiagOpts;
317 DiagnosticConsumer *DiagPrinter;
318 DiagnosticsEngine Diags;
319 SourceManager SourceMgr;
320 llvm::StringMap<ReplacementsWithBuildDir> FileReplacements;
321 ClangTidyContext &Context;
323 unsigned TotalFixes = 0U;
324 unsigned AppliedFixes = 0U;
325 unsigned WarningsAsErrors = 0U;
328class ClangTidyASTConsumer :
public MultiplexConsumer {
330 ClangTidyASTConsumer(std::vector<std::unique_ptr<ASTConsumer>> Consumers,
331 std::unique_ptr<ClangTidyProfiling> Profiling,
332 std::unique_ptr<ast_matchers::MatchFinder> Finder,
333 std::vector<std::unique_ptr<ClangTidyCheck>> Checks)
334 : MultiplexConsumer(std::move(Consumers)),
335 Profiling(std::move(Profiling)), Finder(std::move(Finder)),
336 Checks(std::move(Checks)) {}
341 std::unique_ptr<ClangTidyProfiling> Profiling;
342 std::unique_ptr<ast_matchers::MatchFinder> Finder;
343 std::vector<std::unique_ptr<ClangTidyCheck>> Checks;
344 void anchor()
override {}
351 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS)
352 : Context(Context), OverlayFS(std::
move(OverlayFS)),
354#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
358 for (
const ClangTidyModuleRegistry::entry E :
359 ClangTidyModuleRegistry::entries()) {
360 std::unique_ptr<ClangTidyModule> Module = E.instantiate();
361 Module->addCheckFactories(*CheckFactories);
365#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
367 AnalyzerOptions &AnalyzerOptions) {
369 StringRef OptName(Opt.getKey());
370 if (!OptName.consume_front(AnalyzerCheckNamePrefix))
373 AnalyzerOptions.Config[OptName] = Opt.getValue().Value;
377using CheckersList = std::vector<std::pair<std::string, bool>>;
379static CheckersList getAnalyzerCheckersAndPackages(ClangTidyContext &Context,
380 bool IncludeExperimental) {
383 const auto &RegisteredCheckers =
384 AnalyzerOptions::getRegisteredCheckers(IncludeExperimental);
385 const bool AnalyzerChecksEnabled =
386 llvm::any_of(RegisteredCheckers, [&](StringRef CheckName) ->
bool {
387 return Context.isCheckEnabled(
388 (AnalyzerCheckNamePrefix + CheckName).str());
391 if (!AnalyzerChecksEnabled)
399 for (
const StringRef CheckName : RegisteredCheckers) {
400 const std::string ClangTidyCheckName(
401 (AnalyzerCheckNamePrefix + CheckName).str());
403 if (CheckName.starts_with(
"core") ||
404 Context.isCheckEnabled(ClangTidyCheckName)) {
405 List.emplace_back(std::string(CheckName),
true);
412std::unique_ptr<ASTConsumer>
417 SourceManager *SM = &Compiler.getSourceManager();
418 Context.setSourceManager(SM);
419 Context.setCurrentFile(File);
420 Context.setASTContext(&Compiler.getASTContext());
422 auto WorkingDir = Compiler.getSourceManager()
424 .getVirtualFileSystem()
425 .getCurrentWorkingDirectory();
427 Context.setCurrentBuildDirectory(WorkingDir.get());
428#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
432 std::vector<std::unique_ptr<ClangTidyCheck>>
Checks =
433 CheckFactories->createChecksForLanguage(&Context);
435 ast_matchers::MatchFinder::MatchFinderOptions FinderOptions;
437 std::unique_ptr<ClangTidyProfiling> Profiling;
438 if (Context.getEnableProfiling()) {
440 std::make_unique<ClangTidyProfiling>(Context.getProfileStorageParams());
441 FinderOptions.CheckProfiling.emplace(Profiling->Records);
445 if (!Context.getOptions().SystemHeaders.value_or(
false))
446 FinderOptions.IgnoreSystemHeaders =
true;
449 std::make_unique<ast_matchers::MatchFinder>(std::move(FinderOptions));
451 Preprocessor *PP = &Compiler.getPreprocessor();
452 Preprocessor *ModuleExpanderPP = PP;
454 if (Context.canEnableModuleHeadersParsing() &&
455 Context.getLangOpts().Modules && OverlayFS !=
nullptr) {
456 auto ModuleExpander = std::make_unique<ExpandModularHeadersPPCallbacks>(
457 &Compiler, *OverlayFS);
458 ModuleExpanderPP = ModuleExpander->getPreprocessor();
459 PP->addPPCallbacks(std::move(ModuleExpander));
462 for (
auto &Check :
Checks) {
463 Check->registerMatchers(&*Finder);
464 Check->registerPPCallbacks(*SM, PP, ModuleExpanderPP);
467 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
469 Consumers.push_back(Finder->newASTConsumer());
471#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
472 AnalyzerOptions &AnalyzerOptions = Compiler.getAnalyzerOpts();
473 AnalyzerOptions.CheckersAndPackages = getAnalyzerCheckersAndPackages(
474 Context, Context.canEnableAnalyzerAlphaCheckers());
475 if (!AnalyzerOptions.CheckersAndPackages.empty()) {
476 setStaticAnalyzerCheckerOpts(Context.getOptions(), AnalyzerOptions);
477 AnalyzerOptions.AnalysisDiagOpt = PD_NONE;
478 std::unique_ptr<ento::AnalysisASTConsumer> AnalysisConsumer =
479 ento::CreateAnalysisConsumer(Compiler);
480 AnalysisConsumer->AddDiagnosticConsumer(
481 std::make_unique<AnalyzerDiagnosticConsumer>(Context));
482 Consumers.push_back(std::move(AnalysisConsumer));
485 return std::make_unique<ClangTidyASTConsumer>(
486 std::move(Consumers), std::move(Profiling), std::move(Finder),
491 std::vector<std::string> CheckNames;
492 for (
const auto &CheckFactory : *CheckFactories)
493 if (Context.isCheckEnabled(CheckFactory.getKey()))
494 CheckNames.emplace_back(CheckFactory.getKey());
496#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
497 for (
const auto &AnalyzerCheck : getAnalyzerCheckersAndPackages(
498 Context, Context.canEnableAnalyzerAlphaCheckers()))
499 CheckNames.emplace_back(
500 (AnalyzerCheckNamePrefix + AnalyzerCheck.first).str());
503 llvm::sort(CheckNames);
509 const std::vector<std::unique_ptr<ClangTidyCheck>>
Checks =
510 CheckFactories->createChecks(&Context);
511 for (
const auto &Check :
Checks)
512 Check->storeOptions(Options);
528 const std::vector<std::string> &EnabledChecks) {
530 for (
const auto &[OptionName, Value] : Options.
CheckOptions) {
531 const size_t CheckNameEndPos = OptionName.find(
'.');
532 if (CheckNameEndPos == StringRef::npos)
534 const StringRef CheckName = OptionName.substr(0, CheckNameEndPos);
535 if (llvm::binary_search(EnabledChecks, CheckName))
536 FilteredOptions[OptionName] = Value;
550 auto DiagOpts = std::make_unique<DiagnosticOptions>();
551 DiagnosticsEngine DE(llvm::makeIntrusiveRefCnt<DiagnosticIDs>(), *DiagOpts,
552 &DiagConsumer,
false);
558std::vector<ClangTidyError>
560 ArrayRef<std::string> InputFiles,
561 llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
564 ClangTool Tool(Compilations, InputFiles,
565 std::make_shared<PCHContainerOperations>(), BaseFS);
568 const ArgumentsAdjuster PerFileExtraArgumentsInserter =
569 [&Context](
const CommandLineArguments &Args, StringRef Filename) {
571 CommandLineArguments AdjustedArgs = Args;
573 auto I = AdjustedArgs.begin();
574 if (I != AdjustedArgs.end() && !StringRef(*I).starts_with(
'-'))
580 AdjustedArgs.insert(AdjustedArgs.end(), Opts.
ExtraArgs->begin(),
586 const ArgumentsAdjuster PerFileArgumentRemover =
587 [&Context](
const CommandLineArguments &Args, StringRef Filename) {
589 CommandLineArguments AdjustedArgs = Args;
592 for (
const StringRef ArgToRemove : *Opts.
RemovedArgs) {
593 AdjustedArgs.erase(std::remove(AdjustedArgs.begin(),
594 AdjustedArgs.end(), ArgToRemove),
602 Tool.appendArgumentsAdjuster(PerFileArgumentRemover);
603 Tool.appendArgumentsAdjuster(PerFileExtraArgumentsInserter);
604 Tool.appendArgumentsAdjuster(getStripPluginsAdjuster());
609 auto DiagOpts = std::make_unique<DiagnosticOptions>();
610 DiagnosticsEngine DE(DiagnosticIDs::create(), *DiagOpts, &DiagConsumer,
613 Tool.setDiagnosticConsumer(&DiagConsumer);
618 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
620 : ConsumerFactory(Context, std::move(BaseFS)),
Quiet(
Quiet) {}
621 std::unique_ptr<FrontendAction> create()
override {
622 return std::make_unique<Action>(&ConsumerFactory);
625 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
627 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
630 Invocation->getPreprocessorOpts().SetUpStaticAnalyzer =
true;
632 Invocation->getDiagnosticOpts().ShowCarets =
false;
633 return FrontendActionFactory::runInvocation(
634 Invocation, Files, PCHContainerOps, DiagConsumer);
638 class Action :
public ASTFrontendAction {
645 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
646 StringRef File)
override {
655 ActionFactory Factory(Context, std::move(BaseFS),
Quiet);
657 return DiagConsumer.
take();
662 unsigned &WarningsAsErrorsCount,
663 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
664 ErrorReporter Reporter(Context,
Fix, std::move(BaseFS));
665 llvm::vfs::FileSystem &FileSystem =
666 Reporter.getSourceManager().getFileManager().getVirtualFileSystem();
667 auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();
668 if (!InitialWorkingDir)
669 llvm::report_fatal_error(
"Cannot get current working path.");
672 if (!Error.BuildDirectory.empty()) {
677 FileSystem.setCurrentWorkingDirectory(Error.BuildDirectory);
679 Reporter.reportDiagnostic(Error);
681 FileSystem.setCurrentWorkingDirectory(InitialWorkingDir.get());
684 WarningsAsErrorsCount += Reporter.getWarningsAsErrorsCount();
688 const std::vector<ClangTidyError> &Errors,
690 TranslationUnitDiagnostics TUD;
691 TUD.MainSourceFile = std::string(MainFilePath);
692 for (
const auto &Error : Errors) {
693 tooling::Diagnostic Diag = Error;
694 if (Error.IsWarningAsError)
695 Diag.DiagLevel = tooling::Diagnostic::Error;
696 TUD.Diagnostics.insert(TUD.Diagnostics.end(), Diag);
699 yaml::Output YAML(OS);
712#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
716 for (
const ClangTidyModuleRegistry::entry &Module :
717 ClangTidyModuleRegistry::entries()) {
718 Module.instantiate()->addCheckFactories(Factories);
721 for (
const auto &Factory : Factories)
722 Result.
Checks.insert(Factory.getKey());
724#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
725 SmallString<64> Buffer(AnalyzerCheckNamePrefix);
726 const size_t DefSize = Buffer.size();
727 for (
const auto &AnalyzerCheck : AnalyzerOptions::getRegisteredCheckers(
729 Buffer.truncate(DefSize);
730 Buffer.append(AnalyzerCheck);
731 Result.
Checks.insert(Buffer);
734 static constexpr StringRef OptionNames[] = {
735#define GET_CHECKER_OPTIONS
736#define CHECKER_OPTION(TYPE, CHECKER, OPTION_NAME, DESCRIPTION, DEFAULT, \
738 ANALYZER_CHECK_NAME_PREFIX CHECKER ":" OPTION_NAME,
740#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
742#undef GET_CHECKER_OPTIONS
745 Result.
Options.insert_range(OptionNames);
749 for (
const auto &Factory : Factories)
750 Factory.getValue()(Factory.getKey(), &Context);
static cl::opt< bool > UseColor("use-color", cl::desc(R"(Use colors in detailed AST output. If not set, colors
will be used if the terminal connected to
standard output supports colors.)"), cl::init(false), cl::cat(ClangQueryCategory))
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.