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/Frontend/AnalysisConsumer.h"
46#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
47
48using namespace clang::ast_matchers;
49using namespace clang::driver;
50using namespace clang::tooling;
51using namespace llvm;
52
53LLVM_INSTANTIATE_REGISTRY(clang::tidy::ClangTidyModuleRegistry)
54
55namespace clang::tidy {
56
57#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
58namespace custom {
59void (*RegisterCustomChecks)(const ClangTidyOptions &O,
60 ClangTidyCheckFactories &Factories) = nullptr;
61} // namespace custom
62#endif
63
64namespace {
65#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
66#define ANALYZER_CHECK_NAME_PREFIX "clang-analyzer-"
67static constexpr StringRef AnalyzerCheckNamePrefix = ANALYZER_CHECK_NAME_PREFIX;
68
69class AnalyzerDiagnosticConsumer : public ento::PathDiagnosticConsumer {
70public:
71 AnalyzerDiagnosticConsumer(ClangTidyContext &Context) : Context(Context) {}
72
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();
81
82 for (const auto &DiagPiece :
83 PD->path.flatten(/*ShouldFlattenMacros=*/true)) {
84 Context.diag(CheckName, DiagPiece->getLocation().asLocation(),
85 DiagPiece->getString(), DiagnosticIDs::Note)
86 << DiagPiece->getRanges();
87 }
88 }
89 }
90
91 StringRef getName() const override { return "ClangTidyDiags"; }
92 bool supportsLogicalOpControlFlow() const override { return true; }
93 bool supportsCrossFileDiagnostics() const override { return true; }
94
95private:
96 ClangTidyContext &Context;
97};
98#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
99
100class ErrorReporter {
101public:
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())
110 ? ShowColorsKind::On
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);
116 }
117
118 SourceManager &getSourceManager() { return SourceMgr; }
119
120 void reportDiagnostic(const ClangTidyError &Error) {
121 const tooling::DiagnosticMessage &Message = Error.Message;
122 const SourceLocation Loc =
123 getLocation(Message.FilePath, Message.FileOffset);
124 // Contains a pair for each attempted fix: location and whether the fix was
125 // applied successfully.
126 SmallVector<std::pair<SourceLocation, bool>, 4> FixLocations;
127 {
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;
135 WarningsAsErrors++;
136 }
137 const auto Diag =
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);
142 // FIXME: explore options to support interactive fix selection.
143 const llvm::StringMap<Replacements> *ChosenFix = nullptr;
144 if (ApplyFixes != FB_NoFix &&
145 (ChosenFix = getFixIt(Error, ApplyFixes == FB_FixNotes))) {
146 for (const auto &FileAndReplacements : *ChosenFix) {
147 for (const auto &Repl : FileAndReplacements.second) {
148 ++TotalFixes;
149 bool CanBeApplied = false;
150 if (!Repl.isApplicable())
151 continue;
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);
160 if (Err) {
161 // FIXME: Implement better conflict handling.
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()) -
168 NewOffset;
169 if (NewLength == R.getLength()) {
170 R = Replacement(R.getFilePath(), NewOffset, NewLength,
171 R.getReplacementText());
172 Replacements = Replacements.merge(tooling::Replacements(R));
173 CanBeApplied = true;
174 ++AppliedFixes;
175 } else {
176 llvm::errs()
177 << "Can't resolve conflict, skipping the replacement.\n";
178 }
179 } else {
180 CanBeApplied = true;
181 ++AppliedFixes;
182 }
183 FixLoc = getLocation(FixAbsoluteFilePath, Repl.getOffset());
184 FixLocations.emplace_back(FixLoc, CanBeApplied);
185 Entry.BuildDir = Error.BuildDirectory;
186 }
187 }
188 }
189 reportFix(Diag, Error.Message.Fix);
190 }
191 for (const auto &Fix : FixLocations) {
192 Diags.Report(Fix.first, Fix.second ? diag::note_fixit_applied
193 : diag::note_fixit_failed);
194 }
195 for (const auto &Note : Error.Notes)
196 reportNote(Note);
197 }
198
199 void finish() {
200 if (TotalFixes > 0) {
201 auto &VFS = Files.getVirtualFileSystem();
202 auto OriginalCWD = VFS.getCurrentWorkingDirectory();
203 bool AnyNotWritten = false;
204
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);
211 if (!Buffer) {
212 llvm::errs() << "Can't get buffer for file " << File << ": "
213 << Buffer.getError().message() << "\n";
214 // FIXME: Maybe don't apply fixes for other files as well.
215 continue;
216 }
217 const StringRef Code = Buffer.get()->getBuffer();
218 auto Style = format::getStyle(
219 Context.getOptionsForFile(File).FormatStyle.value_or("none"), File,
220 "none");
221 if (!Style) {
222 llvm::errs() << llvm::toString(Style.takeError()) << "\n";
223 continue;
224 }
225 llvm::Expected<tooling::Replacements> Replacements =
226 format::cleanupAroundReplacements(
227 Code, FileAndReplacements.second.Replaces, *Style);
228 if (!Replacements) {
229 llvm::errs() << llvm::toString(Replacements.takeError()) << "\n";
230 continue;
231 }
232 if (llvm::Expected<tooling::Replacements> FormattedReplacements =
233 format::formatReplacements(Code, *Replacements, *Style)) {
234 Replacements = std::move(FormattedReplacements);
235 if (!Replacements)
236 llvm_unreachable("!Replacements");
237 } else {
238 llvm::errs() << llvm::toString(FormattedReplacements.takeError())
239 << ". Skipping formatting.\n";
240 }
241 if (!tooling::applyAllReplacements(Replacements.get(), Rewrite))
242 llvm::errs() << "Can't apply replacements for file " << File << "\n";
243 AnyNotWritten |= Rewrite.overwriteChangedFiles();
244 }
245
246 if (AnyNotWritten) {
247 llvm::errs() << "clang-tidy failed to apply suggested fixes.\n";
248 } else {
249 llvm::errs() << "clang-tidy applied " << AppliedFixes << " of "
250 << TotalFixes << " suggested fixes.\n";
251 }
252
253 if (OriginalCWD)
254 VFS.setCurrentWorkingDirectory(*OriginalCWD);
255 }
256 }
257
258 unsigned getWarningsAsErrorsCount() const { return WarningsAsErrors; }
259
260private:
261 SourceLocation getLocation(StringRef FilePath, unsigned Offset) {
262 if (FilePath.empty())
263 return {};
264
265 auto File = SourceMgr.getFileManager().getOptionalFileRef(FilePath);
266 if (!File)
267 return {};
268
269 const FileID ID = SourceMgr.getOrCreateFileID(*File, SrcMgr::C_User);
270 return SourceMgr.getLocForStartOfFile(ID).getLocWithOffset(Offset);
271 }
272
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())
278 continue;
279 FileByteRange FBR;
280 FBR.FilePath = Repl.getFilePath().str();
281 FBR.FileOffset = Repl.getOffset();
282 FBR.Length = Repl.getLength();
283
284 Diag << FixItHint::CreateReplacement(getRange(FBR),
285 Repl.getReplacementText());
286 }
287 }
288 }
289
290 void reportNote(const tooling::DiagnosticMessage &Message) {
291 const SourceLocation Loc =
292 getLocation(Message.FilePath, Message.FileOffset);
293 const auto Diag =
294 Diags.Report(Loc, Diags.getCustomDiagID(DiagnosticsEngine::Note, "%0"))
295 << Message.Message;
296 for (const FileByteRange &FBR : Message.Ranges)
297 Diag << getRange(FBR);
298 reportFix(Diag, Message.Fix);
299 }
300
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);
307 // Retrieve the source range for applicable highlights and fixes. Macro
308 // definition on the command line have locations in a virtual buffer and
309 // don't have valid file paths and are therefore not applicable.
310 return CharSourceRange::getCharRange(BeginLoc, EndLoc);
311 }
312
313 struct ReplacementsWithBuildDir {
314 StringRef BuildDir;
315 Replacements Replaces;
316 };
317
318 FileManager Files;
319 LangOptions LangOpts; // FIXME: use langopts from each original file
320 DiagnosticOptions DiagOpts;
321 DiagnosticConsumer *DiagPrinter;
322 DiagnosticsEngine Diags;
323 SourceManager SourceMgr;
324 llvm::StringMap<ReplacementsWithBuildDir> FileReplacements;
325 ClangTidyContext &Context;
326 FixBehaviour ApplyFixes;
327 unsigned TotalFixes = 0U;
328 unsigned AppliedFixes = 0U;
329 unsigned WarningsAsErrors = 0U;
330};
331
332class ClangTidyASTConsumer : public MultiplexConsumer {
333public:
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)) {}
341
342private:
343 // Destructor order matters! Profiling must be destructed last.
344 // Or at least after Finder.
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 {}
349};
350
351} // namespace
352
354 ClangTidyContext &Context,
355 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS)
356 : Context(Context), OverlayFS(std::move(OverlayFS)),
357 CheckFactories(new ClangTidyCheckFactories) {
358#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
359 if (Context.canExperimentalCustomChecks() && custom::RegisterCustomChecks)
360 custom::RegisterCustomChecks(Context.getOptions(), *CheckFactories);
361#endif
362 for (const ClangTidyModuleRegistry::entry E :
363 ClangTidyModuleRegistry::entries()) {
364 std::unique_ptr<ClangTidyModule> Module = E.instantiate();
365 Module->addCheckFactories(*CheckFactories);
366 }
367}
368
369#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
370static void setStaticAnalyzerCheckerOpts(const ClangTidyOptions &Opts,
371 AnalyzerOptions &AnalyzerOptions) {
372 for (const auto &Opt : Opts.CheckOptions) {
373 StringRef OptName(Opt.getKey());
374 if (!OptName.consume_front(AnalyzerCheckNamePrefix))
375 continue;
376 // Analyzer options are always local options so we can ignore priority.
377 AnalyzerOptions.Config[OptName] = Opt.getValue().Value;
378 }
379}
380
381using CheckersList = std::vector<std::pair<std::string, bool>>;
382
383static CheckersList getAnalyzerCheckersAndPackages(ClangTidyContext &Context,
384 bool IncludeExperimental) {
385 CheckersList List;
386
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());
393 });
394
395 if (!AnalyzerChecksEnabled)
396 return List;
397
398 // List all static analyzer checkers that our filter enables.
399 //
400 // Always add all core checkers if any other static analyzer check is enabled.
401 // This is currently necessary, as other path sensitive checks rely on the
402 // core checkers.
403 for (const StringRef CheckName : RegisteredCheckers) {
404 const std::string ClangTidyCheckName(
405 (AnalyzerCheckNamePrefix + CheckName).str());
406
407 if (CheckName.starts_with("core") ||
408 Context.isCheckEnabled(ClangTidyCheckName)) {
409 List.emplace_back(std::string(CheckName), true);
410 }
411 }
412 return List;
413}
414#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
415
416std::unique_ptr<ASTConsumer>
418 StringRef File) {
419 // FIXME: Move this to a separate method, so that CreateASTConsumer doesn't
420 // modify Compiler.
421 SourceManager *SM = &Compiler.getSourceManager();
422 Context.setSourceManager(SM);
423 Context.setCurrentFile(File);
424 Context.setASTContext(&Compiler.getASTContext());
425
426 auto WorkingDir = Compiler.getSourceManager()
427 .getFileManager()
428 .getVirtualFileSystem()
429 .getCurrentWorkingDirectory();
430 if (WorkingDir)
431 Context.setCurrentBuildDirectory(WorkingDir.get());
432#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
433 if (Context.canExperimentalCustomChecks() && custom::RegisterCustomChecks)
434 custom::RegisterCustomChecks(Context.getOptions(), *CheckFactories);
435#endif
436 std::vector<std::unique_ptr<ClangTidyCheck>> Checks =
437 CheckFactories->createChecksForLanguage(&Context);
438
439 ast_matchers::MatchFinder::MatchFinderOptions FinderOptions;
440
441 // We should always skip the declarations in modules.
442 FinderOptions.SkipDeclsInModules = true;
443
444 std::unique_ptr<ClangTidyProfiling> Profiling;
445 if (Context.getEnableProfiling()) {
446 Profiling =
447 std::make_unique<ClangTidyProfiling>(Context.getProfileStorageParams());
448 FinderOptions.CheckProfiling.emplace(Profiling->Records);
449 }
450
451 // Avoid processing system headers, unless the user explicitly requests it
452 if (!Context.getOptions().SystemHeaders.value_or(false))
453 FinderOptions.IgnoreSystemHeaders = true;
454
455 auto Finder =
456 std::make_unique<ast_matchers::MatchFinder>(std::move(FinderOptions));
457
458 Preprocessor *PP = &Compiler.getPreprocessor();
459 Preprocessor *ModuleExpanderPP = PP;
460
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));
467 }
468
469 for (auto &Check : Checks) {
470 Check->registerMatchers(&*Finder);
471 Check->registerPPCallbacks(*SM, PP, ModuleExpanderPP);
472 }
473
474 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
475 if (!Checks.empty())
476 Consumers.push_back(Finder->newASTConsumer());
477
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));
490 }
491#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
492 return std::make_unique<ClangTidyASTConsumer>(
493 std::move(Consumers), std::move(Profiling), std::move(Finder),
494 std::move(Checks));
495}
496
498 std::vector<std::string> CheckNames;
499 for (const auto &CheckFactory : *CheckFactories)
500 if (Context.isCheckEnabled(CheckFactory.getKey()))
501 CheckNames.emplace_back(CheckFactory.getKey());
502
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());
508#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
509
510 llvm::sort(CheckNames);
511 return CheckNames;
512}
513
516 const std::vector<std::unique_ptr<ClangTidyCheck>> Checks =
517 CheckFactories->createChecks(&Context);
518 for (const auto &Check : Checks)
519 Check->storeOptions(Options);
520 return Options;
521}
522
523std::vector<std::string> getCheckNames(const ClangTidyOptions &Options,
526 ClangTidyContext Context(std::make_unique<DefaultOptionsProvider>(
527 ClangTidyGlobalOptions(), Options),
530 ClangTidyASTConsumerFactory Factory(Context);
531 return Factory.getCheckNames();
532}
533
535 const std::vector<std::string> &EnabledChecks) {
536 ClangTidyOptions::OptionMap FilteredOptions;
537 for (const auto &[OptionName, Value] : Options.CheckOptions) {
538 const size_t CheckNameEndPos = OptionName.find('.');
539 if (CheckNameEndPos == StringRef::npos)
540 continue;
541 const StringRef CheckName = OptionName.substr(0, CheckNameEndPos);
542 if (llvm::binary_search(EnabledChecks, CheckName))
543 FilteredOptions[OptionName] = Value;
544 }
545 Options.CheckOptions = std::move(FilteredOptions);
546}
547
552 ClangTidyContext Context(std::make_unique<DefaultOptionsProvider>(
553 ClangTidyGlobalOptions(), Options),
556 ClangTidyDiagnosticConsumer DiagConsumer(Context);
557 auto DiagOpts = std::make_unique<DiagnosticOptions>();
558 DiagnosticsEngine DE(llvm::makeIntrusiveRefCnt<DiagnosticIDs>(), *DiagOpts,
559 &DiagConsumer, /*ShouldOwnClient=*/false);
560 Context.setDiagnosticsEngine(std::move(DiagOpts), &DE);
561 ClangTidyASTConsumerFactory Factory(Context);
562 return Factory.getCheckOptions();
563}
564
565std::vector<ClangTidyError>
566runClangTidy(ClangTidyContext &Context, const CompilationDatabase &Compilations,
567 ArrayRef<std::string> InputFiles,
568 llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
569 bool ApplyAnyFix, bool EnableCheckProfile,
570 StringRef StoreCheckProfile, bool Quiet) {
571 ClangTool Tool(Compilations, InputFiles,
572 std::make_shared<PCHContainerOperations>(), BaseFS);
573
574 // Add extra arguments passed by the clang-tidy command-line.
575 const ArgumentsAdjuster PerFileExtraArgumentsInserter =
576 [&Context](const CommandLineArguments &Args, StringRef Filename) {
577 ClangTidyOptions Opts = Context.getOptionsForFile(Filename);
578 CommandLineArguments AdjustedArgs = Args;
579 if (Opts.ExtraArgsBefore) {
580 auto I = AdjustedArgs.begin();
581 if (I != AdjustedArgs.end() && !StringRef(*I).starts_with('-'))
582 ++I; // Skip compiler binary name, if it is there.
583 AdjustedArgs.insert(I, Opts.ExtraArgsBefore->begin(),
584 Opts.ExtraArgsBefore->end());
585 }
586 if (Opts.ExtraArgs)
587 AdjustedArgs.insert(AdjustedArgs.end(), Opts.ExtraArgs->begin(),
588 Opts.ExtraArgs->end());
589 return AdjustedArgs;
590 };
591
592 // Remove unwanted arguments passed to the compiler
593 const ArgumentsAdjuster PerFileArgumentRemover =
594 [&Context](const CommandLineArguments &Args, StringRef Filename) {
595 ClangTidyOptions Opts = Context.getOptionsForFile(Filename);
596 CommandLineArguments AdjustedArgs = Args;
597
598 if (Opts.RemovedArgs) {
599 for (const StringRef ArgToRemove : *Opts.RemovedArgs) {
600 AdjustedArgs.erase(std::remove(AdjustedArgs.begin(),
601 AdjustedArgs.end(), ArgToRemove),
602 AdjustedArgs.end());
603 }
604 }
605
606 return AdjustedArgs;
607 };
608
609 Tool.appendArgumentsAdjuster(PerFileArgumentRemover);
610 Tool.appendArgumentsAdjuster(PerFileExtraArgumentsInserter);
611 Tool.appendArgumentsAdjuster(getStripPluginsAdjuster());
614
615 ClangTidyDiagnosticConsumer DiagConsumer(Context, nullptr, true, ApplyAnyFix);
616 auto DiagOpts = std::make_unique<DiagnosticOptions>();
617 DiagnosticsEngine DE(DiagnosticIDs::create(), *DiagOpts, &DiagConsumer,
618 /*ShouldOwnClient=*/false);
619 Context.setDiagnosticsEngine(std::move(DiagOpts), &DE);
620 Tool.setDiagnosticConsumer(&DiagConsumer);
621
622 class ActionFactory : public FrontendActionFactory {
623 public:
624 ActionFactory(ClangTidyContext &Context,
625 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
626 bool Quiet)
627 : ConsumerFactory(Context, std::move(BaseFS)), Quiet(Quiet) {}
628 std::unique_ptr<FrontendAction> create() override {
629 return std::make_unique<Action>(&ConsumerFactory);
630 }
631
632 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
633 FileManager *Files,
634 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
635 DiagnosticConsumer *DiagConsumer) override {
636 // Explicitly ask to define __clang_analyzer__ macro.
637 Invocation->getPreprocessorOpts().SetUpStaticAnalyzer = true;
638 if (Quiet)
639 Invocation->getDiagnosticOpts().ShowCarets = false;
640 return FrontendActionFactory::runInvocation(
641 Invocation, Files, PCHContainerOps, DiagConsumer);
642 }
643
644 private:
645 class Action : public ASTFrontendAction {
646 public:
647 Action(ClangTidyASTConsumerFactory *Factory) : Factory(Factory) {}
648
649 private:
651
652 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
653 StringRef File) override {
654 return Factory->createASTConsumer(Compiler, File);
655 }
656 };
657
658 ClangTidyASTConsumerFactory ConsumerFactory;
659 bool Quiet;
660 };
661
662 ActionFactory Factory(Context, std::move(BaseFS), Quiet);
663 Tool.run(&Factory);
664 return DiagConsumer.take();
665}
666
667void handleErrors(llvm::ArrayRef<ClangTidyError> Errors,
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.");
677
678 for (const ClangTidyError &Error : Errors) {
679 if (!Error.BuildDirectory.empty()) {
680 // By default, the working directory of file system is the current
681 // clang-tidy running directory.
682 //
683 // Change the directory to the one used during the analysis.
684 FileSystem.setCurrentWorkingDirectory(Error.BuildDirectory);
685 }
686 Reporter.reportDiagnostic(Error);
687 // Return to the initial directory to correctly resolve next Error.
688 FileSystem.setCurrentWorkingDirectory(InitialWorkingDir.get());
689 }
690 Reporter.finish();
691 WarningsAsErrorsCount += Reporter.getWarningsAsErrorsCount();
692}
693
694void exportReplacements(const StringRef MainFilePath,
695 const std::vector<ClangTidyError> &Errors,
696 raw_ostream &OS) {
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);
704 }
705
706 yaml::Output YAML(OS);
707 YAML << TUD;
708}
709
712 ChecksAndOptions Result;
713 ClangTidyOptions Opts;
714 Opts.Checks = "*";
715 ClangTidyContext Context(
716 std::make_unique<DefaultOptionsProvider>(ClangTidyGlobalOptions(), Opts),
718 ClangTidyCheckFactories Factories;
719#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
721 custom::RegisterCustomChecks(Context.getOptions(), Factories);
722#endif
723 for (const ClangTidyModuleRegistry::entry &Module :
724 ClangTidyModuleRegistry::entries()) {
725 Module.instantiate()->addCheckFactories(Factories);
726 }
727
728 for (const auto &Factory : Factories)
729 Result.Checks.insert(Factory.getKey());
730
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);
739 }
740
741 static constexpr StringRef OptionNames[] = {
742#define GET_CHECKER_OPTIONS
743#define CHECKER_OPTION(TYPE, CHECKER, OPTION_NAME, DESCRIPTION, DEFAULT, \
744 RELEASE, HIDDEN) \
745 ANALYZER_CHECK_NAME_PREFIX CHECKER ":" OPTION_NAME,
746
747#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
748#undef CHECKER_OPTION
749#undef GET_CHECKER_OPTIONS
750 };
751
752 Result.Options.insert_range(OptionNames);
753#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
754
755 Context.setOptionsCollector(&Result.Options);
756 for (const auto &Factory : Factories)
757 Factory.getValue()(Factory.getKey(), &Context);
758
759 return Result;
760}
761} // 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.