Changed FrontendActionFactory::create to return a std::unique_ptr
[lldb.git] / clang-tools-extra / clang-tidy / ClangTidy.cpp
1 //===--- tools/extra/clang-tidy/ClangTidy.cpp - Clang tidy tool -----------===//
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 ///    http://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 "ClangTidyDiagnosticConsumer.h"
19 #include "ClangTidyModuleRegistry.h"
20 #include "ClangTidyProfiling.h"
21 #include "ExpandModularHeadersPPCallbacks.h"
22 #include "clang/AST/ASTConsumer.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/ASTMatchers/ASTMatchFinder.h"
26 #include "clang/Config/config.h"
27 #include "clang/Format/Format.h"
28 #include "clang/Frontend/ASTConsumers.h"
29 #include "clang/Frontend/CompilerInstance.h"
30 #include "clang/Frontend/FrontendActions.h"
31 #include "clang/Frontend/FrontendDiagnostic.h"
32 #include "clang/Frontend/MultiplexConsumer.h"
33 #include "clang/Frontend/TextDiagnosticPrinter.h"
34 #include "clang/Lex/PPCallbacks.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Rewrite/Frontend/FixItRewriter.h"
37 #include "clang/Rewrite/Frontend/FrontendActions.h"
38 #include "clang/Tooling/Core/Diagnostic.h"
39 #if CLANG_ENABLE_STATIC_ANALYZER
40 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
41 #include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
42 #endif // CLANG_ENABLE_STATIC_ANALYZER
43 #include "clang/Tooling/DiagnosticsYaml.h"
44 #include "clang/Tooling/Refactoring.h"
45 #include "clang/Tooling/ReplacementsYaml.h"
46 #include "clang/Tooling/Tooling.h"
47 #include "llvm/Support/Process.h"
48 #include "llvm/Support/Signals.h"
49 #include <algorithm>
50 #include <utility>
51
52 using namespace clang::ast_matchers;
53 using namespace clang::driver;
54 using namespace clang::tooling;
55 using namespace llvm;
56
57 LLVM_INSTANTIATE_REGISTRY(clang::tidy::ClangTidyModuleRegistry)
58
59 namespace clang {
60 namespace tidy {
61
62 namespace {
63 #if CLANG_ENABLE_STATIC_ANALYZER
64 static const char *AnalyzerCheckNamePrefix = "clang-analyzer-";
65
66 class AnalyzerDiagnosticConsumer : public ento::PathDiagnosticConsumer {
67 public:
68   AnalyzerDiagnosticConsumer(ClangTidyContext &Context) : Context(Context) {}
69
70   void FlushDiagnosticsImpl(std::vector<const ento::PathDiagnostic *> &Diags,
71                             FilesMade *filesMade) override {
72     for (const ento::PathDiagnostic *PD : Diags) {
73       SmallString<64> CheckName(AnalyzerCheckNamePrefix);
74       CheckName += PD->getCheckName();
75       Context.diag(CheckName, PD->getLocation().asLocation(),
76                    PD->getShortDescription())
77           << PD->path.back()->getRanges();
78
79       for (const auto &DiagPiece :
80            PD->path.flatten(/*ShouldFlattenMacros=*/true)) {
81         Context.diag(CheckName, DiagPiece->getLocation().asLocation(),
82                      DiagPiece->getString(), DiagnosticIDs::Note)
83             << DiagPiece->getRanges();
84       }
85     }
86   }
87
88   StringRef getName() const override { return "ClangTidyDiags"; }
89   bool supportsLogicalOpControlFlow() const override { return true; }
90   bool supportsCrossFileDiagnostics() const override { return true; }
91
92 private:
93   ClangTidyContext &Context;
94 };
95 #endif // CLANG_ENABLE_STATIC_ANALYZER
96
97 class ErrorReporter {
98 public:
99   ErrorReporter(ClangTidyContext &Context, bool ApplyFixes,
100                 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS)
101       : Files(FileSystemOptions(), BaseFS), DiagOpts(new DiagnosticOptions()),
102         DiagPrinter(new TextDiagnosticPrinter(llvm::outs(), &*DiagOpts)),
103         Diags(IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), &*DiagOpts,
104               DiagPrinter),
105         SourceMgr(Diags, Files), Context(Context), ApplyFixes(ApplyFixes),
106         TotalFixes(0), AppliedFixes(0), WarningsAsErrors(0) {
107     DiagOpts->ShowColors = llvm::sys::Process::StandardOutHasColors();
108     DiagPrinter->BeginSourceFile(LangOpts);
109   }
110
111   SourceManager &getSourceManager() { return SourceMgr; }
112
113   void reportDiagnostic(const ClangTidyError &Error) {
114     const tooling::DiagnosticMessage &Message = Error.Message;
115     SourceLocation Loc = getLocation(Message.FilePath, Message.FileOffset);
116     // Contains a pair for each attempted fix: location and whether the fix was
117     // applied successfully.
118     SmallVector<std::pair<SourceLocation, bool>, 4> FixLocations;
119     {
120       auto Level = static_cast<DiagnosticsEngine::Level>(Error.DiagLevel);
121       std::string Name = Error.DiagnosticName;
122       if (Error.IsWarningAsError) {
123         Name += ",-warnings-as-errors";
124         Level = DiagnosticsEngine::Error;
125         WarningsAsErrors++;
126       }
127       auto Diag = Diags.Report(Loc, Diags.getCustomDiagID(Level, "%0 [%1]"))
128                   << Message.Message << Name;
129       // FIXME: explore options to support interactive fix selection.
130       const llvm::StringMap<Replacements> *ChosenFix = selectFirstFix(Error);
131       if (ApplyFixes && ChosenFix) {
132         for (const auto &FileAndReplacements : *ChosenFix) {
133           for (const auto &Repl : FileAndReplacements.second) {
134             ++TotalFixes;
135             bool CanBeApplied = false;
136             if (!Repl.isApplicable())
137               continue;
138             SourceLocation FixLoc;
139             SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
140             Files.makeAbsolutePath(FixAbsoluteFilePath);
141             tooling::Replacement R(FixAbsoluteFilePath, Repl.getOffset(),
142                                    Repl.getLength(), Repl.getReplacementText());
143             Replacements &Replacements = FileReplacements[R.getFilePath()];
144             llvm::Error Err = Replacements.add(R);
145             if (Err) {
146               // FIXME: Implement better conflict handling.
147               llvm::errs() << "Trying to resolve conflict: "
148                            << llvm::toString(std::move(Err)) << "\n";
149               unsigned NewOffset =
150                   Replacements.getShiftedCodePosition(R.getOffset());
151               unsigned NewLength = Replacements.getShiftedCodePosition(
152                                        R.getOffset() + R.getLength()) -
153                                    NewOffset;
154               if (NewLength == R.getLength()) {
155                 R = Replacement(R.getFilePath(), NewOffset, NewLength,
156                                 R.getReplacementText());
157                 Replacements = Replacements.merge(tooling::Replacements(R));
158                 CanBeApplied = true;
159                 ++AppliedFixes;
160               } else {
161                 llvm::errs()
162                     << "Can't resolve conflict, skipping the replacement.\n";
163               }
164             } else {
165               CanBeApplied = true;
166               ++AppliedFixes;
167             }
168             FixLoc = getLocation(FixAbsoluteFilePath, Repl.getOffset());
169             FixLocations.push_back(std::make_pair(FixLoc, CanBeApplied));
170           }
171         }
172       }
173       reportFix(Diag, Error.Message.Fix);
174     }
175     for (auto Fix : FixLocations) {
176       Diags.Report(Fix.first, Fix.second ? diag::note_fixit_applied
177                                          : diag::note_fixit_failed);
178     }
179     for (const auto &Note : Error.Notes)
180       reportNote(Note);
181   }
182
183   void Finish() {
184     if (ApplyFixes && TotalFixes > 0) {
185       Rewriter Rewrite(SourceMgr, LangOpts);
186       for (const auto &FileAndReplacements : FileReplacements) {
187         StringRef File = FileAndReplacements.first();
188         llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
189             SourceMgr.getFileManager().getBufferForFile(File);
190         if (!Buffer) {
191           llvm::errs() << "Can't get buffer for file " << File << ": "
192                        << Buffer.getError().message() << "\n";
193           // FIXME: Maybe don't apply fixes for other files as well.
194           continue;
195         }
196         StringRef Code = Buffer.get()->getBuffer();
197         auto Style = format::getStyle(
198             *Context.getOptionsForFile(File).FormatStyle, File, "none");
199         if (!Style) {
200           llvm::errs() << llvm::toString(Style.takeError()) << "\n";
201           continue;
202         }
203         llvm::Expected<tooling::Replacements> Replacements =
204             format::cleanupAroundReplacements(Code, FileAndReplacements.second,
205                                               *Style);
206         if (!Replacements) {
207           llvm::errs() << llvm::toString(Replacements.takeError()) << "\n";
208           continue;
209         }
210         if (llvm::Expected<tooling::Replacements> FormattedReplacements =
211                 format::formatReplacements(Code, *Replacements, *Style)) {
212           Replacements = std::move(FormattedReplacements);
213           if (!Replacements)
214             llvm_unreachable("!Replacements");
215         } else {
216           llvm::errs() << llvm::toString(FormattedReplacements.takeError())
217                        << ". Skipping formatting.\n";
218         }
219         if (!tooling::applyAllReplacements(Replacements.get(), Rewrite)) {
220           llvm::errs() << "Can't apply replacements for file " << File << "\n";
221         }
222       }
223       if (Rewrite.overwriteChangedFiles()) {
224         llvm::errs() << "clang-tidy failed to apply suggested fixes.\n";
225       } else {
226         llvm::errs() << "clang-tidy applied " << AppliedFixes << " of "
227                      << TotalFixes << " suggested fixes.\n";
228       }
229     }
230   }
231
232   unsigned getWarningsAsErrorsCount() const { return WarningsAsErrors; }
233
234 private:
235   SourceLocation getLocation(StringRef FilePath, unsigned Offset) {
236     if (FilePath.empty())
237       return SourceLocation();
238
239     auto File = SourceMgr.getFileManager().getFile(FilePath);
240     if (!File)
241       return SourceLocation();
242
243     FileID ID = SourceMgr.getOrCreateFileID(*File, SrcMgr::C_User);
244     return SourceMgr.getLocForStartOfFile(ID).getLocWithOffset(Offset);
245   }
246
247   void reportFix(const DiagnosticBuilder &Diag,
248                  const llvm::StringMap<Replacements> &Fix) {
249     for (const auto &FileAndReplacements : Fix) {
250       for (const auto &Repl : FileAndReplacements.second) {
251         if (!Repl.isApplicable())
252           continue;
253         SmallString<128> FixAbsoluteFilePath = Repl.getFilePath();
254         Files.makeAbsolutePath(FixAbsoluteFilePath);
255         SourceLocation FixLoc =
256             getLocation(FixAbsoluteFilePath, Repl.getOffset());
257         SourceLocation FixEndLoc = FixLoc.getLocWithOffset(Repl.getLength());
258         // Retrieve the source range for applicable fixes. Macro definitions
259         // on the command line have locations in a virtual buffer and don't
260         // have valid file paths and are therefore not applicable.
261         CharSourceRange Range =
262             CharSourceRange::getCharRange(SourceRange(FixLoc, FixEndLoc));
263         Diag << FixItHint::CreateReplacement(Range, Repl.getReplacementText());
264       }
265     }
266   }
267
268   void reportNote(const tooling::DiagnosticMessage &Message) {
269     SourceLocation Loc = getLocation(Message.FilePath, Message.FileOffset);
270     auto Diag =
271         Diags.Report(Loc, Diags.getCustomDiagID(DiagnosticsEngine::Note, "%0"))
272         << Message.Message;
273     reportFix(Diag, Message.Fix);
274   }
275
276   FileManager Files;
277   LangOptions LangOpts; // FIXME: use langopts from each original file
278   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
279   DiagnosticConsumer *DiagPrinter;
280   DiagnosticsEngine Diags;
281   SourceManager SourceMgr;
282   llvm::StringMap<Replacements> FileReplacements;
283   ClangTidyContext &Context;
284   bool ApplyFixes;
285   unsigned TotalFixes;
286   unsigned AppliedFixes;
287   unsigned WarningsAsErrors;
288 };
289
290 class ClangTidyASTConsumer : public MultiplexConsumer {
291 public:
292   ClangTidyASTConsumer(std::vector<std::unique_ptr<ASTConsumer>> Consumers,
293                        std::unique_ptr<ClangTidyProfiling> Profiling,
294                        std::unique_ptr<ast_matchers::MatchFinder> Finder,
295                        std::vector<std::unique_ptr<ClangTidyCheck>> Checks)
296       : MultiplexConsumer(std::move(Consumers)),
297         Profiling(std::move(Profiling)), Finder(std::move(Finder)),
298         Checks(std::move(Checks)) {}
299
300 private:
301   // Destructor order matters! Profiling must be destructed last.
302   // Or at least after Finder.
303   std::unique_ptr<ClangTidyProfiling> Profiling;
304   std::unique_ptr<ast_matchers::MatchFinder> Finder;
305   std::vector<std::unique_ptr<ClangTidyCheck>> Checks;
306 };
307
308 } // namespace
309
310 ClangTidyASTConsumerFactory::ClangTidyASTConsumerFactory(
311     ClangTidyContext &Context,
312     IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFS)
313     : Context(Context), OverlayFS(OverlayFS),
314       CheckFactories(new ClangTidyCheckFactories) {
315   for (ClangTidyModuleRegistry::iterator I = ClangTidyModuleRegistry::begin(),
316                                          E = ClangTidyModuleRegistry::end();
317        I != E; ++I) {
318     std::unique_ptr<ClangTidyModule> Module(I->instantiate());
319     Module->addCheckFactories(*CheckFactories);
320   }
321 }
322
323 #if CLANG_ENABLE_STATIC_ANALYZER
324 static void setStaticAnalyzerCheckerOpts(const ClangTidyOptions &Opts,
325                                          AnalyzerOptionsRef AnalyzerOptions) {
326   StringRef AnalyzerPrefix(AnalyzerCheckNamePrefix);
327   for (const auto &Opt : Opts.CheckOptions) {
328     StringRef OptName(Opt.first);
329     if (!OptName.startswith(AnalyzerPrefix))
330       continue;
331     AnalyzerOptions->Config[OptName.substr(AnalyzerPrefix.size())] = Opt.second;
332   }
333 }
334
335 typedef std::vector<std::pair<std::string, bool>> CheckersList;
336
337 static CheckersList getAnalyzerCheckersAndPackages(ClangTidyContext &Context,
338                                                    bool IncludeExperimental) {
339   CheckersList List;
340
341   const auto &RegisteredCheckers =
342       AnalyzerOptions::getRegisteredCheckers(IncludeExperimental);
343   bool AnalyzerChecksEnabled = false;
344   for (StringRef CheckName : RegisteredCheckers) {
345     std::string ClangTidyCheckName((AnalyzerCheckNamePrefix + CheckName).str());
346     AnalyzerChecksEnabled |= Context.isCheckEnabled(ClangTidyCheckName);
347   }
348
349   if (!AnalyzerChecksEnabled)
350     return List;
351
352   // List all static analyzer checkers that our filter enables.
353   //
354   // Always add all core checkers if any other static analyzer check is enabled.
355   // This is currently necessary, as other path sensitive checks rely on the
356   // core checkers.
357   for (StringRef CheckName : RegisteredCheckers) {
358     std::string ClangTidyCheckName((AnalyzerCheckNamePrefix + CheckName).str());
359
360     if (CheckName.startswith("core") ||
361         Context.isCheckEnabled(ClangTidyCheckName)) {
362       List.emplace_back(CheckName, true);
363     }
364   }
365   return List;
366 }
367 #endif // CLANG_ENABLE_STATIC_ANALYZER
368
369 std::unique_ptr<clang::ASTConsumer>
370 ClangTidyASTConsumerFactory::CreateASTConsumer(
371     clang::CompilerInstance &Compiler, StringRef File) {
372   // FIXME: Move this to a separate method, so that CreateASTConsumer doesn't
373   // modify Compiler.
374   SourceManager *SM = &Compiler.getSourceManager();
375   Context.setSourceManager(SM);
376   Context.setCurrentFile(File);
377   Context.setASTContext(&Compiler.getASTContext());
378
379   auto WorkingDir = Compiler.getSourceManager()
380                         .getFileManager()
381                         .getVirtualFileSystem()
382                         .getCurrentWorkingDirectory();
383   if (WorkingDir)
384     Context.setCurrentBuildDirectory(WorkingDir.get());
385
386   std::vector<std::unique_ptr<ClangTidyCheck>> Checks;
387   CheckFactories->createChecks(&Context, Checks);
388
389   ast_matchers::MatchFinder::MatchFinderOptions FinderOptions;
390
391   std::unique_ptr<ClangTidyProfiling> Profiling;
392   if (Context.getEnableProfiling()) {
393     Profiling = std::make_unique<ClangTidyProfiling>(
394         Context.getProfileStorageParams());
395     FinderOptions.CheckProfiling.emplace(Profiling->Records);
396   }
397
398   std::unique_ptr<ast_matchers::MatchFinder> Finder(
399       new ast_matchers::MatchFinder(std::move(FinderOptions)));
400
401   Preprocessor *PP = &Compiler.getPreprocessor();
402   Preprocessor *ModuleExpanderPP = PP;
403
404   if (Context.getLangOpts().Modules && OverlayFS != nullptr) {
405     auto ModuleExpander = std::make_unique<ExpandModularHeadersPPCallbacks>(
406         &Compiler, OverlayFS);
407     ModuleExpanderPP = ModuleExpander->getPreprocessor();
408     PP->addPPCallbacks(std::move(ModuleExpander));
409   }
410
411   for (auto &Check : Checks) {
412     Check->registerMatchers(&*Finder);
413     Check->registerPPCallbacks(*SM, PP, ModuleExpanderPP);
414   }
415
416   std::vector<std::unique_ptr<ASTConsumer>> Consumers;
417   if (!Checks.empty())
418     Consumers.push_back(Finder->newASTConsumer());
419
420 #if CLANG_ENABLE_STATIC_ANALYZER
421   AnalyzerOptionsRef AnalyzerOptions = Compiler.getAnalyzerOpts();
422   AnalyzerOptions->CheckersAndPackages = getAnalyzerCheckersAndPackages(
423       Context, Context.canEnableAnalyzerAlphaCheckers());
424   if (!AnalyzerOptions->CheckersAndPackages.empty()) {
425     setStaticAnalyzerCheckerOpts(Context.getOptions(), AnalyzerOptions);
426     AnalyzerOptions->AnalysisStoreOpt = RegionStoreModel;
427     AnalyzerOptions->AnalysisDiagOpt = PD_NONE;
428     AnalyzerOptions->AnalyzeNestedBlocks = true;
429     AnalyzerOptions->eagerlyAssumeBinOpBifurcation = true;
430     std::unique_ptr<ento::AnalysisASTConsumer> AnalysisConsumer =
431         ento::CreateAnalysisConsumer(Compiler);
432     AnalysisConsumer->AddDiagnosticConsumer(
433         new AnalyzerDiagnosticConsumer(Context));
434     Consumers.push_back(std::move(AnalysisConsumer));
435   }
436 #endif // CLANG_ENABLE_STATIC_ANALYZER
437   return std::make_unique<ClangTidyASTConsumer>(
438       std::move(Consumers), std::move(Profiling), std::move(Finder),
439       std::move(Checks));
440 }
441
442 std::vector<std::string> ClangTidyASTConsumerFactory::getCheckNames() {
443   std::vector<std::string> CheckNames;
444   for (const auto &CheckFactory : *CheckFactories) {
445     if (Context.isCheckEnabled(CheckFactory.first))
446       CheckNames.push_back(CheckFactory.first);
447   }
448
449 #if CLANG_ENABLE_STATIC_ANALYZER
450   for (const auto &AnalyzerCheck : getAnalyzerCheckersAndPackages(
451            Context, Context.canEnableAnalyzerAlphaCheckers()))
452     CheckNames.push_back(AnalyzerCheckNamePrefix + AnalyzerCheck.first);
453 #endif // CLANG_ENABLE_STATIC_ANALYZER
454
455   std::sort(CheckNames.begin(), CheckNames.end());
456   return CheckNames;
457 }
458
459 ClangTidyOptions::OptionMap ClangTidyASTConsumerFactory::getCheckOptions() {
460   ClangTidyOptions::OptionMap Options;
461   std::vector<std::unique_ptr<ClangTidyCheck>> Checks;
462   CheckFactories->createChecks(&Context, Checks);
463   for (const auto &Check : Checks)
464     Check->storeOptions(Options);
465   return Options;
466 }
467
468 std::vector<std::string>
469 getCheckNames(const ClangTidyOptions &Options,
470               bool AllowEnablingAnalyzerAlphaCheckers) {
471   clang::tidy::ClangTidyContext Context(
472       std::make_unique<DefaultOptionsProvider>(ClangTidyGlobalOptions(),
473                                                 Options),
474       AllowEnablingAnalyzerAlphaCheckers);
475   ClangTidyASTConsumerFactory Factory(Context);
476   return Factory.getCheckNames();
477 }
478
479 ClangTidyOptions::OptionMap
480 getCheckOptions(const ClangTidyOptions &Options,
481                 bool AllowEnablingAnalyzerAlphaCheckers) {
482   clang::tidy::ClangTidyContext Context(
483       std::make_unique<DefaultOptionsProvider>(ClangTidyGlobalOptions(),
484                                                 Options),
485       AllowEnablingAnalyzerAlphaCheckers);
486   ClangTidyASTConsumerFactory Factory(Context);
487   return Factory.getCheckOptions();
488 }
489
490 std::vector<ClangTidyError>
491 runClangTidy(clang::tidy::ClangTidyContext &Context,
492              const CompilationDatabase &Compilations,
493              ArrayRef<std::string> InputFiles,
494              llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS,
495              bool EnableCheckProfile, llvm::StringRef StoreCheckProfile) {
496   ClangTool Tool(Compilations, InputFiles,
497                  std::make_shared<PCHContainerOperations>(), BaseFS);
498
499   // Add extra arguments passed by the clang-tidy command-line.
500   ArgumentsAdjuster PerFileExtraArgumentsInserter =
501       [&Context](const CommandLineArguments &Args, StringRef Filename) {
502         ClangTidyOptions Opts = Context.getOptionsForFile(Filename);
503         CommandLineArguments AdjustedArgs = Args;
504         if (Opts.ExtraArgsBefore) {
505           auto I = AdjustedArgs.begin();
506           if (I != AdjustedArgs.end() && !StringRef(*I).startswith("-"))
507             ++I; // Skip compiler binary name, if it is there.
508           AdjustedArgs.insert(I, Opts.ExtraArgsBefore->begin(),
509                               Opts.ExtraArgsBefore->end());
510         }
511         if (Opts.ExtraArgs)
512           AdjustedArgs.insert(AdjustedArgs.end(), Opts.ExtraArgs->begin(),
513                               Opts.ExtraArgs->end());
514         return AdjustedArgs;
515       };
516
517   Tool.appendArgumentsAdjuster(PerFileExtraArgumentsInserter);
518   Tool.appendArgumentsAdjuster(getStripPluginsAdjuster());
519   Context.setEnableProfiling(EnableCheckProfile);
520   Context.setProfileStoragePrefix(StoreCheckProfile);
521
522   ClangTidyDiagnosticConsumer DiagConsumer(Context);
523   DiagnosticsEngine DE(new DiagnosticIDs(), new DiagnosticOptions(),
524                        &DiagConsumer, /*ShouldOwnClient=*/false);
525   Context.setDiagnosticsEngine(&DE);
526   Tool.setDiagnosticConsumer(&DiagConsumer);
527
528   class ActionFactory : public FrontendActionFactory {
529   public:
530     ActionFactory(ClangTidyContext &Context,
531                   IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> BaseFS)
532         : ConsumerFactory(Context, BaseFS) {}
533     std::unique_ptr<FrontendAction> create() override {
534       return std::make_unique<Action>(&ConsumerFactory);
535     }
536
537     bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
538                        FileManager *Files,
539                        std::shared_ptr<PCHContainerOperations> PCHContainerOps,
540                        DiagnosticConsumer *DiagConsumer) override {
541       // Explicitly set ProgramAction to RunAnalysis to make the preprocessor
542       // define __clang_analyzer__ macro. The frontend analyzer action will not
543       // be called here.
544       Invocation->getFrontendOpts().ProgramAction = frontend::RunAnalysis;
545       return FrontendActionFactory::runInvocation(
546           Invocation, Files, PCHContainerOps, DiagConsumer);
547     }
548
549   private:
550     class Action : public ASTFrontendAction {
551     public:
552       Action(ClangTidyASTConsumerFactory *Factory) : Factory(Factory) {}
553       std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
554                                                      StringRef File) override {
555         return Factory->CreateASTConsumer(Compiler, File);
556       }
557
558     private:
559       ClangTidyASTConsumerFactory *Factory;
560     };
561
562     ClangTidyASTConsumerFactory ConsumerFactory;
563   };
564
565   ActionFactory Factory(Context, BaseFS);
566   Tool.run(&Factory);
567   return DiagConsumer.take();
568 }
569
570 void handleErrors(llvm::ArrayRef<ClangTidyError> Errors,
571                   ClangTidyContext &Context, bool Fix,
572                   unsigned &WarningsAsErrorsCount,
573                   llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
574   ErrorReporter Reporter(Context, Fix, BaseFS);
575   llvm::vfs::FileSystem &FileSystem =
576       Reporter.getSourceManager().getFileManager().getVirtualFileSystem();
577   auto InitialWorkingDir = FileSystem.getCurrentWorkingDirectory();
578   if (!InitialWorkingDir)
579     llvm::report_fatal_error("Cannot get current working path.");
580
581   for (const ClangTidyError &Error : Errors) {
582     if (!Error.BuildDirectory.empty()) {
583       // By default, the working directory of file system is the current
584       // clang-tidy running directory.
585       //
586       // Change the directory to the one used during the analysis.
587       FileSystem.setCurrentWorkingDirectory(Error.BuildDirectory);
588     }
589     Reporter.reportDiagnostic(Error);
590     // Return to the initial directory to correctly resolve next Error.
591     FileSystem.setCurrentWorkingDirectory(InitialWorkingDir.get());
592   }
593   Reporter.Finish();
594   WarningsAsErrorsCount += Reporter.getWarningsAsErrorsCount();
595 }
596
597 void exportReplacements(const llvm::StringRef MainFilePath,
598                         const std::vector<ClangTidyError> &Errors,
599                         raw_ostream &OS) {
600   TranslationUnitDiagnostics TUD;
601   TUD.MainSourceFile = MainFilePath;
602   for (const auto &Error : Errors) {
603     tooling::Diagnostic Diag = Error;
604     TUD.Diagnostics.insert(TUD.Diagnostics.end(), Diag);
605   }
606
607   yaml::Output YAML(OS);
608   YAML << TUD;
609 }
610
611 } // namespace tidy
612 } // namespace clang