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