23#include "clang-tidy-config.h"
24#include "clang/AST/ASTConsumer.h"
25#include "clang/ASTMatchers/ASTMatchFinder.h"
26#include "clang/Format/Format.h"
27#include "clang/Frontend/ASTConsumers.h"
28#include "clang/Frontend/CompilerInstance.h"
29#include "clang/Frontend/FrontendDiagnostic.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"
42#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
43#include "clang/Analysis/PathDiagnostic.h"
44#include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
48using namespace clang::driver;
56#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
59 ClangTidyCheckFactories &Factories) =
nullptr;
64#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
65#define ANALYZER_CHECK_NAME_PREFIX "clang-analyzer-"
66static constexpr llvm::StringLiteral AnalyzerCheckNamePrefix =
67 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);
116 SourceManager &getSourceManager() {
return SourceMgr; }
118 void reportDiagnostic(
const ClangTidyError &Error) {
119 const tooling::DiagnosticMessage &Message =
Error.Message;
120 const SourceLocation Loc =
121 getLocation(Message.FilePath, Message.FileOffset);
124 SmallVector<std::pair<SourceLocation, bool>, 4> FixLocations;
126 auto Level =
static_cast<DiagnosticsEngine::Level
>(
Error.DiagLevel);
127 std::string Name =
Error.DiagnosticName;
128 if (!
Error.EnabledDiagnosticAliases.empty())
129 Name +=
"," + llvm::join(
Error.EnabledDiagnosticAliases,
",");
130 if (
Error.IsWarningAsError) {
131 Name +=
",-warnings-as-errors";
132 Level = DiagnosticsEngine::Error;
135 auto Diag = Diags.Report(Loc, Diags.getCustomDiagID(Level,
"%0 [%1]"))
136 << Message.Message << Name;
137 for (
const FileByteRange &FBR :
Error.Message.Ranges)
138 Diag << getRange(FBR);
140 const llvm::StringMap<Replacements> *ChosenFix =
nullptr;
143 for (
const auto &FileAndReplacements : *ChosenFix) {
144 for (
const auto &Repl : FileAndReplacements.second) {
146 bool CanBeApplied =
false;
147 if (!Repl.isApplicable())
149 SourceLocation FixLoc;
150 SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
151 Files.makeAbsolutePath(FixAbsoluteFilePath);
152 tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
153 Repl.getLength(), Repl.getReplacementText());
154 auto &Entry = FileReplacements[R.getFilePath()];
155 Replacements &Replacements = Entry.Replaces;
156 llvm::Error Err = Replacements.add(R);
159 llvm::errs() <<
"Trying to resolve conflict: "
160 << llvm::toString(std::move(Err)) <<
"\n";
161 const unsigned NewOffset =
162 Replacements.getShiftedCodePosition(R.getOffset());
163 const unsigned NewLength = Replacements.getShiftedCodePosition(
164 R.getOffset() + R.getLength()) -
166 if (NewLength == R.getLength()) {
167 R = Replacement(R.getFilePath(), NewOffset, NewLength,
168 R.getReplacementText());
169 Replacements = Replacements.merge(tooling::Replacements(R));
174 <<
"Can't resolve conflict, skipping the replacement.\n";
180 FixLoc = getLocation(FixAbsoluteFilePath, Repl.getOffset());
181 FixLocations.push_back(std::make_pair(FixLoc, CanBeApplied));
182 Entry.BuildDir =
Error.BuildDirectory;
186 reportFix(Diag,
Error.Message.Fix);
188 for (
auto Fix : FixLocations) {
189 Diags.Report(
Fix.first,
Fix.second ? diag::note_fixit_applied
190 : diag::note_fixit_failed);
192 for (
const auto &Note :
Error.Notes)
197 if (TotalFixes > 0) {
198 auto &VFS = Files.getVirtualFileSystem();
199 auto OriginalCWD = VFS.getCurrentWorkingDirectory();
200 bool AnyNotWritten =
false;
202 for (
const auto &FileAndReplacements : FileReplacements) {
203 Rewriter Rewrite(SourceMgr, LangOpts);
204 const StringRef
File = FileAndReplacements.first();
205 VFS.setCurrentWorkingDirectory(FileAndReplacements.second.BuildDir);
206 llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
207 SourceMgr.getFileManager().getBufferForFile(File);
209 llvm::errs() <<
"Can't get buffer for file " <<
File <<
": "
210 << Buffer.getError().message() <<
"\n";
214 const StringRef Code = Buffer.get()->getBuffer();
215 auto Style = format::getStyle(
216 *Context.getOptionsForFile(File).FormatStyle, File,
"none");
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";
240 AnyNotWritten |= Rewrite.overwriteChangedFiles();
244 llvm::errs() <<
"clang-tidy failed to apply suggested fixes.\n";
246 llvm::errs() <<
"clang-tidy applied " << AppliedFixes <<
" of "
247 << TotalFixes <<
" suggested fixes.\n";
251 VFS.setCurrentWorkingDirectory(*OriginalCWD);
255 unsigned getWarningsAsErrorsCount()
const {
return WarningsAsErrors; }
258 SourceLocation getLocation(StringRef FilePath,
unsigned Offset) {
259 if (FilePath.empty())
262 auto File = SourceMgr.getFileManager().getOptionalFileRef(FilePath);
266 const FileID ID = SourceMgr.getOrCreateFileID(*File, SrcMgr::C_User);
267 return SourceMgr.getLocForStartOfFile(ID).getLocWithOffset(Offset);
270 void reportFix(
const DiagnosticBuilder &Diag,
271 const llvm::StringMap<Replacements> &
Fix) {
272 for (
const auto &FileAndReplacements :
Fix) {
273 for (
const auto &Repl : FileAndReplacements.second) {
274 if (!Repl.isApplicable())
277 FBR.FilePath = Repl.getFilePath().str();
278 FBR.FileOffset = Repl.getOffset();
279 FBR.Length = Repl.getLength();
281 Diag << FixItHint::CreateReplacement(getRange(FBR),
282 Repl.getReplacementText());
287 void reportNote(
const tooling::DiagnosticMessage &Message) {
288 const SourceLocation Loc =
289 getLocation(Message.FilePath, Message.FileOffset);
291 Diags.Report(Loc, Diags.getCustomDiagID(DiagnosticsEngine::Note,
"%0"))
293 for (
const FileByteRange &FBR : Message.Ranges)
294 Diag << getRange(FBR);
295 reportFix(Diag, Message.Fix);
298 CharSourceRange getRange(
const FileByteRange &Range) {
299 SmallString<128> AbsoluteFilePath{Range.FilePath};
300 Files.makeAbsolutePath(AbsoluteFilePath);
301 const SourceLocation BeginLoc =
302 getLocation(AbsoluteFilePath, Range.FileOffset);
303 const SourceLocation EndLoc = BeginLoc.getLocWithOffset(Range.Length);
307 return CharSourceRange::getCharRange(BeginLoc, EndLoc);
310 struct ReplacementsWithBuildDir {
312 Replacements Replaces;
316 LangOptions LangOpts;
317 DiagnosticOptions DiagOpts;
318 DiagnosticConsumer *DiagPrinter;
319 DiagnosticsEngine Diags;
320 SourceManager SourceMgr;
321 llvm::StringMap<ReplacementsWithBuildDir> FileReplacements;
322 ClangTidyContext &Context;
324 unsigned TotalFixes = 0U;
325 unsigned AppliedFixes = 0U;
326 unsigned WarningsAsErrors = 0U;
329class ClangTidyASTConsumer :
public MultiplexConsumer {
331 ClangTidyASTConsumer(std::vector<std::unique_ptr<ASTConsumer>> Consumers,
332 std::unique_ptr<ClangTidyProfiling> Profiling,
333 std::unique_ptr<ast_matchers::MatchFinder> Finder,
334 std::vector<std::unique_ptr<ClangTidyCheck>> Checks)
335 : MultiplexConsumer(std::move(Consumers)),
336 Profiling(std::move(Profiling)), Finder(std::move(Finder)),
337 Checks(std::move(Checks)) {}
342 std::unique_ptr<ClangTidyProfiling> Profiling;
343 std::unique_ptr<ast_matchers::MatchFinder> Finder;
344 std::vector<std::unique_ptr<ClangTidyCheck>> Checks;
345 void anchor()
override {};
352 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS)
353 : Context(Context), OverlayFS(std::
move(OverlayFS)),
355#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
359 for (
const ClangTidyModuleRegistry::entry E :
360 ClangTidyModuleRegistry::entries()) {
361 std::unique_ptr<ClangTidyModule> Module = E.instantiate();
362 Module->addCheckFactories(*CheckFactories);
366#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
369 clang::AnalyzerOptions &AnalyzerOptions) {
371 StringRef OptName(Opt.getKey());
372 if (!OptName.consume_front(AnalyzerCheckNamePrefix))
375 AnalyzerOptions.Config[OptName] = Opt.getValue().Value;
379using CheckersList = std::vector<std::pair<std::string, bool>>;
381static CheckersList getAnalyzerCheckersAndPackages(ClangTidyContext &Context,
382 bool IncludeExperimental) {
385 const auto &RegisteredCheckers =
386 AnalyzerOptions::getRegisteredCheckers(IncludeExperimental);
387 const bool AnalyzerChecksEnabled =
388 llvm::any_of(RegisteredCheckers, [&](StringRef CheckName) ->
bool {
389 return Context.isCheckEnabled(
390 (AnalyzerCheckNamePrefix + CheckName).str());
393 if (!AnalyzerChecksEnabled)
401 for (
const StringRef CheckName : RegisteredCheckers) {
402 const std::string ClangTidyCheckName(
403 (AnalyzerCheckNamePrefix + CheckName).str());
405 if (CheckName.starts_with(
"core") ||
406 Context.isCheckEnabled(ClangTidyCheckName)) {
407 List.emplace_back(std::string(CheckName),
true);
414std::unique_ptr<clang::ASTConsumer>
416 clang::CompilerInstance &Compiler, StringRef File) {
419 SourceManager *SM = &Compiler.getSourceManager();
420 Context.setSourceManager(SM);
421 Context.setCurrentFile(File);
422 Context.setASTContext(&Compiler.getASTContext());
424 auto WorkingDir = Compiler.getSourceManager()
426 .getVirtualFileSystem()
427 .getCurrentWorkingDirectory();
429 Context.setCurrentBuildDirectory(WorkingDir.get());
430#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
434 std::vector<std::unique_ptr<ClangTidyCheck>>
Checks =
435 CheckFactories->createChecksForLanguage(&Context);
437 ast_matchers::MatchFinder::MatchFinderOptions FinderOptions;
439 std::unique_ptr<ClangTidyProfiling> Profiling;
440 if (Context.getEnableProfiling()) {
442 std::make_unique<ClangTidyProfiling>(Context.getProfileStorageParams());
443 FinderOptions.CheckProfiling.emplace(Profiling->Records);
447 if (!Context.getOptions().SystemHeaders.value_or(
false))
448 FinderOptions.IgnoreSystemHeaders =
true;
450 std::unique_ptr<ast_matchers::MatchFinder> Finder(
451 new ast_matchers::MatchFinder(std::move(FinderOptions)));
453 Preprocessor *PP = &Compiler.getPreprocessor();
454 Preprocessor *ModuleExpanderPP = PP;
456 if (Context.canEnableModuleHeadersParsing() &&
457 Context.getLangOpts().Modules && OverlayFS !=
nullptr) {
458 auto ModuleExpander = std::make_unique<ExpandModularHeadersPPCallbacks>(
459 &Compiler, *OverlayFS);
460 ModuleExpanderPP = ModuleExpander->getPreprocessor();
461 PP->addPPCallbacks(std::move(ModuleExpander));
464 for (
auto &Check :
Checks) {
465 Check->registerMatchers(&*Finder);
466 Check->registerPPCallbacks(*SM, PP, ModuleExpanderPP);
469 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
471 Consumers.push_back(Finder->newASTConsumer());
473#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
474 AnalyzerOptions &AnalyzerOptions = Compiler.getAnalyzerOpts();
475 AnalyzerOptions.CheckersAndPackages = getAnalyzerCheckersAndPackages(
476 Context, Context.canEnableAnalyzerAlphaCheckers());
477 if (!AnalyzerOptions.CheckersAndPackages.empty()) {
478 setStaticAnalyzerCheckerOpts(Context.getOptions(), AnalyzerOptions);
479 AnalyzerOptions.AnalysisDiagOpt = PD_NONE;
480 std::unique_ptr<ento::AnalysisASTConsumer> AnalysisConsumer =
481 ento::CreateAnalysisConsumer(Compiler);
482 AnalysisConsumer->AddDiagnosticConsumer(
483 std::make_unique<AnalyzerDiagnosticConsumer>(Context));
484 Consumers.push_back(std::move(AnalysisConsumer));
487 return std::make_unique<ClangTidyASTConsumer>(
488 std::move(Consumers), std::move(Profiling), std::move(Finder),
493 std::vector<std::string> CheckNames;
494 for (
const auto &CheckFactory : *CheckFactories) {
495 if (Context.isCheckEnabled(CheckFactory.getKey()))
496 CheckNames.emplace_back(CheckFactory.getKey());
499#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
500 for (
const auto &AnalyzerCheck : getAnalyzerCheckersAndPackages(
501 Context, Context.canEnableAnalyzerAlphaCheckers()))
502 CheckNames.emplace_back(
503 (AnalyzerCheckNamePrefix + AnalyzerCheck.first).str());
506 llvm::sort(CheckNames);
512 const std::vector<std::unique_ptr<ClangTidyCheck>>
Checks =
513 CheckFactories->createChecks(&Context);
514 for (
const auto &Check :
Checks)
515 Check->storeOptions(Options);
531 const std::vector<std::string> &EnabledChecks) {
533 for (
const auto &[OptionName, Value] : Options.
CheckOptions) {
534 const size_t CheckNameEndPos = OptionName.find(
'.');
535 if (CheckNameEndPos == StringRef::npos)
537 const StringRef CheckName = OptionName.substr(0, CheckNameEndPos);
538 if (llvm::binary_search(EnabledChecks, CheckName))
539 FilteredOptions[OptionName] = Value;
553 auto DiagOpts = std::make_unique<DiagnosticOptions>();
554 DiagnosticsEngine DE(llvm::makeIntrusiveRefCnt<DiagnosticIDs>(), *DiagOpts,
555 &DiagConsumer,
false);
561std::vector<ClangTidyError>
563 const CompilationDatabase &Compilations,
564 ArrayRef<std::string> InputFiles,
565 llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
568 ClangTool Tool(Compilations, InputFiles,
569 std::make_shared<PCHContainerOperations>(), BaseFS);
572 const ArgumentsAdjuster PerFileExtraArgumentsInserter =
573 [&Context](
const CommandLineArguments &Args, StringRef Filename) {
575 CommandLineArguments AdjustedArgs = Args;
577 auto I = AdjustedArgs.begin();
578 if (I != AdjustedArgs.end() && !StringRef(*I).starts_with(
"-"))
584 AdjustedArgs.insert(AdjustedArgs.end(), Opts.
ExtraArgs->begin(),
589 Tool.appendArgumentsAdjuster(PerFileExtraArgumentsInserter);
590 Tool.appendArgumentsAdjuster(getStripPluginsAdjuster());
595 auto DiagOpts = std::make_unique<DiagnosticOptions>();
596 DiagnosticsEngine DE(DiagnosticIDs::create(), *DiagOpts, &DiagConsumer,
599 Tool.setDiagnosticConsumer(&DiagConsumer);
604 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
606 : ConsumerFactory(Context, std::move(BaseFS)),
Quiet(
Quiet) {}
607 std::unique_ptr<FrontendAction> create()
override {
608 return std::make_unique<Action>(&ConsumerFactory);
611 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
613 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
616 Invocation->getPreprocessorOpts().SetUpStaticAnalyzer =
true;
618 Invocation->getDiagnosticOpts().ShowCarets =
false;
619 return FrontendActionFactory::runInvocation(
620 Invocation, Files, PCHContainerOps, DiagConsumer);
624 class Action :
public ASTFrontendAction {
627 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
628 StringRef File)
override {
640 ActionFactory Factory(Context, std::move(BaseFS),
Quiet);
642 return DiagConsumer.
take();
647 unsigned &WarningsAsErrorsCount,
648 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
649 ErrorReporter Reporter(Context,
Fix, std::move(BaseFS));
650 llvm::vfs::FileSystem &FileSystem =
651 Reporter.getSourceManager().getFileManager().getVirtualFileSystem();
652 auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();
653 if (!InitialWorkingDir)
654 llvm::report_fatal_error(
"Cannot get current working path.");
657 if (!Error.BuildDirectory.empty()) {
662 FileSystem.setCurrentWorkingDirectory(Error.BuildDirectory);
664 Reporter.reportDiagnostic(Error);
666 FileSystem.setCurrentWorkingDirectory(InitialWorkingDir.get());
669 WarningsAsErrorsCount += Reporter.getWarningsAsErrorsCount();
673 const std::vector<ClangTidyError> &Errors,
675 TranslationUnitDiagnostics TUD;
676 TUD.MainSourceFile = std::string(MainFilePath);
677 for (
const auto &Error : Errors) {
678 tooling::Diagnostic Diag = Error;
679 if (Error.IsWarningAsError)
680 Diag.DiagLevel = tooling::Diagnostic::Error;
681 TUD.Diagnostics.insert(TUD.Diagnostics.end(), Diag);
684 yaml::Output YAML(OS);
697#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
701 for (
const ClangTidyModuleRegistry::entry &Module :
702 ClangTidyModuleRegistry::entries()) {
703 Module.instantiate()->addCheckFactories(Factories);
706 for (
const auto &Factory : Factories)
707 Result.
Checks.insert(Factory.getKey());
709#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
710 SmallString<64> Buffer(AnalyzerCheckNamePrefix);
711 const size_t DefSize = Buffer.size();
712 for (
const auto &AnalyzerCheck : AnalyzerOptions::getRegisteredCheckers(
714 Buffer.truncate(DefSize);
715 Buffer.append(AnalyzerCheck);
716 Result.
Checks.insert(Buffer);
719 static constexpr llvm::StringLiteral OptionNames[] = {
720#define GET_CHECKER_OPTIONS
721#define CHECKER_OPTION(TYPE, CHECKER, OPTION_NAME, DESCRIPTION, DEFAULT, \
723 ANALYZER_CHECK_NAME_PREFIX CHECKER ":" OPTION_NAME,
725#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
727#undef GET_CHECKER_OPTIONS
730 Result.
Options.insert_range(OptionNames);
734 for (
const auto &Factory : Factories) {
735 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< clang::ASTConsumer > createASTConsumer(clang::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 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...
void exportReplacements(const llvm::StringRef MainFilePath, const std::vector< ClangTidyError > &Errors, raw_ostream &OS)
std::vector< ClangTidyError > runClangTidy(clang::tidy::ClangTidyContext &Context, const CompilationDatabase &Compilations, ArrayRef< std::string > InputFiles, llvm::IntrusiveRefCntPtr< llvm::vfs::OverlayFileSystem > BaseFS, bool ApplyAnyFix, bool EnableCheckProfile, llvm::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 > 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.