xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/Tooling/DependencyScanning/DependencyScanningTool.cpp (revision 627f7eb200a4419d89b531d55fccd2ee3ffdcde0)
1 //===- DependencyScanningTool.cpp - clang-scan-deps service ---------------===//
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 #include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
10 #include "clang/Frontend/Utils.h"
11 
12 namespace clang{
13 namespace tooling{
14 namespace dependencies{
15 
16 DependencyScanningTool::DependencyScanningTool(
17     DependencyScanningService &Service,
18     const tooling::CompilationDatabase &Compilations)
19     : Worker(Service), Compilations(Compilations) {}
20 
21 llvm::Expected<std::string>
22 DependencyScanningTool::getDependencyFile(const std::string &Input,
23                                           StringRef CWD) {
24   /// Prints out all of the gathered dependencies into a string.
25   class DependencyPrinterConsumer : public DependencyConsumer {
26   public:
27     void handleFileDependency(const DependencyOutputOptions &Opts,
28                               StringRef File) override {
29       if (!this->Opts)
30         this->Opts = std::make_unique<DependencyOutputOptions>(Opts);
31       Dependencies.push_back(File);
32     }
33 
34     void printDependencies(std::string &S) {
35       if (!Opts)
36         return;
37 
38       class DependencyPrinter : public DependencyFileGenerator {
39       public:
40         DependencyPrinter(DependencyOutputOptions &Opts,
41                           ArrayRef<std::string> Dependencies)
42             : DependencyFileGenerator(Opts) {
43           for (const auto &Dep : Dependencies)
44             addDependency(Dep);
45         }
46 
47         void printDependencies(std::string &S) {
48           llvm::raw_string_ostream OS(S);
49           outputDependencyFile(OS);
50         }
51       };
52 
53       DependencyPrinter Generator(*Opts, Dependencies);
54       Generator.printDependencies(S);
55     }
56 
57   private:
58     std::unique_ptr<DependencyOutputOptions> Opts;
59     std::vector<std::string> Dependencies;
60   };
61 
62   DependencyPrinterConsumer Consumer;
63   auto Result =
64       Worker.computeDependencies(Input, CWD, Compilations, Consumer);
65   if (Result)
66     return std::move(Result);
67   std::string Output;
68   Consumer.printDependencies(Output);
69   return Output;
70 }
71 
72 } // end namespace dependencies
73 } // end namespace tooling
74 } // end namespace clang
75