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/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 <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 StringRef AnalyzerCheckNamePrefix = ANALYZER_CHECK_NAME_PREFIX;
67
68class AnalyzerDiagnosticConsumer : public ento::PathDiagnosticConsumer {
69public:
70 AnalyzerDiagnosticConsumer(ClangTidyContext &Context) : Context(Context) {}
71
72 void FlushDiagnosticsImpl(std::vector<const ento::PathDiagnostic *> &Diags,
73 FilesMade *FilesMade) override {
74 for (const ento::PathDiagnostic *PD : Diags) {
75 SmallString<64> CheckName(AnalyzerCheckNamePrefix);
76 CheckName += PD->getCheckerName();
77 Context.diag(CheckName, PD->getLocation().asLocation(),
78 PD->getShortDescription())
79 << PD->path.back()->getRanges();
80
81 for (const auto &DiagPiece :
82 PD->path.flatten(/*ShouldFlattenMacros=*/true)) {
83 Context.diag(CheckName, DiagPiece->getLocation().asLocation(),
84 DiagPiece->getString(), DiagnosticIDs::Note)
85 << DiagPiece->getRanges();
86 }
87 }
88 }
89
90 StringRef getName() const override { return "ClangTidyDiags"; }
91 bool supportsLogicalOpControlFlow() const override { return true; }
92 bool supportsCrossFileDiagnostics() const override { return true; }
93
94private:
95 ClangTidyContext &Context;
96};
97#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
98
99class ErrorReporter {
100public:
101 ErrorReporter(ClangTidyContext &Context, FixBehaviour ApplyFixes,
102 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS)
103 : Files(FileSystemOptions(), std::move(BaseFS)),
104 DiagPrinter(new TextDiagnosticPrinter(llvm::outs(), DiagOpts)),
105 Diags(DiagnosticIDs::create(), DiagOpts, DiagPrinter),
106 SourceMgr(Diags, Files), Context(Context), ApplyFixes(ApplyFixes) {
107 DiagOpts.ShowColors = Context.getOptions().UseColor.value_or(
108 llvm::sys::Process::StandardOutHasColors());
109 DiagPrinter->BeginSourceFile(LangOpts);
110 if (DiagOpts.ShowColors && !llvm::sys::Process::StandardOutIsDisplayed()) {
111 llvm::sys::Process::UseANSIEscapeCodes(true);
112 }
113 }
114
115 SourceManager &getSourceManager() { return SourceMgr; }
116
117 void reportDiagnostic(const ClangTidyError &Error) {
118 const tooling::DiagnosticMessage &Message = Error.Message;
119 const SourceLocation Loc =
120 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 const unsigned NewOffset =
161 Replacements.getShiftedCodePosition(R.getOffset());
162 const 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 const 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 const 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 const 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 const SourceLocation Loc =
288 getLocation(Message.FilePath, Message.FileOffset);
289 auto Diag =
290 Diags.Report(Loc, Diags.getCustomDiagID(DiagnosticsEngine::Note, "%0"))
291 << Message.Message;
292 for (const FileByteRange &FBR : Message.Ranges)
293 Diag << getRange(FBR);
294 reportFix(Diag, Message.Fix);
295 }
296
297 CharSourceRange getRange(const FileByteRange &Range) {
298 SmallString<128> AbsoluteFilePath{Range.FilePath};
299 Files.makeAbsolutePath(AbsoluteFilePath);
300 const SourceLocation BeginLoc =
301 getLocation(AbsoluteFilePath, Range.FileOffset);
302 const SourceLocation EndLoc = BeginLoc.getLocWithOffset(Range.Length);
303 // Retrieve the source range for applicable highlights and fixes. Macro
304 // definition on the command line have locations in a virtual buffer and
305 // don't have valid file paths and are therefore not applicable.
306 return CharSourceRange::getCharRange(BeginLoc, EndLoc);
307 }
308
309 struct ReplacementsWithBuildDir {
310 StringRef BuildDir;
311 Replacements Replaces;
312 };
313
314 FileManager Files;
315 LangOptions LangOpts; // FIXME: use langopts from each original file
316 DiagnosticOptions DiagOpts;
317 DiagnosticConsumer *DiagPrinter;
318 DiagnosticsEngine Diags;
319 SourceManager SourceMgr;
320 llvm::StringMap<ReplacementsWithBuildDir> FileReplacements;
321 ClangTidyContext &Context;
322 FixBehaviour ApplyFixes;
323 unsigned TotalFixes = 0U;
324 unsigned AppliedFixes = 0U;
325 unsigned WarningsAsErrors = 0U;
326};
327
328class ClangTidyASTConsumer : public MultiplexConsumer {
329public:
330 ClangTidyASTConsumer(std::vector<std::unique_ptr<ASTConsumer>> Consumers,
331 std::unique_ptr<ClangTidyProfiling> Profiling,
332 std::unique_ptr<ast_matchers::MatchFinder> Finder,
333 std::vector<std::unique_ptr<ClangTidyCheck>> Checks)
334 : MultiplexConsumer(std::move(Consumers)),
335 Profiling(std::move(Profiling)), Finder(std::move(Finder)),
336 Checks(std::move(Checks)) {}
337
338private:
339 // Destructor order matters! Profiling must be destructed last.
340 // Or at least after Finder.
341 std::unique_ptr<ClangTidyProfiling> Profiling;
342 std::unique_ptr<ast_matchers::MatchFinder> Finder;
343 std::vector<std::unique_ptr<ClangTidyCheck>> Checks;
344 void anchor() override {};
345};
346
347} // namespace
348
350 ClangTidyContext &Context,
351 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS)
352 : Context(Context), OverlayFS(std::move(OverlayFS)),
353 CheckFactories(new ClangTidyCheckFactories) {
354#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
355 if (Context.canExperimentalCustomChecks() && custom::RegisterCustomChecks)
356 custom::RegisterCustomChecks(Context.getOptions(), *CheckFactories);
357#endif
358 for (const ClangTidyModuleRegistry::entry E :
359 ClangTidyModuleRegistry::entries()) {
360 std::unique_ptr<ClangTidyModule> Module = E.instantiate();
361 Module->addCheckFactories(*CheckFactories);
362 }
363}
364
365#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
366static void
367setStaticAnalyzerCheckerOpts(const ClangTidyOptions &Opts,
368 clang::AnalyzerOptions &AnalyzerOptions) {
369 for (const auto &Opt : Opts.CheckOptions) {
370 StringRef OptName(Opt.getKey());
371 if (!OptName.consume_front(AnalyzerCheckNamePrefix))
372 continue;
373 // Analyzer options are always local options so we can ignore priority.
374 AnalyzerOptions.Config[OptName] = Opt.getValue().Value;
375 }
376}
377
378using CheckersList = std::vector<std::pair<std::string, bool>>;
379
380static CheckersList getAnalyzerCheckersAndPackages(ClangTidyContext &Context,
381 bool IncludeExperimental) {
382 CheckersList List;
383
384 const auto &RegisteredCheckers =
385 AnalyzerOptions::getRegisteredCheckers(IncludeExperimental);
386 const bool AnalyzerChecksEnabled =
387 llvm::any_of(RegisteredCheckers, [&](StringRef CheckName) -> bool {
388 return Context.isCheckEnabled(
389 (AnalyzerCheckNamePrefix + CheckName).str());
390 });
391
392 if (!AnalyzerChecksEnabled)
393 return List;
394
395 // List all static analyzer checkers that our filter enables.
396 //
397 // Always add all core checkers if any other static analyzer check is enabled.
398 // This is currently necessary, as other path sensitive checks rely on the
399 // core checkers.
400 for (const StringRef CheckName : RegisteredCheckers) {
401 const std::string ClangTidyCheckName(
402 (AnalyzerCheckNamePrefix + CheckName).str());
403
404 if (CheckName.starts_with("core") ||
405 Context.isCheckEnabled(ClangTidyCheckName)) {
406 List.emplace_back(std::string(CheckName), true);
407 }
408 }
409 return List;
410}
411#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
412
413std::unique_ptr<clang::ASTConsumer>
415 clang::CompilerInstance &Compiler, StringRef File) {
416 // FIXME: Move this to a separate method, so that CreateASTConsumer doesn't
417 // modify Compiler.
418 SourceManager *SM = &Compiler.getSourceManager();
419 Context.setSourceManager(SM);
420 Context.setCurrentFile(File);
421 Context.setASTContext(&Compiler.getASTContext());
422
423 auto WorkingDir = Compiler.getSourceManager()
424 .getFileManager()
425 .getVirtualFileSystem()
426 .getCurrentWorkingDirectory();
427 if (WorkingDir)
428 Context.setCurrentBuildDirectory(WorkingDir.get());
429#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
430 if (Context.canExperimentalCustomChecks() && custom::RegisterCustomChecks)
431 custom::RegisterCustomChecks(Context.getOptions(), *CheckFactories);
432#endif
433 std::vector<std::unique_ptr<ClangTidyCheck>> Checks =
434 CheckFactories->createChecksForLanguage(&Context);
435
436 ast_matchers::MatchFinder::MatchFinderOptions FinderOptions;
437
438 std::unique_ptr<ClangTidyProfiling> Profiling;
439 if (Context.getEnableProfiling()) {
440 Profiling =
441 std::make_unique<ClangTidyProfiling>(Context.getProfileStorageParams());
442 FinderOptions.CheckProfiling.emplace(Profiling->Records);
443 }
444
445 // Avoid processing system headers, unless the user explicitly requests it
446 if (!Context.getOptions().SystemHeaders.value_or(false))
447 FinderOptions.IgnoreSystemHeaders = true;
448
449 std::unique_ptr<ast_matchers::MatchFinder> Finder(
450 new ast_matchers::MatchFinder(std::move(FinderOptions)));
451
452 Preprocessor *PP = &Compiler.getPreprocessor();
453 Preprocessor *ModuleExpanderPP = PP;
454
455 if (Context.canEnableModuleHeadersParsing() &&
456 Context.getLangOpts().Modules && OverlayFS != nullptr) {
457 auto ModuleExpander = std::make_unique<ExpandModularHeadersPPCallbacks>(
458 &Compiler, *OverlayFS);
459 ModuleExpanderPP = ModuleExpander->getPreprocessor();
460 PP->addPPCallbacks(std::move(ModuleExpander));
461 }
462
463 for (auto &Check : Checks) {
464 Check->registerMatchers(&*Finder);
465 Check->registerPPCallbacks(*SM, PP, ModuleExpanderPP);
466 }
467
468 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
469 if (!Checks.empty())
470 Consumers.push_back(Finder->newASTConsumer());
471
472#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
473 AnalyzerOptions &AnalyzerOptions = Compiler.getAnalyzerOpts();
474 AnalyzerOptions.CheckersAndPackages = getAnalyzerCheckersAndPackages(
475 Context, Context.canEnableAnalyzerAlphaCheckers());
476 if (!AnalyzerOptions.CheckersAndPackages.empty()) {
477 setStaticAnalyzerCheckerOpts(Context.getOptions(), AnalyzerOptions);
478 AnalyzerOptions.AnalysisDiagOpt = PD_NONE;
479 std::unique_ptr<ento::AnalysisASTConsumer> AnalysisConsumer =
480 ento::CreateAnalysisConsumer(Compiler);
481 AnalysisConsumer->AddDiagnosticConsumer(
482 std::make_unique<AnalyzerDiagnosticConsumer>(Context));
483 Consumers.push_back(std::move(AnalysisConsumer));
484 }
485#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
486 return std::make_unique<ClangTidyASTConsumer>(
487 std::move(Consumers), std::move(Profiling), std::move(Finder),
488 std::move(Checks));
489}
490
492 std::vector<std::string> CheckNames;
493 for (const auto &CheckFactory : *CheckFactories) {
494 if (Context.isCheckEnabled(CheckFactory.getKey()))
495 CheckNames.emplace_back(CheckFactory.getKey());
496 }
497
498#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
499 for (const auto &AnalyzerCheck : getAnalyzerCheckersAndPackages(
500 Context, Context.canEnableAnalyzerAlphaCheckers()))
501 CheckNames.emplace_back(
502 (AnalyzerCheckNamePrefix + AnalyzerCheck.first).str());
503#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
504
505 llvm::sort(CheckNames);
506 return CheckNames;
507}
508
511 const std::vector<std::unique_ptr<ClangTidyCheck>> Checks =
512 CheckFactories->createChecks(&Context);
513 for (const auto &Check : Checks)
514 Check->storeOptions(Options);
515 return Options;
516}
517
518std::vector<std::string> getCheckNames(const ClangTidyOptions &Options,
522 std::make_unique<DefaultOptionsProvider>(ClangTidyGlobalOptions(),
523 Options),
525 ClangTidyASTConsumerFactory Factory(Context);
526 return Factory.getCheckNames();
527}
528
530 const std::vector<std::string> &EnabledChecks) {
531 ClangTidyOptions::OptionMap FilteredOptions;
532 for (const auto &[OptionName, Value] : Options.CheckOptions) {
533 const size_t CheckNameEndPos = OptionName.find('.');
534 if (CheckNameEndPos == StringRef::npos)
535 continue;
536 const StringRef CheckName = OptionName.substr(0, CheckNameEndPos);
537 if (llvm::binary_search(EnabledChecks, CheckName))
538 FilteredOptions[OptionName] = Value;
539 }
540 Options.CheckOptions = std::move(FilteredOptions);
541}
542
548 std::make_unique<DefaultOptionsProvider>(ClangTidyGlobalOptions(),
549 Options),
551 ClangTidyDiagnosticConsumer DiagConsumer(Context);
552 auto DiagOpts = std::make_unique<DiagnosticOptions>();
553 DiagnosticsEngine DE(llvm::makeIntrusiveRefCnt<DiagnosticIDs>(), *DiagOpts,
554 &DiagConsumer, /*ShouldOwnClient=*/false);
555 Context.setDiagnosticsEngine(std::move(DiagOpts), &DE);
556 ClangTidyASTConsumerFactory Factory(Context);
557 return Factory.getCheckOptions();
558}
559
560std::vector<ClangTidyError>
562 const CompilationDatabase &Compilations,
563 ArrayRef<std::string> InputFiles,
564 llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
565 bool ApplyAnyFix, bool EnableCheckProfile,
566 llvm::StringRef StoreCheckProfile, bool Quiet) {
567 ClangTool Tool(Compilations, InputFiles,
568 std::make_shared<PCHContainerOperations>(), BaseFS);
569
570 // Add extra arguments passed by the clang-tidy command-line.
571 const ArgumentsAdjuster PerFileExtraArgumentsInserter =
572 [&Context](const CommandLineArguments &Args, StringRef Filename) {
573 ClangTidyOptions Opts = Context.getOptionsForFile(Filename);
574 CommandLineArguments AdjustedArgs = Args;
575 if (Opts.ExtraArgsBefore) {
576 auto I = AdjustedArgs.begin();
577 if (I != AdjustedArgs.end() && !StringRef(*I).starts_with("-"))
578 ++I; // Skip compiler binary name, if it is there.
579 AdjustedArgs.insert(I, Opts.ExtraArgsBefore->begin(),
580 Opts.ExtraArgsBefore->end());
581 }
582 if (Opts.ExtraArgs)
583 AdjustedArgs.insert(AdjustedArgs.end(), Opts.ExtraArgs->begin(),
584 Opts.ExtraArgs->end());
585 return AdjustedArgs;
586 };
587
588 // Remove unwanted arguments passed to the compiler
589 const ArgumentsAdjuster PerFileArgumentRemover =
590 [&Context](const CommandLineArguments &Args, StringRef Filename) {
591 ClangTidyOptions Opts = Context.getOptionsForFile(Filename);
592 CommandLineArguments AdjustedArgs = Args;
593
594 if (Opts.RemovedArgs) {
595 for (const StringRef ArgToRemove : *Opts.RemovedArgs) {
596 AdjustedArgs.erase(std::remove(AdjustedArgs.begin(),
597 AdjustedArgs.end(), ArgToRemove),
598 AdjustedArgs.end());
599 }
600 }
601
602 return AdjustedArgs;
603 };
604
605 Tool.appendArgumentsAdjuster(PerFileArgumentRemover);
606 Tool.appendArgumentsAdjuster(PerFileExtraArgumentsInserter);
607 Tool.appendArgumentsAdjuster(getStripPluginsAdjuster());
610
611 ClangTidyDiagnosticConsumer DiagConsumer(Context, nullptr, true, ApplyAnyFix);
612 auto DiagOpts = std::make_unique<DiagnosticOptions>();
613 DiagnosticsEngine DE(DiagnosticIDs::create(), *DiagOpts, &DiagConsumer,
614 /*ShouldOwnClient=*/false);
615 Context.setDiagnosticsEngine(std::move(DiagOpts), &DE);
616 Tool.setDiagnosticConsumer(&DiagConsumer);
617
618 class ActionFactory : public FrontendActionFactory {
619 public:
620 ActionFactory(ClangTidyContext &Context,
621 IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
622 bool Quiet)
623 : ConsumerFactory(Context, std::move(BaseFS)), Quiet(Quiet) {}
624 std::unique_ptr<FrontendAction> create() override {
625 return std::make_unique<Action>(&ConsumerFactory);
626 }
627
628 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
629 FileManager *Files,
630 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
631 DiagnosticConsumer *DiagConsumer) override {
632 // Explicitly ask to define __clang_analyzer__ macro.
633 Invocation->getPreprocessorOpts().SetUpStaticAnalyzer = true;
634 if (Quiet)
635 Invocation->getDiagnosticOpts().ShowCarets = false;
636 return FrontendActionFactory::runInvocation(
637 Invocation, Files, PCHContainerOps, DiagConsumer);
638 }
639
640 private:
641 class Action : public ASTFrontendAction {
642 public:
643 Action(ClangTidyASTConsumerFactory *Factory) : Factory(Factory) {}
644 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
645 StringRef File) override {
646 return Factory->createASTConsumer(Compiler, File);
647 }
648
649 private:
651 };
652
653 ClangTidyASTConsumerFactory ConsumerFactory;
654 bool Quiet;
655 };
656
657 ActionFactory Factory(Context, std::move(BaseFS), Quiet);
658 Tool.run(&Factory);
659 return DiagConsumer.take();
660}
661
662void handleErrors(llvm::ArrayRef<ClangTidyError> Errors,
664 unsigned &WarningsAsErrorsCount,
665 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
666 ErrorReporter Reporter(Context, Fix, std::move(BaseFS));
667 llvm::vfs::FileSystem &FileSystem =
668 Reporter.getSourceManager().getFileManager().getVirtualFileSystem();
669 auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();
670 if (!InitialWorkingDir)
671 llvm::report_fatal_error("Cannot get current working path.");
672
673 for (const ClangTidyError &Error : Errors) {
674 if (!Error.BuildDirectory.empty()) {
675 // By default, the working directory of file system is the current
676 // clang-tidy running directory.
677 //
678 // Change the directory to the one used during the analysis.
679 FileSystem.setCurrentWorkingDirectory(Error.BuildDirectory);
680 }
681 Reporter.reportDiagnostic(Error);
682 // Return to the initial directory to correctly resolve next Error.
683 FileSystem.setCurrentWorkingDirectory(InitialWorkingDir.get());
684 }
685 Reporter.finish();
686 WarningsAsErrorsCount += Reporter.getWarningsAsErrorsCount();
687}
688
689void exportReplacements(const llvm::StringRef MainFilePath,
690 const std::vector<ClangTidyError> &Errors,
691 raw_ostream &OS) {
692 TranslationUnitDiagnostics TUD;
693 TUD.MainSourceFile = std::string(MainFilePath);
694 for (const auto &Error : Errors) {
695 tooling::Diagnostic Diag = Error;
696 if (Error.IsWarningAsError)
697 Diag.DiagLevel = tooling::Diagnostic::Error;
698 TUD.Diagnostics.insert(TUD.Diagnostics.end(), Diag);
699 }
700
701 yaml::Output YAML(OS);
702 YAML << TUD;
703}
704
707 ChecksAndOptions Result;
708 ClangTidyOptions Opts;
709 Opts.Checks = "*";
711 std::make_unique<DefaultOptionsProvider>(ClangTidyGlobalOptions(), Opts),
713 ClangTidyCheckFactories Factories;
714#if CLANG_TIDY_ENABLE_QUERY_BASED_CUSTOM_CHECKS
716 custom::RegisterCustomChecks(Context.getOptions(), Factories);
717#endif
718 for (const ClangTidyModuleRegistry::entry &Module :
719 ClangTidyModuleRegistry::entries()) {
720 Module.instantiate()->addCheckFactories(Factories);
721 }
722
723 for (const auto &Factory : Factories)
724 Result.Checks.insert(Factory.getKey());
725
726#if CLANG_TIDY_ENABLE_STATIC_ANALYZER
727 SmallString<64> Buffer(AnalyzerCheckNamePrefix);
728 const size_t DefSize = Buffer.size();
729 for (const auto &AnalyzerCheck : AnalyzerOptions::getRegisteredCheckers(
731 Buffer.truncate(DefSize);
732 Buffer.append(AnalyzerCheck);
733 Result.Checks.insert(Buffer);
734 }
735
736 static constexpr StringRef OptionNames[] = {
737#define GET_CHECKER_OPTIONS
738#define CHECKER_OPTION(TYPE, CHECKER, OPTION_NAME, DESCRIPTION, DEFAULT, \
739 RELEASE, HIDDEN) \
740 ANALYZER_CHECK_NAME_PREFIX CHECKER ":" OPTION_NAME,
741
742#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
743#undef CHECKER_OPTION
744#undef GET_CHECKER_OPTIONS
745 };
746
747 Result.Options.insert_range(OptionNames);
748#endif // CLANG_TIDY_ENABLE_STATIC_ANALYZER
749
750 Context.setOptionsCollector(&Result.Options);
751 for (const auto &Factory : Factories) {
752 Factory.getValue()(Factory.getKey(), &Context);
753 }
754
755 return Result;
756}
757} // 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:145
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.