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