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;
138 Diags.Report(Loc, Diags.getCustomDiagID(Level,
"%0 [%1]"))
139 << Message.Message << Name;
140 for (
const FileByteRange &FBR :
Error.Message.Ranges)
141 Diag << getRange(FBR);
143 const llvm::StringMap<Replacements> *ChosenFix =
nullptr;
146 for (
const auto &FileAndReplacements : *ChosenFix) {
147 for (
const auto &Repl : FileAndReplacements.second) {
149 bool CanBeApplied =
false;
150 if (!Repl.isApplicable())
152 SourceLocation FixLoc;
153 SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
154 Files.makeAbsolutePath(FixAbsoluteFilePath);
155 tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
156 Repl.getLength(), Repl.getReplacementText());
157 auto &Entry = FileReplacements[R.getFilePath()];
158 Replacements &Replacements = Entry.Replaces;
159 llvm::Error Err = Replacements.add(R);
162 llvm::errs() <<
"Trying to resolve conflict: "
163 << llvm::toString(std::move(Err)) <<
"\n";
164 const unsigned NewOffset =
165 Replacements.getShiftedCodePosition(R.getOffset());
166 const unsigned NewLength = Replacements.getShiftedCodePosition(
167 R.getOffset() + R.getLength()) -
169 if (NewLength == R.getLength()) {
170 R = Replacement(R.getFilePath(), NewOffset, NewLength,
171 R.getReplacementText());
172 Replacements = Replacements.merge(tooling::Replacements(R));
177 <<
"Can't resolve conflict, skipping the replacement.\n";
183 FixLoc = getLocation(FixAbsoluteFilePath, Repl.getOffset());
184 FixLocations.emplace_back(FixLoc, CanBeApplied);
185 Entry.BuildDir =
Error.BuildDirectory;
189 reportFix(Diag,
Error.Message.Fix);
191 for (
const auto &
Fix : FixLocations) {
192 Diags.Report(
Fix.first,
Fix.second ? diag::note_fixit_applied
193 : diag::note_fixit_failed);
195 for (
const auto &Note :
Error.Notes)
200 if (TotalFixes > 0) {
201 auto &VFS = Files.getVirtualFileSystem();
202 auto OriginalCWD = VFS.getCurrentWorkingDirectory();
203 bool AnyNotWritten =
false;
205 for (
const auto &FileAndReplacements : FileReplacements) {
206 Rewriter Rewrite(SourceMgr, LangOpts);
207 const StringRef
File = FileAndReplacements.first();
208 VFS.setCurrentWorkingDirectory(FileAndReplacements.second.BuildDir);
209 llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
210 SourceMgr.getFileManager().getBufferForFile(File);
212 llvm::errs() <<
"Can't get buffer for file " <<
File <<
": "
213 << Buffer.getError().message() <<
"\n";
217 const StringRef Code = Buffer.get()->getBuffer();
218 auto Style = format::getStyle(
219 Context.getOptionsForFile(File).FormatStyle.value_or(
"none"), File,
222 llvm::errs() << llvm::toString(Style.takeError()) <<
"\n";
225 llvm::Expected<tooling::Replacements> Replacements =
226 format::cleanupAroundReplacements(
227 Code, FileAndReplacements.second.Replaces, *Style);
229 llvm::errs() << llvm::toString(Replacements.takeError()) <<
"\n";
232 if (llvm::Expected<tooling::Replacements> FormattedReplacements =
233 format::formatReplacements(Code, *Replacements, *Style)) {
234 Replacements = std::move(FormattedReplacements);
236 llvm_unreachable(
"!Replacements");
238 llvm::errs() << llvm::toString(FormattedReplacements.takeError())
239 <<
". Skipping formatting.\n";
241 if (!tooling::applyAllReplacements(Replacements.get(), Rewrite))
242 llvm::errs() <<
"Can't apply replacements for file " <<
File <<
"\n";
243 AnyNotWritten |= Rewrite.overwriteChangedFiles();
247 llvm::errs() <<
"clang-tidy failed to apply suggested fixes.\n";
249 llvm::errs() <<
"clang-tidy applied " << AppliedFixes <<
" of "
250 << TotalFixes <<
" suggested fixes.\n";
254 VFS.setCurrentWorkingDirectory(*OriginalCWD);
258 unsigned getWarningsAsErrorsCount()
const {
return WarningsAsErrors; }
261 SourceLocation getLocation(StringRef FilePath,
unsigned Offset) {
262 if (FilePath.empty())
265 auto File = SourceMgr.getFileManager().getOptionalFileRef(FilePath);
269 const FileID ID = SourceMgr.getOrCreateFileID(*File, SrcMgr::C_User);
270 return SourceMgr.getLocForStartOfFile(ID).getLocWithOffset(Offset);
273 void reportFix(
const DiagnosticBuilder &Diag,
274 const llvm::StringMap<Replacements> &
Fix) {
275 for (
const auto &FileAndReplacements :
Fix) {
276 for (
const auto &Repl : FileAndReplacements.second) {
277 if (!Repl.isApplicable())
280 FBR.FilePath = Repl.getFilePath().str();
281 FBR.FileOffset = Repl.getOffset();
282 FBR.Length = Repl.getLength();
284 Diag << FixItHint::CreateReplacement(getRange(FBR),
285 Repl.getReplacementText());
290 void reportNote(
const tooling::DiagnosticMessage &Message) {
291 const SourceLocation Loc =
292 getLocation(Message.FilePath, Message.FileOffset);
294 Diags.Report(Loc, Diags.getCustomDiagID(DiagnosticsEngine::Note,
"%0"))
296 for (
const FileByteRange &FBR : Message.Ranges)
297 Diag << getRange(FBR);
298 reportFix(Diag, Message.Fix);
301 CharSourceRange getRange(
const FileByteRange &Range) {
302 SmallString<128> AbsoluteFilePath{Range.FilePath};
303 Files.makeAbsolutePath(AbsoluteFilePath);
304 const SourceLocation BeginLoc =
305 getLocation(AbsoluteFilePath, Range.FileOffset);
306 const SourceLocation EndLoc = BeginLoc.getLocWithOffset(Range.Length);
310 return CharSourceRange::getCharRange(BeginLoc, EndLoc);
313 struct ReplacementsWithBuildDir {
315 Replacements Replaces;
319 LangOptions LangOpts;
320 DiagnosticOptions DiagOpts;
321 DiagnosticConsumer *DiagPrinter;
322 DiagnosticsEngine Diags;
323 SourceManager SourceMgr;
324 llvm::StringMap<ReplacementsWithBuildDir> FileReplacements;
325 ClangTidyContext &Context;
327 unsigned TotalFixes = 0U;
328 unsigned AppliedFixes = 0U;
329 unsigned WarningsAsErrors = 0U;
332class ClangTidyASTConsumer :
public MultiplexConsumer {
334 ClangTidyASTConsumer(std::vector<std::unique_ptr<ASTConsumer>> Consumers,
335 std::unique_ptr<ClangTidyProfiling> Profiling,
336 std::unique_ptr<ast_matchers::MatchFinder> Finder,
337 std::vector<std::unique_ptr<ClangTidyCheck>> Checks)
338 : MultiplexConsumer(std::move(Consumers)),
339 Profiling(std::move(Profiling)), Finder(std::move(Finder)),
340 Checks(std::move(Checks)) {}
345 std::unique_ptr<ClangTidyProfiling> Profiling;
346 std::unique_ptr<ast_matchers::MatchFinder> Finder;
347 std::vector<std::unique_ptr<ClangTidyCheck>> Checks;
348 void anchor()
override {}
355 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS)
356 : Context(Context), OverlayFS(std::
move(OverlayFS)),
358#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
362 for (
const ClangTidyModuleRegistry::entry E :
363 ClangTidyModuleRegistry::entries()) {
364 std::unique_ptr<ClangTidyModule> Module = E.instantiate();
365 Module->addCheckFactories(*CheckFactories);
369#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
371 AnalyzerOptions &AnalyzerOptions) {
373 StringRef OptName(Opt.getKey());
374 if (!OptName.consume_front(AnalyzerCheckNamePrefix))
377 AnalyzerOptions.Config[OptName] = Opt.getValue().Value;
381using CheckersList = std::vector<std::pair<std::string, bool>>;
383static CheckersList getAnalyzerCheckersAndPackages(ClangTidyContext &Context,
384 bool IncludeExperimental) {
387 const auto &RegisteredCheckers =
388 AnalyzerOptions::getRegisteredCheckers(IncludeExperimental);
389 const bool AnalyzerChecksEnabled =
390 llvm::any_of(RegisteredCheckers, [&](StringRef CheckName) ->
bool {
391 return Context.isCheckEnabled(
392 (AnalyzerCheckNamePrefix + CheckName).str());
395 if (!AnalyzerChecksEnabled)
403 for (
const StringRef CheckName : RegisteredCheckers) {
404 const std::string ClangTidyCheckName(
405 (AnalyzerCheckNamePrefix + CheckName).str());
407 if (CheckName.starts_with(
"core") ||
408 Context.isCheckEnabled(ClangTidyCheckName)) {
409 List.emplace_back(std::string(CheckName),
true);
416std::unique_ptr<ASTConsumer>
421 SourceManager *SM = &Compiler.getSourceManager();
422 Context.setSourceManager(SM);
423 Context.setCurrentFile(File);
424 Context.setASTContext(&Compiler.getASTContext());
426 auto WorkingDir = Compiler.getSourceManager()
428 .getVirtualFileSystem()
429 .getCurrentWorkingDirectory();
431 Context.setCurrentBuildDirectory(WorkingDir.get());
432#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
436 std::vector<std::unique_ptr<ClangTidyCheck>>
Checks =
437 CheckFactories->createChecksForLanguage(&Context);
439 ast_matchers::MatchFinder::MatchFinderOptions FinderOptions;
442 FinderOptions.SkipDeclsInModules =
true;
444 std::unique_ptr<ClangTidyProfiling> Profiling;
445 if (Context.getEnableProfiling()) {
447 std::make_unique<ClangTidyProfiling>(Context.getProfileStorageParams());
448 FinderOptions.CheckProfiling.emplace(Profiling->Records);
452 if (!Context.getOptions().SystemHeaders.value_or(
false))
453 FinderOptions.IgnoreSystemHeaders =
true;
456 std::make_unique<ast_matchers::MatchFinder>(std::move(FinderOptions));
458 Preprocessor *PP = &Compiler.getPreprocessor();
459 Preprocessor *ModuleExpanderPP = PP;
461 if (Context.canEnableModuleHeadersParsing() &&
462 Context.getLangOpts().Modules && OverlayFS !=
nullptr) {
463 auto ModuleExpander = std::make_unique<ExpandModularHeadersPPCallbacks>(
464 &Compiler, *OverlayFS);
465 ModuleExpanderPP = ModuleExpander->getPreprocessor();
466 PP->addPPCallbacks(std::move(ModuleExpander));
469 for (
auto &Check :
Checks) {
470 Check->registerMatchers(&*Finder);
471 Check->registerPPCallbacks(*SM, PP, ModuleExpanderPP);
474 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
476 Consumers.push_back(Finder->newASTConsumer());
478#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
479 AnalyzerOptions &AnalyzerOptions = Compiler.getAnalyzerOpts();
480 AnalyzerOptions.CheckersAndPackages = getAnalyzerCheckersAndPackages(
481 Context, Context.canEnableAnalyzerAlphaCheckers());
482 if (!AnalyzerOptions.CheckersAndPackages.empty()) {
483 setStaticAnalyzerCheckerOpts(Context.getOptions(), AnalyzerOptions);
484 AnalyzerOptions.AnalysisDiagOpt = PD_NONE;
485 std::unique_ptr<ento::AnalysisASTConsumer> AnalysisConsumer =
486 ento::CreateAnalysisConsumer(Compiler);
487 AnalysisConsumer->AddDiagnosticConsumer(
488 std::make_unique<AnalyzerDiagnosticConsumer>(Context));
489 Consumers.push_back(std::move(AnalysisConsumer));
492 return std::make_unique<ClangTidyASTConsumer>(
493 std::move(Consumers), std::move(Profiling), std::move(Finder),
498 std::vector<std::string> CheckNames;
499 for (
const auto &CheckFactory : *CheckFactories)
500 if (Context.isCheckEnabled(CheckFactory.getKey()))
501 CheckNames.emplace_back(CheckFactory.getKey());
503#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
504 for (
const auto &AnalyzerCheck : getAnalyzerCheckersAndPackages(
505 Context, Context.canEnableAnalyzerAlphaCheckers()))
506 CheckNames.emplace_back(
507 (AnalyzerCheckNamePrefix + AnalyzerCheck.first).str());
510 llvm::sort(CheckNames);
516 const std::vector<std::unique_ptr<ClangTidyCheck>>
Checks =
517 CheckFactories->createChecks(&Context);
518 for (
const auto &Check :
Checks)
519 Check->storeOptions(Options);
535 const std::vector<std::string> &EnabledChecks) {
537 for (
const auto &[OptionName, Value] : Options.
CheckOptions) {
538 const size_t CheckNameEndPos = OptionName.find(
'.');
539 if (CheckNameEndPos == StringRef::npos)
541 const StringRef CheckName = OptionName.substr(0, CheckNameEndPos);
542 if (llvm::binary_search(EnabledChecks, CheckName))
543 FilteredOptions[OptionName] = Value;
557 auto DiagOpts = std::make_unique<DiagnosticOptions>();
558 DiagnosticsEngine DE(llvm::makeIntrusiveRefCnt<DiagnosticIDs>(), *DiagOpts,
559 &DiagConsumer,
false);
565std::vector<ClangTidyError>
567 ArrayRef<std::string> InputFiles,
568 llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
571 ClangTool Tool(Compilations, InputFiles,
572 std::make_shared<PCHContainerOperations>(), BaseFS);
575 const ArgumentsAdjuster PerFileExtraArgumentsInserter =
576 [&Context](
const CommandLineArguments &Args, StringRef Filename) {
578 CommandLineArguments AdjustedArgs = Args;
580 auto I = AdjustedArgs.begin();
581 if (I != AdjustedArgs.end() && !StringRef(*I).starts_with(
'-'))
587 AdjustedArgs.insert(AdjustedArgs.end(), Opts.
ExtraArgs->begin(),
593 const ArgumentsAdjuster PerFileArgumentRemover =
594 [&Context](
const CommandLineArguments &Args, StringRef Filename) {
596 CommandLineArguments AdjustedArgs = Args;
599 for (
const StringRef ArgToRemove : *Opts.
RemovedArgs) {
600 AdjustedArgs.erase(std::remove(AdjustedArgs.begin(),
601 AdjustedArgs.end(), ArgToRemove),
609 Tool.appendArgumentsAdjuster(PerFileArgumentRemover);
610 Tool.appendArgumentsAdjuster(PerFileExtraArgumentsInserter);
611 Tool.appendArgumentsAdjuster(getStripPluginsAdjuster());
616 auto DiagOpts = std::make_unique<DiagnosticOptions>();
617 DiagnosticsEngine DE(DiagnosticIDs::create(), *DiagOpts, &DiagConsumer,
620 Tool.setDiagnosticConsumer(&DiagConsumer);
625 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
627 : ConsumerFactory(Context, std::move(BaseFS)),
Quiet(
Quiet) {}
628 std::unique_ptr<FrontendAction> create()
override {
629 return std::make_unique<Action>(&ConsumerFactory);
632 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
634 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
637 Invocation->getPreprocessorOpts().SetUpStaticAnalyzer =
true;
639 Invocation->getDiagnosticOpts().ShowCarets =
false;
640 return FrontendActionFactory::runInvocation(
641 Invocation, Files, PCHContainerOps, DiagConsumer);
645 class Action :
public ASTFrontendAction {
652 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
653 StringRef File)
override {
662 ActionFactory Factory(Context, std::move(BaseFS),
Quiet);
664 return DiagConsumer.
take();
669 unsigned &WarningsAsErrorsCount,
670 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
671 ErrorReporter Reporter(Context,
Fix, std::move(BaseFS));
672 llvm::vfs::FileSystem &FileSystem =
673 Reporter.getSourceManager().getFileManager().getVirtualFileSystem();
674 auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();
675 if (!InitialWorkingDir)
676 llvm::report_fatal_error(
"Cannot get current working path.");
679 if (!Error.BuildDirectory.empty()) {
684 FileSystem.setCurrentWorkingDirectory(Error.BuildDirectory);
686 Reporter.reportDiagnostic(Error);
688 FileSystem.setCurrentWorkingDirectory(InitialWorkingDir.get());
691 WarningsAsErrorsCount += Reporter.getWarningsAsErrorsCount();
695 const std::vector<ClangTidyError> &Errors,
697 TranslationUnitDiagnostics TUD;
698 TUD.MainSourceFile = std::string(MainFilePath);
699 for (
const auto &Error : Errors) {
700 tooling::Diagnostic Diag = Error;
701 if (Error.IsWarningAsError)
702 Diag.DiagLevel = tooling::Diagnostic::Error;
703 TUD.Diagnostics.insert(TUD.Diagnostics.end(), Diag);
706 yaml::Output YAML(OS);
719#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
723 for (
const ClangTidyModuleRegistry::entry &Module :
724 ClangTidyModuleRegistry::entries()) {
725 Module.instantiate()->addCheckFactories(Factories);
728 for (
const auto &Factory : Factories)
729 Result.
Checks.insert(Factory.getKey());
731#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
732 SmallString<64> Buffer(AnalyzerCheckNamePrefix);
733 const size_t DefSize = Buffer.size();
734 for (
const auto &AnalyzerCheck : AnalyzerOptions::getRegisteredCheckers(
736 Buffer.truncate(DefSize);
737 Buffer.append(AnalyzerCheck);
738 Result.
Checks.insert(Buffer);
741 static constexpr StringRef OptionNames[] = {
742#define GET_CHECKER_OPTIONS
743#define CHECKER_OPTION(TYPE, CHECKER, OPTION_NAME, DESCRIPTION, DEFAULT, \
745 ANALYZER_CHECK_NAME_PREFIX CHECKER ":" OPTION_NAME,
747#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
749#undef GET_CHECKER_OPTIONS
752 Result.
Options.insert_range(OptionNames);
756 for (
const auto &Factory : Factories)
757 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.