clang-tools 24.0.0git
ClangTidy.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file This file implements a clang-tidy tool.
10///
11/// This tool uses the Clang Tooling infrastructure, see
12/// https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
13/// for details on setting it up with LLVM source tree.
14///
15//===----------------------------------------------------------------------===//
16
17#include "ClangTidy.h"
18#include "ClangTidyCheck.h"
20#include "ClangTidyModule.h"
21#include "ClangTidyProfiling.h"
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" // IWYU pragma: keep
37#include "clang/Tooling/Refactoring.h"
38#include "clang/Tooling/Tooling.h"
39#include "llvm/Support/Process.h"
40#include <memory>
41#include <utility>
42
43#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
44#include "clang/Analysis/PathDiagnostic.h"
45#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
46#include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
47#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
48
49using namespace clang::ast_matchers;
50using namespace clang::driver;
51using namespace clang::tooling;
52using namespace llvm;
53
54LLVM_INSTANTIATE_REGISTRY(clang::tidy::ClangTidyModuleRegistry)
55
56namespace clang::tidy {
57
58#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
59namespace custom {
60void (*RegisterCustomChecks)(const ClangTidyOptions &O,
61 ClangTidyCheckFactories &Factories) = nullptr;
62} // namespace custom
63#endif
64
65namespace {
66#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
67#define ANALYZER_CHECK_NAME_PREFIX "clang-analyzer-"
68static constexpr StringRef AnalyzerCheckNamePrefix = ANALYZER_CHECK_NAME_PREFIX;
69
70class AnalyzerDiagnosticConsumer : public ento::PathDiagnosticConsumer {
71public:
72 AnalyzerDiagnosticConsumer(ClangTidyContext &Context) : Context(Context) {}
73
74 void FlushDiagnosticsImpl(std::vector<const ento::PathDiagnostic *> &Diags,
75 FilesMade *FilesMade) override {
76 for (const ento::PathDiagnostic *PD : Diags) {
77 SmallString<64> CheckName(AnalyzerCheckNamePrefix);
78 CheckName += PD->getCheckerName();
79 Context.diag(CheckName, PD->getLocation().asLocation(),
80 PD->getShortDescription())
81 << PD->path.back()->getRanges();
82
83 for (const auto &DiagPiece :
84 PD->path.flatten(/*ShouldFlattenMacros=*/true)) {
85 Context.diag(CheckName, DiagPiece->getLocation().asLocation(),
86 DiagPiece->getString(), DiagnosticIDs::Note)
87 << DiagPiece->getRanges();
88 }
89 }
90 }
91
92 StringRef getName() const override { return "ClangTidyDiags"; }
93 bool supportsLogicalOpControlFlow() const override { return true; }
94 bool supportsCrossFileDiagnostics() const override { return true; }
95
96private:
97 ClangTidyContext &Context;
98};
99#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
100
101class ErrorReporter {
102public:
103 ErrorReporter(ClangTidyContext &Context, FixBehaviour ApplyFixes,
104 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS)
105 : Files(FileSystemOptions(), std::move(BaseFS)),
106 DiagPrinter(new TextDiagnosticPrinter(llvm::outs(), DiagOpts)),
107 Diags(DiagnosticIDs::create(), DiagOpts, DiagPrinter),
108 SourceMgr(Diags, Files), Context(Context), ApplyFixes(ApplyFixes) {
109 DiagOpts.setShowColors(Context.getOptions().UseColor.value_or(
110 llvm::sys::Process::StandardOutHasColors())
111 ? ShowColorsKind::On
112 : ShowColorsKind::Off);
113 DiagPrinter->BeginSourceFile(LangOpts);
114 if (DiagOpts.showColors(llvm::sys::Process::StandardOutHasColors()) &&
115 !llvm::sys::Process::StandardOutIsDisplayed())
116 llvm::sys::Process::UseANSIEscapeCodes(true);
117 }
118
119 SourceManager &getSourceManager() { return SourceMgr; }
120
121 void reportDiagnostic(const ClangTidyError &Error) {
122 const tooling::DiagnosticMessage &Message = Error.Message;
123 const SourceLocation Loc =
124 getLocation(Message.FilePath, Message.FileOffset);
125 // Contains a pair for each attempted fix: location and whether the fix was
126 // applied successfully.
127 SmallVector<std::pair<SourceLocation, bool>, 4> FixLocations;
128 {
129 auto Level = static_cast<DiagnosticsEngine::Level>(Error.DiagLevel);
130 std::string Name = Error.DiagnosticName;
131 if (!Error.EnabledDiagnosticAliases.empty())
132 Name += "," + llvm::join(Error.EnabledDiagnosticAliases, ",");
133 if (Error.IsWarningAsError) {
134 Name += ",-warnings-as-errors";
135 Level = DiagnosticsEngine::Error;
136 WarningsAsErrors++;
137 }
138 const auto Diag =
139 Diags.Report(Loc, Diags.getCustomDiagID(Level, "%0 [%1]"))
140 << Message.Message << Name;
141 for (const FileByteRange &FBR : Error.Message.Ranges)
142 Diag << getRange(FBR);
143 // FIXME: explore options to support interactive fix selection.
144 const llvm::StringMap<Replacements> *ChosenFix = nullptr;
145 if (ApplyFixes != FB_NoFix &&
146 (ChosenFix = getFixIt(Error, ApplyFixes == FB_FixNotes))) {
147 for (const auto &FileAndReplacements : *ChosenFix) {
148 for (const auto &Repl : FileAndReplacements.second) {
149 ++TotalFixes;
150 bool CanBeApplied = false;
151 if (!Repl.isApplicable())
152 continue;
153 SourceLocation FixLoc;
154 SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
155 Files.makeAbsolutePath(FixAbsoluteFilePath);
156 tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
157 Repl.getLength(), Repl.getReplacementText());
158 auto &Entry = FileReplacements[R.getFilePath()];
159 Replacements &Replacements = Entry.Replaces;
160 llvm::Error Err = Replacements.add(R);
161 if (Err) {
162 // FIXME: Implement better conflict handling.
163 llvm::errs() << "Trying to resolve conflict: "
164 << llvm::toString(std::move(Err)) << "\n";
165 const unsigned NewOffset =
166 Replacements.getShiftedCodePosition(R.getOffset());
167 const unsigned NewLength = Replacements.getShiftedCodePosition(
168 R.getOffset() + R.getLength()) -
169 NewOffset;
170 if (NewLength == R.getLength()) {
171 R = Replacement(R.getFilePath(), NewOffset, NewLength,
172 R.getReplacementText());
173 Replacements = Replacements.merge(tooling::Replacements(R));
174 CanBeApplied = true;
175 ++AppliedFixes;
176 } else {
177 llvm::errs()
178 << "Can't resolve conflict, skipping the replacement.\n";
179 }
180 } else {
181 CanBeApplied = true;
182 ++AppliedFixes;
183 }
184 FixLoc = getLocation(FixAbsoluteFilePath, Repl.getOffset());
185 FixLocations.emplace_back(FixLoc, CanBeApplied);
186 Entry.BuildDir = Error.BuildDirectory;
187 }
188 }
189 }
190 reportFix(Diag, Error.Message.Fix);
191 }
192 for (const auto &Fix : FixLocations) {
193 Diags.Report(Fix.first, Fix.second ? diag::note_fixit_applied
194 : diag::note_fixit_failed);
195 }
196 for (const auto &Note : Error.Notes)
197 reportNote(Note);
198 }
199
200 void finish() {
201 if (TotalFixes > 0) {
202 auto &VFS = Files.getVirtualFileSystem();
203 auto OriginalCWD = VFS.getCurrentWorkingDirectory();
204 bool AnyNotWritten = false;
205
206 for (const auto &FileAndReplacements : FileReplacements) {
207 Rewriter Rewrite(SourceMgr, LangOpts);
208 const StringRef File = FileAndReplacements.first();
209 VFS.setCurrentWorkingDirectory(FileAndReplacements.second.BuildDir);
210 llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
211 SourceMgr.getFileManager().getBufferForFile(File);
212 if (!Buffer) {
213 llvm::errs() << "Can't get buffer for file " << File << ": "
214 << Buffer.getError().message() << "\n";
215 // FIXME: Maybe don't apply fixes for other files as well.
216 continue;
217 }
218 const StringRef Code = Buffer.get()->getBuffer();
219 auto Style = format::getStyle(
220 Context.getOptionsForFile(File).FormatStyle.value_or("none"), File,
221 "none");
222 if (!Style) {
223 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
224 continue;
225 }
226 llvm::Expected<tooling::Replacements> Replacements =
227 format::cleanupAroundReplacements(
228 Code, FileAndReplacements.second.Replaces, *Style);
229 if (!Replacements) {
230 llvm::errs() << llvm::toString(Replacements.takeError()) << "\n";
231 continue;
232 }
233 if (llvm::Expected<tooling::Replacements> FormattedReplacements =
234 format::formatReplacements(Code, *Replacements, *Style)) {
235 Replacements = std::move(FormattedReplacements);
236 if (!Replacements)
237 llvm_unreachable("!Replacements");
238 } else {
239 llvm::errs() << llvm::toString(FormattedReplacements.takeError())
240 << ". Skipping formatting.\n";
241 }
242 if (!tooling::applyAllReplacements(Replacements.get(), Rewrite))
243 llvm::errs() << "Can't apply replacements for file " << File << "\n";
244 AnyNotWritten |= Rewrite.overwriteChangedFiles();
245 }
246
247 if (AnyNotWritten) {
248 llvm::errs() << "clang-tidy failed to apply suggested fixes.\n";
249 } else {
250 llvm::errs() << "clang-tidy applied " << AppliedFixes << " of "
251 << TotalFixes << " suggested fixes.\n";
252 }
253
254 if (OriginalCWD)
255 VFS.setCurrentWorkingDirectory(*OriginalCWD);
256 }
257 }
258
259 unsigned getWarningsAsErrorsCount() const { return WarningsAsErrors; }
260
261private:
262 SourceLocation getLocation(StringRef FilePath, unsigned Offset) {
263 if (FilePath.empty())
264 return {};
265
266 auto File = SourceMgr.getFileManager().getOptionalFileRef(FilePath);
267 if (!File)
268 return {};
269
270 const FileID ID = SourceMgr.getOrCreateFileID(*File, SrcMgr::C_User);
271 return SourceMgr.getLocForStartOfFile(ID).getLocWithOffset(Offset);
272 }
273
274 void reportFix(const DiagnosticBuilder &Diag,
275 const llvm::StringMap<Replacements> &Fix) {
276 for (const auto &FileAndReplacements : Fix) {
277 for (const auto &Repl : FileAndReplacements.second) {
278 if (!Repl.isApplicable())
279 continue;
280 FileByteRange FBR;
281 FBR.FilePath = Repl.getFilePath().str();
282 FBR.FileOffset = Repl.getOffset();
283 FBR.Length = Repl.getLength();
284
285 Diag << FixItHint::CreateReplacement(getRange(FBR),
286 Repl.getReplacementText());
287 }
288 }
289 }
290
291 void reportNote(const tooling::DiagnosticMessage &Message) {
292 const SourceLocation Loc =
293 getLocation(Message.FilePath, Message.FileOffset);
294 const auto Diag =
295 Diags.Report(Loc, Diags.getCustomDiagID(DiagnosticsEngine::Note, "%0"))
296 << Message.Message;
297 for (const FileByteRange &FBR : Message.Ranges)
298 Diag << getRange(FBR);
299 reportFix(Diag, Message.Fix);
300 }
301
302 CharSourceRange getRange(const FileByteRange &Range) {
303 SmallString<128> AbsoluteFilePath{Range.FilePath};
304 Files.makeAbsolutePath(AbsoluteFilePath);
305 const SourceLocation BeginLoc =
306 getLocation(AbsoluteFilePath, Range.FileOffset);
307 const SourceLocation EndLoc = BeginLoc.getLocWithOffset(Range.Length);
308 // Retrieve the source range for applicable highlights and fixes. Macro
309 // definition on the command line have locations in a virtual buffer and
310 // don't have valid file paths and are therefore not applicable.
311 return CharSourceRange::getCharRange(BeginLoc, EndLoc);
312 }
313
314 struct ReplacementsWithBuildDir {
315 StringRef BuildDir;
316 Replacements Replaces;
317 };
318
319 FileManager Files;
320 LangOptions LangOpts; // FIXME: use langopts from each original file
321 DiagnosticOptions DiagOpts;
322 DiagnosticConsumer *DiagPrinter;
323 DiagnosticsEngine Diags;
324 SourceManager SourceMgr;
325 llvm::StringMap<ReplacementsWithBuildDir> FileReplacements;
326 ClangTidyContext &Context;
327 FixBehaviour ApplyFixes;
328 unsigned TotalFixes = 0U;
329 unsigned AppliedFixes = 0U;
330 unsigned WarningsAsErrors = 0U;
331};
332
333class ClangTidyASTConsumer : public MultiplexConsumer {
334public:
335 ClangTidyASTConsumer(std::vector<std::unique_ptr<ASTConsumer>> Consumers,
336 std::unique_ptr<ClangTidyProfiling> Profiling,
337 std::unique_ptr<ast_matchers::MatchFinder> Finder,
338 std::vector<std::unique_ptr<ClangTidyCheck>> Checks)
339 : MultiplexConsumer(std::move(Consumers)),
340 Profiling(std::move(Profiling)), Finder(std::move(Finder)),
341 Checks(std::move(Checks)) {}
342
343private:
344 // Destructor order matters! Profiling must be destructed last.
345 // Or at least after Finder.
346 std::unique_ptr<ClangTidyProfiling> Profiling;
347 std::unique_ptr<ast_matchers::MatchFinder> Finder;
348 std::vector<std::unique_ptr<ClangTidyCheck>> Checks;
349 void anchor() override {}
350};
351
352} // namespace
353
355 ClangTidyContext &Context,
356 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS)
357 : Context(Context), OverlayFS(std::move(OverlayFS)),
358 CheckFactories(new ClangTidyCheckFactories) {
359#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
360 if (Context.canExperimentalCustomChecks() && custom::RegisterCustomChecks)
361 custom::RegisterCustomChecks(Context.getOptions(), *CheckFactories);
362#endif
363 for (const ClangTidyModuleRegistry::entry E :
364 ClangTidyModuleRegistry::entries()) {
365 std::unique_ptr<ClangTidyModule> Module = E.instantiate();
366 Module->addCheckFactories(*CheckFactories);
367 }
368}
369
370#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
371static void setStaticAnalyzerCheckerOpts(const ClangTidyOptions &Opts,
372 AnalyzerOptions &AnalyzerOptions) {
373 for (const auto &Opt : Opts.CheckOptions) {
374 StringRef OptName(Opt.getKey());
375 if (!OptName.consume_front(AnalyzerCheckNamePrefix))
376 continue;
377 // Analyzer options are always local options so we can ignore priority.
378 AnalyzerOptions.Config[OptName] = Opt.getValue().Value;
379 }
380}
381
382using CheckersList = std::vector<std::pair<std::string, bool>>;
383
384static CheckersList getAnalyzerCheckersAndPackages(ClangTidyContext &Context,
385 bool IncludeExperimental) {
386 CheckersList List;
387
388 const auto &RegisteredCheckers =
389 AnalyzerOptions::getRegisteredCheckers(IncludeExperimental);
390 const bool AnalyzerChecksEnabled =
391 llvm::any_of(RegisteredCheckers, [&](StringRef CheckName) -> bool {
392 return Context.isCheckEnabled(
393 (AnalyzerCheckNamePrefix + CheckName).str());
394 });
395
396 if (!AnalyzerChecksEnabled)
397 return List;
398
399 // List all static analyzer checkers that our filter enables.
400 //
401 // Always add all core checkers if any other static analyzer check is enabled.
402 // This is currently necessary, as other path sensitive checks rely on the
403 // core checkers.
404 for (const StringRef CheckName : RegisteredCheckers) {
405 const std::string ClangTidyCheckName(
406 (AnalyzerCheckNamePrefix + CheckName).str());
407
408 if (CheckName.starts_with("core") ||
409 Context.isCheckEnabled(ClangTidyCheckName)) {
410 List.emplace_back(std::string(CheckName), true);
411 }
412 }
413 return List;
414}
415#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
416
417std::unique_ptr<ASTConsumer>
419 StringRef File) {
420 // FIXME: Move this to a separate method, so that CreateASTConsumer doesn't
421 // modify Compiler.
422 SourceManager *SM = &Compiler.getSourceManager();
423 Context.setSourceManager(SM);
424 Context.setCurrentFile(File);
425 Context.setASTContext(&Compiler.getASTContext());
426
427 auto WorkingDir = Compiler.getSourceManager()
428 .getFileManager()
429 .getVirtualFileSystem()
430 .getCurrentWorkingDirectory();
431 if (WorkingDir)
432 Context.setCurrentBuildDirectory(WorkingDir.get());
433#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
434 if (Context.canExperimentalCustomChecks() && custom::RegisterCustomChecks)
435 custom::RegisterCustomChecks(Context.getOptions(), *CheckFactories);
436#endif
437 std::vector<std::unique_ptr<ClangTidyCheck>> Checks =
438 CheckFactories->createChecksForLanguage(&Context);
439
440 ast_matchers::MatchFinder::MatchFinderOptions FinderOptions;
441
442 // We should always skip the declarations in modules.
443 FinderOptions.SkipDeclsInModules = true;
444
445 std::unique_ptr<ClangTidyProfiling> Profiling;
446 if (Context.getEnableProfiling()) {
447 Profiling =
448 std::make_unique<ClangTidyProfiling>(Context.getProfileStorageParams());
449 FinderOptions.CheckProfiling.emplace(Profiling->Records);
450 }
451
452 // Avoid processing system headers, unless the user explicitly requests it
453 if (!Context.getOptions().SystemHeaders.value_or(false))
454 FinderOptions.IgnoreSystemHeaders = true;
455
456 auto Finder =
457 std::make_unique<ast_matchers::MatchFinder>(std::move(FinderOptions));
458
459 Preprocessor *PP = &Compiler.getPreprocessor();
460 Preprocessor *ModuleExpanderPP = PP;
461
462 if (Context.canEnableModuleHeadersParsing() &&
463 Context.getLangOpts().Modules && OverlayFS != nullptr) {
464 auto ModuleExpander = std::make_unique<ExpandModularHeadersPPCallbacks>(
465 &Compiler, *OverlayFS);
466 ModuleExpanderPP = ModuleExpander->getPreprocessor();
467 PP->addPPCallbacks(std::move(ModuleExpander));
468 }
469
470 for (auto &Check : Checks) {
471 Check->registerMatchers(&*Finder);
472 Check->registerPPCallbacks(*SM, PP, ModuleExpanderPP);
473 }
474
475 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
476 if (!Checks.empty())
477 Consumers.push_back(Finder->newASTConsumer());
478
479#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
480 AnalyzerOptions &AnalyzerOptions = Compiler.getAnalyzerOpts();
481 AnalyzerOptions.CheckersAndPackages = getAnalyzerCheckersAndPackages(
482 Context, Context.canEnableAnalyzerAlphaCheckers());
483 if (!AnalyzerOptions.CheckersAndPackages.empty()) {
484 setStaticAnalyzerCheckerOpts(Context.getOptions(), AnalyzerOptions);
485 AnalyzerOptions.AnalysisDiagOpt = PD_NONE;
486 std::unique_ptr<ento::AnalysisASTConsumer> AnalysisConsumer =
487 ento::CreateAnalysisConsumer(Compiler);
488 AnalysisConsumer->AddDiagnosticConsumer(
489 std::make_unique<AnalyzerDiagnosticConsumer>(Context));
490 Consumers.push_back(std::move(AnalysisConsumer));
491 }
492#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
493 return std::make_unique<ClangTidyASTConsumer>(
494 std::move(Consumers), std::move(Profiling), std::move(Finder),
495 std::move(Checks));
496}
497
499 std::vector<std::string> CheckNames;
500 for (const auto &CheckFactory : *CheckFactories)
501 if (Context.isCheckEnabled(CheckFactory.getKey()))
502 CheckNames.emplace_back(CheckFactory.getKey());
503
504#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
505 for (const auto &AnalyzerCheck : getAnalyzerCheckersAndPackages(
506 Context, Context.canEnableAnalyzerAlphaCheckers()))
507 CheckNames.emplace_back(
508 (AnalyzerCheckNamePrefix + AnalyzerCheck.first).str());
509#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
510
511 llvm::sort(CheckNames);
512 return CheckNames;
513}
514
517 const std::vector<std::unique_ptr<ClangTidyCheck>> Checks =
518 CheckFactories->createChecks(&Context);
519 for (const auto &Check : Checks)
520 Check->storeOptions(Options);
521 return Options;
522}
523
524std::vector<std::string> getCheckNames(const ClangTidyOptions &Options,
527 ClangTidyContext Context(std::make_unique<DefaultOptionsProvider>(
528 ClangTidyGlobalOptions(), Options),
531 ClangTidyASTConsumerFactory Factory(Context);
532 return Factory.getCheckNames();
533}
534
536 const std::vector<std::string> &EnabledChecks) {
537 ClangTidyOptions::OptionMap FilteredOptions;
538 for (const auto &[OptionName, Value] : Options.CheckOptions) {
539 const size_t CheckNameEndPos = OptionName.find('.');
540 if (CheckNameEndPos == StringRef::npos)
541 continue;
542 const StringRef CheckName = OptionName.substr(0, CheckNameEndPos);
543 if (llvm::binary_search(EnabledChecks, CheckName))
544 FilteredOptions[OptionName] = Value;
545 }
546 Options.CheckOptions = std::move(FilteredOptions);
547}
548
553 ClangTidyContext Context(std::make_unique<DefaultOptionsProvider>(
554 ClangTidyGlobalOptions(), Options),
557 ClangTidyDiagnosticConsumer DiagConsumer(Context);
558 auto DiagOpts = std::make_unique<DiagnosticOptions>();
559 DiagnosticsEngine DE(llvm::makeIntrusiveRefCnt<DiagnosticIDs>(), *DiagOpts,
560 &DiagConsumer, /*ShouldOwnClient=*/false);
561 Context.setDiagnosticsEngine(std::move(DiagOpts), &DE);
562 ClangTidyASTConsumerFactory Factory(Context);
563 return Factory.getCheckOptions();
564}
565
566std::vector<ClangTidyError>
567runClangTidy(ClangTidyContext &Context, const CompilationDatabase &Compilations,
568 ArrayRef<std::string> InputFiles,
569 llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
570 bool ApplyAnyFix, bool EnableCheckProfile,
571 StringRef StoreCheckProfile, bool Quiet) {
572 ClangTool Tool(Compilations, InputFiles,
573 std::make_shared<PCHContainerOperations>(), BaseFS);
574
575 // Add extra arguments passed by the clang-tidy command-line.
576 const ArgumentsAdjuster PerFileExtraArgumentsInserter =
577 [&Context](const CommandLineArguments &Args, StringRef Filename) {
578 ClangTidyOptions Opts = Context.getOptionsForFile(Filename);
579 CommandLineArguments AdjustedArgs = Args;
580 if (Opts.ExtraArgsBefore) {
581 auto I = AdjustedArgs.begin();
582 if (I != AdjustedArgs.end() && !StringRef(*I).starts_with('-'))
583 ++I; // Skip compiler binary name, if it is there.
584 AdjustedArgs.insert(I, Opts.ExtraArgsBefore->begin(),
585 Opts.ExtraArgsBefore->end());
586 }
587 if (Opts.ExtraArgs)
588 AdjustedArgs.insert(AdjustedArgs.end(), Opts.ExtraArgs->begin(),
589 Opts.ExtraArgs->end());
590 return AdjustedArgs;
591 };
592
593 // Remove unwanted arguments passed to the compiler
594 const ArgumentsAdjuster PerFileArgumentRemover =
595 [&Context](const CommandLineArguments &Args, StringRef Filename) {
596 ClangTidyOptions Opts = Context.getOptionsForFile(Filename);
597 CommandLineArguments AdjustedArgs = Args;
598
599 if (Opts.RemovedArgs) {
600 for (const StringRef ArgToRemove : *Opts.RemovedArgs) {
601 AdjustedArgs.erase(std::remove(AdjustedArgs.begin(),
602 AdjustedArgs.end(), ArgToRemove),
603 AdjustedArgs.end());
604 }
605 }
606
607 return AdjustedArgs;
608 };
609
610 Tool.appendArgumentsAdjuster(PerFileArgumentRemover);
611 Tool.appendArgumentsAdjuster(PerFileExtraArgumentsInserter);
612 Tool.appendArgumentsAdjuster(getStripPluginsAdjuster());
615
616 ClangTidyDiagnosticConsumer DiagConsumer(Context, nullptr, true, ApplyAnyFix);
617 auto DiagOpts = std::make_unique<DiagnosticOptions>();
618 DiagnosticsEngine DE(DiagnosticIDs::create(), *DiagOpts, &DiagConsumer,
619 /*ShouldOwnClient=*/false);
620 Context.setDiagnosticsEngine(std::move(DiagOpts), &DE);
621 Tool.setDiagnosticConsumer(&DiagConsumer);
622
623 class ActionFactory : public FrontendActionFactory {
624 public:
625 ActionFactory(ClangTidyContext &Context,
626 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
627 bool Quiet)
628 : ConsumerFactory(Context, std::move(BaseFS)), Quiet(Quiet) {}
629 std::unique_ptr<FrontendAction> create() override {
630 return std::make_unique<Action>(&ConsumerFactory);
631 }
632
633 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
634 FileManager *Files,
635 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
636 DiagnosticConsumer *DiagConsumer) override {
637 // Explicitly ask to define __clang_analyzer__ macro.
638 Invocation->getPreprocessorOpts().SetUpStaticAnalyzer = true;
639 if (Quiet)
640 Invocation->getDiagnosticOpts().ShowCarets = false;
641 return FrontendActionFactory::runInvocation(
642 Invocation, Files, PCHContainerOps, DiagConsumer);
643 }
644
645 private:
646 class Action : public ASTFrontendAction {
647 public:
648 Action(ClangTidyASTConsumerFactory *Factory) : Factory(Factory) {}
649
650 private:
652
653 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
654 StringRef File) override {
655 return Factory->createASTConsumer(Compiler, File);
656 }
657 };
658
659 ClangTidyASTConsumerFactory ConsumerFactory;
660 bool Quiet;
661 };
662
663 ActionFactory Factory(Context, std::move(BaseFS), Quiet);
664 Tool.run(&Factory);
665 return DiagConsumer.take();
666}
667
668void handleErrors(llvm::ArrayRef<ClangTidyError> Errors,
670 unsigned &WarningsAsErrorsCount,
671 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
672 ErrorReporter Reporter(Context, Fix, std::move(BaseFS));
673 llvm::vfs::FileSystem &FileSystem =
674 Reporter.getSourceManager().getFileManager().getVirtualFileSystem();
675 auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();
676 if (!InitialWorkingDir)
677 llvm::report_fatal_error("Cannot get current working path.");
678
679 for (const ClangTidyError &Error : Errors) {
680 if (!Error.BuildDirectory.empty()) {
681 // By default, the working directory of file system is the current
682 // clang-tidy running directory.
683 //
684 // Change the directory to the one used during the analysis.
685 FileSystem.setCurrentWorkingDirectory(Error.BuildDirectory);
686 }
687 Reporter.reportDiagnostic(Error);
688 // Return to the initial directory to correctly resolve next Error.
689 FileSystem.setCurrentWorkingDirectory(InitialWorkingDir.get());
690 }
691 Reporter.finish();
692 WarningsAsErrorsCount += Reporter.getWarningsAsErrorsCount();
693}
694
695void exportReplacements(const StringRef MainFilePath,
696 const std::vector<ClangTidyError> &Errors,
697 raw_ostream &OS) {
698 TranslationUnitDiagnostics TUD;
699 TUD.MainSourceFile = std::string(MainFilePath);
700 for (const auto &Error : Errors) {
701 tooling::Diagnostic Diag = Error;
702 if (Error.IsWarningAsError)
703 Diag.DiagLevel = tooling::Diagnostic::Error;
704 TUD.Diagnostics.insert(TUD.Diagnostics.end(), Diag);
705 }
706
707 yaml::Output YAML(OS);
708 YAML << TUD;
709}
710
713 ChecksAndOptions Result;
714 ClangTidyOptions Opts;
715 Opts.Checks = "*";
716 ClangTidyContext Context(
717 std::make_unique<DefaultOptionsProvider>(ClangTidyGlobalOptions(), Opts),
719 ClangTidyCheckFactories Factories;
720#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
722 custom::RegisterCustomChecks(Context.getOptions(), Factories);
723#endif
724 for (const ClangTidyModuleRegistry::entry &Module :
725 ClangTidyModuleRegistry::entries()) {
726 Module.instantiate()->addCheckFactories(Factories);
727 }
728
729 for (const auto &Factory : Factories)
730 Result.Checks.insert(Factory.getKey());
731
732#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
733 SmallString<64> Buffer(AnalyzerCheckNamePrefix);
734 const size_t DefSize = Buffer.size();
735 for (const auto &AnalyzerCheck : AnalyzerOptions::getRegisteredCheckers(
737 Buffer.truncate(DefSize);
738 Buffer.append(AnalyzerCheck);
739 Result.Checks.insert(Buffer);
740 }
741
742 static constexpr StringRef OptionNames[] = {
743#define GET_CHECKER_OPTIONS
744#define CHECKER_OPTION(TYPE, CHECKER, OPTION_NAME, DESCRIPTION, DEFAULT, \
745 RELEASE, HIDDEN) \
746 ANALYZER_CHECK_NAME_PREFIX CHECKER ":" OPTION_NAME,
747
748#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
749#undef CHECKER_OPTION
750#undef GET_CHECKER_OPTIONS
751 };
752
753 Result.Options.insert_range(OptionNames);
754#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
755
756 Context.setOptionsCollector(&Result.Options);
757 for (const auto &Factory : Factories)
758 Factory.getValue()(Factory.getKey(), &Context);
759
760 return Result;
761}
762} // namespace clang::tidy
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.
@ Error
An error message.
Definition Protocol.h:751
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.
Definition ClangTidy.h:102
@ FB_NoFix
Don't try to apply any fix.
Definition ClangTidy.h:104
@ FB_FixNotes
Apply fixes found in notes.
Definition ClangTidy.h:108
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.
Definition Generators.h:150
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.