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.setShowColors(Context.getOptions().UseColor.value_or(
109 llvm::sys::Process::StandardOutHasColors())
111 : ShowColorsKind::Off);
112 DiagPrinter->BeginSourceFile(LangOpts);
113 if (DiagOpts.showColors(llvm::sys::Process::StandardOutHasColors()) &&
114 !llvm::sys::Process::StandardOutIsDisplayed())
115 llvm::sys::Process::UseANSIEscapeCodes(
true);
118 SourceManager &getSourceManager() {
return SourceMgr; }
120 void reportDiagnostic(
const ClangTidyError &Error) {
121 const tooling::DiagnosticMessage &Message =
Error.Message;
122 const SourceLocation Loc =
123 getLocation(Message.FilePath, Message.FileOffset);
126 SmallVector<std::pair<SourceLocation, bool>, 4> FixLocations;
128 auto Level =
static_cast<DiagnosticsEngine::Level
>(
Error.DiagLevel);
129 std::string Name =
Error.DiagnosticName;
130 if (!
Error.EnabledDiagnosticAliases.empty())
131 Name +=
"," + llvm::join(
Error.EnabledDiagnosticAliases,
",");
132 if (
Error.IsWarningAsError) {
133 Name +=
",-warnings-as-errors";
134 Level = DiagnosticsEngine::Error;
137 auto Diag = Diags.Report(Loc, Diags.getCustomDiagID(Level,
"%0 [%1]"))
138 << Message.Message << Name;
139 for (
const FileByteRange &FBR :
Error.Message.Ranges)
140 Diag << getRange(FBR);
142 const llvm::StringMap<Replacements> *ChosenFix =
nullptr;
145 for (
const auto &FileAndReplacements : *ChosenFix) {
146 for (
const auto &Repl : FileAndReplacements.second) {
148 bool CanBeApplied =
false;
149 if (!Repl.isApplicable())
151 SourceLocation FixLoc;
152 SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
153 Files.makeAbsolutePath(FixAbsoluteFilePath);
154 tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
155 Repl.getLength(), Repl.getReplacementText());
156 auto &Entry = FileReplacements[R.getFilePath()];
157 Replacements &Replacements = Entry.Replaces;
158 llvm::Error Err = Replacements.add(R);
161 llvm::errs() <<
"Trying to resolve conflict: "
162 << llvm::toString(std::move(Err)) <<
"\n";
163 const unsigned NewOffset =
164 Replacements.getShiftedCodePosition(R.getOffset());
165 const unsigned NewLength = Replacements.getShiftedCodePosition(
166 R.getOffset() + R.getLength()) -
168 if (NewLength == R.getLength()) {
169 R = Replacement(R.getFilePath(), NewOffset, NewLength,
170 R.getReplacementText());
171 Replacements = Replacements.merge(tooling::Replacements(R));
176 <<
"Can't resolve conflict, skipping the replacement.\n";
182 FixLoc = getLocation(FixAbsoluteFilePath, Repl.getOffset());
183 FixLocations.emplace_back(FixLoc, CanBeApplied);
184 Entry.BuildDir =
Error.BuildDirectory;
188 reportFix(Diag,
Error.Message.Fix);
190 for (
auto Fix : FixLocations) {
191 Diags.Report(
Fix.first,
Fix.second ? diag::note_fixit_applied
192 : diag::note_fixit_failed);
194 for (
const auto &Note :
Error.Notes)
199 if (TotalFixes > 0) {
200 auto &VFS = Files.getVirtualFileSystem();
201 auto OriginalCWD = VFS.getCurrentWorkingDirectory();
202 bool AnyNotWritten =
false;
204 for (
const auto &FileAndReplacements : FileReplacements) {
205 Rewriter Rewrite(SourceMgr, LangOpts);
206 const StringRef
File = FileAndReplacements.first();
207 VFS.setCurrentWorkingDirectory(FileAndReplacements.second.BuildDir);
208 llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
209 SourceMgr.getFileManager().getBufferForFile(File);
211 llvm::errs() <<
"Can't get buffer for file " <<
File <<
": "
212 << Buffer.getError().message() <<
"\n";
216 const StringRef Code = Buffer.get()->getBuffer();
217 auto Style = format::getStyle(
218 Context.getOptionsForFile(File).FormatStyle.value_or(
"none"), File,
221 llvm::errs() << llvm::toString(Style.takeError()) <<
"\n";
224 llvm::Expected<tooling::Replacements> Replacements =
225 format::cleanupAroundReplacements(
226 Code, FileAndReplacements.second.Replaces, *Style);
228 llvm::errs() << llvm::toString(Replacements.takeError()) <<
"\n";
231 if (llvm::Expected<tooling::Replacements> FormattedReplacements =
232 format::formatReplacements(Code, *Replacements, *Style)) {
233 Replacements = std::move(FormattedReplacements);
235 llvm_unreachable(
"!Replacements");
237 llvm::errs() << llvm::toString(FormattedReplacements.takeError())
238 <<
". Skipping formatting.\n";
240 if (!tooling::applyAllReplacements(Replacements.get(), Rewrite))
241 llvm::errs() <<
"Can't apply replacements for file " <<
File <<
"\n";
242 AnyNotWritten |= Rewrite.overwriteChangedFiles();
246 llvm::errs() <<
"clang-tidy failed to apply suggested fixes.\n";
248 llvm::errs() <<
"clang-tidy applied " << AppliedFixes <<
" of "
249 << TotalFixes <<
" suggested fixes.\n";
253 VFS.setCurrentWorkingDirectory(*OriginalCWD);
257 unsigned getWarningsAsErrorsCount()
const {
return WarningsAsErrors; }
260 SourceLocation getLocation(StringRef FilePath,
unsigned Offset) {
261 if (FilePath.empty())
264 auto File = SourceMgr.getFileManager().getOptionalFileRef(FilePath);
268 const FileID ID = SourceMgr.getOrCreateFileID(*File, SrcMgr::C_User);
269 return SourceMgr.getLocForStartOfFile(ID).getLocWithOffset(Offset);
272 void reportFix(
const DiagnosticBuilder &Diag,
273 const llvm::StringMap<Replacements> &
Fix) {
274 for (
const auto &FileAndReplacements :
Fix) {
275 for (
const auto &Repl : FileAndReplacements.second) {
276 if (!Repl.isApplicable())
279 FBR.FilePath = Repl.getFilePath().str();
280 FBR.FileOffset = Repl.getOffset();
281 FBR.Length = Repl.getLength();
283 Diag << FixItHint::CreateReplacement(getRange(FBR),
284 Repl.getReplacementText());
289 void reportNote(
const tooling::DiagnosticMessage &Message) {
290 const SourceLocation Loc =
291 getLocation(Message.FilePath, Message.FileOffset);
293 Diags.Report(Loc, Diags.getCustomDiagID(DiagnosticsEngine::Note,
"%0"))
295 for (
const FileByteRange &FBR : Message.Ranges)
296 Diag << getRange(FBR);
297 reportFix(Diag, Message.Fix);
300 CharSourceRange getRange(
const FileByteRange &Range) {
301 SmallString<128> AbsoluteFilePath{Range.FilePath};
302 Files.makeAbsolutePath(AbsoluteFilePath);
303 const SourceLocation BeginLoc =
304 getLocation(AbsoluteFilePath, Range.FileOffset);
305 const SourceLocation EndLoc = BeginLoc.getLocWithOffset(Range.Length);
309 return CharSourceRange::getCharRange(BeginLoc, EndLoc);
312 struct ReplacementsWithBuildDir {
314 Replacements Replaces;
318 LangOptions LangOpts;
319 DiagnosticOptions DiagOpts;
320 DiagnosticConsumer *DiagPrinter;
321 DiagnosticsEngine Diags;
322 SourceManager SourceMgr;
323 llvm::StringMap<ReplacementsWithBuildDir> FileReplacements;
324 ClangTidyContext &Context;
326 unsigned TotalFixes = 0U;
327 unsigned AppliedFixes = 0U;
328 unsigned WarningsAsErrors = 0U;
331class ClangTidyASTConsumer :
public MultiplexConsumer {
333 ClangTidyASTConsumer(std::vector<std::unique_ptr<ASTConsumer>> Consumers,
334 std::unique_ptr<ClangTidyProfiling> Profiling,
335 std::unique_ptr<ast_matchers::MatchFinder> Finder,
336 std::vector<std::unique_ptr<ClangTidyCheck>> Checks)
337 : MultiplexConsumer(std::move(Consumers)),
338 Profiling(std::move(Profiling)), Finder(std::move(Finder)),
339 Checks(std::move(Checks)) {}
344 std::unique_ptr<ClangTidyProfiling> Profiling;
345 std::unique_ptr<ast_matchers::MatchFinder> Finder;
346 std::vector<std::unique_ptr<ClangTidyCheck>> Checks;
347 void anchor()
override {}
354 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS)
355 : Context(Context), OverlayFS(std::
move(OverlayFS)),
357#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
361 for (
const ClangTidyModuleRegistry::entry E :
362 ClangTidyModuleRegistry::entries()) {
363 std::unique_ptr<ClangTidyModule> Module = E.instantiate();
364 Module->addCheckFactories(*CheckFactories);
368#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
370 AnalyzerOptions &AnalyzerOptions) {
372 StringRef OptName(Opt.getKey());
373 if (!OptName.consume_front(AnalyzerCheckNamePrefix))
376 AnalyzerOptions.Config[OptName] = Opt.getValue().Value;
380using CheckersList = std::vector<std::pair<std::string, bool>>;
382static CheckersList getAnalyzerCheckersAndPackages(ClangTidyContext &Context,
383 bool IncludeExperimental) {
386 const auto &RegisteredCheckers =
387 AnalyzerOptions::getRegisteredCheckers(IncludeExperimental);
388 const bool AnalyzerChecksEnabled =
389 llvm::any_of(RegisteredCheckers, [&](StringRef CheckName) ->
bool {
390 return Context.isCheckEnabled(
391 (AnalyzerCheckNamePrefix + CheckName).str());
394 if (!AnalyzerChecksEnabled)
402 for (
const StringRef CheckName : RegisteredCheckers) {
403 const std::string ClangTidyCheckName(
404 (AnalyzerCheckNamePrefix + CheckName).str());
406 if (CheckName.starts_with(
"core") ||
407 Context.isCheckEnabled(ClangTidyCheckName)) {
408 List.emplace_back(std::string(CheckName),
true);
415std::unique_ptr<ASTConsumer>
420 SourceManager *SM = &Compiler.getSourceManager();
421 Context.setSourceManager(SM);
422 Context.setCurrentFile(File);
423 Context.setASTContext(&Compiler.getASTContext());
425 auto WorkingDir = Compiler.getSourceManager()
427 .getVirtualFileSystem()
428 .getCurrentWorkingDirectory();
430 Context.setCurrentBuildDirectory(WorkingDir.get());
431#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
435 std::vector<std::unique_ptr<ClangTidyCheck>>
Checks =
436 CheckFactories->createChecksForLanguage(&Context);
438 ast_matchers::MatchFinder::MatchFinderOptions FinderOptions;
441 FinderOptions.SkipDeclsInModules =
true;
443 std::unique_ptr<ClangTidyProfiling> Profiling;
444 if (Context.getEnableProfiling()) {
446 std::make_unique<ClangTidyProfiling>(Context.getProfileStorageParams());
447 FinderOptions.CheckProfiling.emplace(Profiling->Records);
451 if (!Context.getOptions().SystemHeaders.value_or(
false))
452 FinderOptions.IgnoreSystemHeaders =
true;
455 std::make_unique<ast_matchers::MatchFinder>(std::move(FinderOptions));
457 Preprocessor *PP = &Compiler.getPreprocessor();
458 Preprocessor *ModuleExpanderPP = PP;
460 if (Context.canEnableModuleHeadersParsing() &&
461 Context.getLangOpts().Modules && OverlayFS !=
nullptr) {
462 auto ModuleExpander = std::make_unique<ExpandModularHeadersPPCallbacks>(
463 &Compiler, *OverlayFS);
464 ModuleExpanderPP = ModuleExpander->getPreprocessor();
465 PP->addPPCallbacks(std::move(ModuleExpander));
468 for (
auto &Check :
Checks) {
469 Check->registerMatchers(&*Finder);
470 Check->registerPPCallbacks(*SM, PP, ModuleExpanderPP);
473 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
475 Consumers.push_back(Finder->newASTConsumer());
477#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
478 AnalyzerOptions &AnalyzerOptions = Compiler.getAnalyzerOpts();
479 AnalyzerOptions.CheckersAndPackages = getAnalyzerCheckersAndPackages(
480 Context, Context.canEnableAnalyzerAlphaCheckers());
481 if (!AnalyzerOptions.CheckersAndPackages.empty()) {
482 setStaticAnalyzerCheckerOpts(Context.getOptions(), AnalyzerOptions);
483 AnalyzerOptions.AnalysisDiagOpt = PD_NONE;
484 std::unique_ptr<ento::AnalysisASTConsumer> AnalysisConsumer =
485 ento::CreateAnalysisConsumer(Compiler);
486 AnalysisConsumer->AddDiagnosticConsumer(
487 std::make_unique<AnalyzerDiagnosticConsumer>(Context));
488 Consumers.push_back(std::move(AnalysisConsumer));
491 return std::make_unique<ClangTidyASTConsumer>(
492 std::move(Consumers), std::move(Profiling), std::move(Finder),
497 std::vector<std::string> CheckNames;
498 for (
const auto &CheckFactory : *CheckFactories)
499 if (Context.isCheckEnabled(CheckFactory.getKey()))
500 CheckNames.emplace_back(CheckFactory.getKey());
502#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
503 for (
const auto &AnalyzerCheck : getAnalyzerCheckersAndPackages(
504 Context, Context.canEnableAnalyzerAlphaCheckers()))
505 CheckNames.emplace_back(
506 (AnalyzerCheckNamePrefix + AnalyzerCheck.first).str());
509 llvm::sort(CheckNames);
515 const std::vector<std::unique_ptr<ClangTidyCheck>>
Checks =
516 CheckFactories->createChecks(&Context);
517 for (
const auto &Check :
Checks)
518 Check->storeOptions(Options);
534 const std::vector<std::string> &EnabledChecks) {
536 for (
const auto &[OptionName, Value] : Options.
CheckOptions) {
537 const size_t CheckNameEndPos = OptionName.find(
'.');
538 if (CheckNameEndPos == StringRef::npos)
540 const StringRef CheckName = OptionName.substr(0, CheckNameEndPos);
541 if (llvm::binary_search(EnabledChecks, CheckName))
542 FilteredOptions[OptionName] = Value;
556 auto DiagOpts = std::make_unique<DiagnosticOptions>();
557 DiagnosticsEngine DE(llvm::makeIntrusiveRefCnt<DiagnosticIDs>(), *DiagOpts,
558 &DiagConsumer,
false);
564std::vector<ClangTidyError>
566 ArrayRef<std::string> InputFiles,
567 llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
570 ClangTool Tool(Compilations, InputFiles,
571 std::make_shared<PCHContainerOperations>(), BaseFS);
574 const ArgumentsAdjuster PerFileExtraArgumentsInserter =
575 [&Context](
const CommandLineArguments &Args, StringRef Filename) {
577 CommandLineArguments AdjustedArgs = Args;
579 auto I = AdjustedArgs.begin();
580 if (I != AdjustedArgs.end() && !StringRef(*I).starts_with(
'-'))
586 AdjustedArgs.insert(AdjustedArgs.end(), Opts.
ExtraArgs->begin(),
592 const ArgumentsAdjuster PerFileArgumentRemover =
593 [&Context](
const CommandLineArguments &Args, StringRef Filename) {
595 CommandLineArguments AdjustedArgs = Args;
598 for (
const StringRef ArgToRemove : *Opts.
RemovedArgs) {
599 AdjustedArgs.erase(std::remove(AdjustedArgs.begin(),
600 AdjustedArgs.end(), ArgToRemove),
608 Tool.appendArgumentsAdjuster(PerFileArgumentRemover);
609 Tool.appendArgumentsAdjuster(PerFileExtraArgumentsInserter);
610 Tool.appendArgumentsAdjuster(getStripPluginsAdjuster());
615 auto DiagOpts = std::make_unique<DiagnosticOptions>();
616 DiagnosticsEngine DE(DiagnosticIDs::create(), *DiagOpts, &DiagConsumer,
619 Tool.setDiagnosticConsumer(&DiagConsumer);
624 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
626 : ConsumerFactory(Context, std::move(BaseFS)),
Quiet(
Quiet) {}
627 std::unique_ptr<FrontendAction> create()
override {
628 return std::make_unique<Action>(&ConsumerFactory);
631 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
633 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
636 Invocation->getPreprocessorOpts().SetUpStaticAnalyzer =
true;
638 Invocation->getDiagnosticOpts().ShowCarets =
false;
639 return FrontendActionFactory::runInvocation(
640 Invocation, Files, PCHContainerOps, DiagConsumer);
644 class Action :
public ASTFrontendAction {
651 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
652 StringRef File)
override {
661 ActionFactory Factory(Context, std::move(BaseFS),
Quiet);
663 return DiagConsumer.
take();
668 unsigned &WarningsAsErrorsCount,
669 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
670 ErrorReporter Reporter(Context,
Fix, std::move(BaseFS));
671 llvm::vfs::FileSystem &FileSystem =
672 Reporter.getSourceManager().getFileManager().getVirtualFileSystem();
673 auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();
674 if (!InitialWorkingDir)
675 llvm::report_fatal_error(
"Cannot get current working path.");
678 if (!Error.BuildDirectory.empty()) {
683 FileSystem.setCurrentWorkingDirectory(Error.BuildDirectory);
685 Reporter.reportDiagnostic(Error);
687 FileSystem.setCurrentWorkingDirectory(InitialWorkingDir.get());
690 WarningsAsErrorsCount += Reporter.getWarningsAsErrorsCount();
694 const std::vector<ClangTidyError> &Errors,
696 TranslationUnitDiagnostics TUD;
697 TUD.MainSourceFile = std::string(MainFilePath);
698 for (
const auto &Error : Errors) {
699 tooling::Diagnostic Diag = Error;
700 if (Error.IsWarningAsError)
701 Diag.DiagLevel = tooling::Diagnostic::Error;
702 TUD.Diagnostics.insert(TUD.Diagnostics.end(), Diag);
705 yaml::Output YAML(OS);
718#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
722 for (
const ClangTidyModuleRegistry::entry &Module :
723 ClangTidyModuleRegistry::entries()) {
724 Module.instantiate()->addCheckFactories(Factories);
727 for (
const auto &Factory : Factories)
728 Result.
Checks.insert(Factory.getKey());
730#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
731 SmallString<64> Buffer(AnalyzerCheckNamePrefix);
732 const size_t DefSize = Buffer.size();
733 for (
const auto &AnalyzerCheck : AnalyzerOptions::getRegisteredCheckers(
735 Buffer.truncate(DefSize);
736 Buffer.append(AnalyzerCheck);
737 Result.
Checks.insert(Buffer);
740 static constexpr StringRef OptionNames[] = {
741#define GET_CHECKER_OPTIONS
742#define CHECKER_OPTION(TYPE, CHECKER, OPTION_NAME, DESCRIPTION, DEFAULT, \
744 ANALYZER_CHECK_NAME_PREFIX CHECKER ":" OPTION_NAME,
746#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
748#undef GET_CHECKER_OPTIONS
751 Result.
Options.insert_range(OptionNames);
755 for (
const auto &Factory : Factories)
756 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.