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