xref: /openbsd-src/gnu/llvm/clang/lib/Tooling/CompilationDatabase.cpp (revision a9ac8606c53d55cee9c3a39778b249c51df111ef)
1e5dd7070Spatrick //===- CompilationDatabase.cpp --------------------------------------------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick //  This file contains implementations of the CompilationDatabase base class
10e5dd7070Spatrick //  and the FixedCompilationDatabase.
11e5dd7070Spatrick //
12e5dd7070Spatrick //  FIXME: Various functions that take a string &ErrorMessage should be upgraded
13e5dd7070Spatrick //  to Expected.
14e5dd7070Spatrick //
15e5dd7070Spatrick //===----------------------------------------------------------------------===//
16e5dd7070Spatrick 
17e5dd7070Spatrick #include "clang/Tooling/CompilationDatabase.h"
18e5dd7070Spatrick #include "clang/Basic/Diagnostic.h"
19e5dd7070Spatrick #include "clang/Basic/DiagnosticIDs.h"
20e5dd7070Spatrick #include "clang/Basic/DiagnosticOptions.h"
21e5dd7070Spatrick #include "clang/Basic/LLVM.h"
22e5dd7070Spatrick #include "clang/Driver/Action.h"
23e5dd7070Spatrick #include "clang/Driver/Compilation.h"
24e5dd7070Spatrick #include "clang/Driver/Driver.h"
25e5dd7070Spatrick #include "clang/Driver/DriverDiagnostic.h"
26e5dd7070Spatrick #include "clang/Driver/Job.h"
27e5dd7070Spatrick #include "clang/Frontend/TextDiagnosticPrinter.h"
28e5dd7070Spatrick #include "clang/Tooling/CompilationDatabasePluginRegistry.h"
29e5dd7070Spatrick #include "clang/Tooling/Tooling.h"
30e5dd7070Spatrick #include "llvm/ADT/ArrayRef.h"
31e5dd7070Spatrick #include "llvm/ADT/IntrusiveRefCntPtr.h"
32e5dd7070Spatrick #include "llvm/ADT/STLExtras.h"
33e5dd7070Spatrick #include "llvm/ADT/SmallString.h"
34e5dd7070Spatrick #include "llvm/ADT/SmallVector.h"
35e5dd7070Spatrick #include "llvm/ADT/StringRef.h"
36e5dd7070Spatrick #include "llvm/Option/Arg.h"
37e5dd7070Spatrick #include "llvm/Support/Casting.h"
38e5dd7070Spatrick #include "llvm/Support/Compiler.h"
39e5dd7070Spatrick #include "llvm/Support/ErrorOr.h"
40e5dd7070Spatrick #include "llvm/Support/Host.h"
41e5dd7070Spatrick #include "llvm/Support/LineIterator.h"
42e5dd7070Spatrick #include "llvm/Support/MemoryBuffer.h"
43e5dd7070Spatrick #include "llvm/Support/Path.h"
44e5dd7070Spatrick #include "llvm/Support/raw_ostream.h"
45e5dd7070Spatrick #include <algorithm>
46e5dd7070Spatrick #include <cassert>
47e5dd7070Spatrick #include <cstring>
48e5dd7070Spatrick #include <iterator>
49e5dd7070Spatrick #include <memory>
50e5dd7070Spatrick #include <sstream>
51e5dd7070Spatrick #include <string>
52e5dd7070Spatrick #include <system_error>
53e5dd7070Spatrick #include <utility>
54e5dd7070Spatrick #include <vector>
55e5dd7070Spatrick 
56e5dd7070Spatrick using namespace clang;
57e5dd7070Spatrick using namespace tooling;
58e5dd7070Spatrick 
59e5dd7070Spatrick LLVM_INSTANTIATE_REGISTRY(CompilationDatabasePluginRegistry)
60e5dd7070Spatrick 
61e5dd7070Spatrick CompilationDatabase::~CompilationDatabase() = default;
62e5dd7070Spatrick 
63e5dd7070Spatrick std::unique_ptr<CompilationDatabase>
loadFromDirectory(StringRef BuildDirectory,std::string & ErrorMessage)64e5dd7070Spatrick CompilationDatabase::loadFromDirectory(StringRef BuildDirectory,
65e5dd7070Spatrick                                        std::string &ErrorMessage) {
66e5dd7070Spatrick   llvm::raw_string_ostream ErrorStream(ErrorMessage);
67ec727ea7Spatrick   for (const CompilationDatabasePluginRegistry::entry &Database :
68ec727ea7Spatrick        CompilationDatabasePluginRegistry::entries()) {
69e5dd7070Spatrick     std::string DatabaseErrorMessage;
70ec727ea7Spatrick     std::unique_ptr<CompilationDatabasePlugin> Plugin(Database.instantiate());
71e5dd7070Spatrick     if (std::unique_ptr<CompilationDatabase> DB =
72e5dd7070Spatrick             Plugin->loadFromDirectory(BuildDirectory, DatabaseErrorMessage))
73e5dd7070Spatrick       return DB;
74ec727ea7Spatrick     ErrorStream << Database.getName() << ": " << DatabaseErrorMessage << "\n";
75e5dd7070Spatrick   }
76e5dd7070Spatrick   return nullptr;
77e5dd7070Spatrick }
78e5dd7070Spatrick 
79e5dd7070Spatrick static std::unique_ptr<CompilationDatabase>
findCompilationDatabaseFromDirectory(StringRef Directory,std::string & ErrorMessage)80e5dd7070Spatrick findCompilationDatabaseFromDirectory(StringRef Directory,
81e5dd7070Spatrick                                      std::string &ErrorMessage) {
82e5dd7070Spatrick   std::stringstream ErrorStream;
83e5dd7070Spatrick   bool HasErrorMessage = false;
84e5dd7070Spatrick   while (!Directory.empty()) {
85e5dd7070Spatrick     std::string LoadErrorMessage;
86e5dd7070Spatrick 
87e5dd7070Spatrick     if (std::unique_ptr<CompilationDatabase> DB =
88e5dd7070Spatrick             CompilationDatabase::loadFromDirectory(Directory, LoadErrorMessage))
89e5dd7070Spatrick       return DB;
90e5dd7070Spatrick 
91e5dd7070Spatrick     if (!HasErrorMessage) {
92e5dd7070Spatrick       ErrorStream << "No compilation database found in " << Directory.str()
93e5dd7070Spatrick                   << " or any parent directory\n" << LoadErrorMessage;
94e5dd7070Spatrick       HasErrorMessage = true;
95e5dd7070Spatrick     }
96e5dd7070Spatrick 
97e5dd7070Spatrick     Directory = llvm::sys::path::parent_path(Directory);
98e5dd7070Spatrick   }
99e5dd7070Spatrick   ErrorMessage = ErrorStream.str();
100e5dd7070Spatrick   return nullptr;
101e5dd7070Spatrick }
102e5dd7070Spatrick 
103e5dd7070Spatrick std::unique_ptr<CompilationDatabase>
autoDetectFromSource(StringRef SourceFile,std::string & ErrorMessage)104e5dd7070Spatrick CompilationDatabase::autoDetectFromSource(StringRef SourceFile,
105e5dd7070Spatrick                                           std::string &ErrorMessage) {
106e5dd7070Spatrick   SmallString<1024> AbsolutePath(getAbsolutePath(SourceFile));
107e5dd7070Spatrick   StringRef Directory = llvm::sys::path::parent_path(AbsolutePath);
108e5dd7070Spatrick 
109e5dd7070Spatrick   std::unique_ptr<CompilationDatabase> DB =
110e5dd7070Spatrick       findCompilationDatabaseFromDirectory(Directory, ErrorMessage);
111e5dd7070Spatrick 
112e5dd7070Spatrick   if (!DB)
113e5dd7070Spatrick     ErrorMessage = ("Could not auto-detect compilation database for file \"" +
114e5dd7070Spatrick                    SourceFile + "\"\n" + ErrorMessage).str();
115e5dd7070Spatrick   return DB;
116e5dd7070Spatrick }
117e5dd7070Spatrick 
118e5dd7070Spatrick std::unique_ptr<CompilationDatabase>
autoDetectFromDirectory(StringRef SourceDir,std::string & ErrorMessage)119e5dd7070Spatrick CompilationDatabase::autoDetectFromDirectory(StringRef SourceDir,
120e5dd7070Spatrick                                              std::string &ErrorMessage) {
121e5dd7070Spatrick   SmallString<1024> AbsolutePath(getAbsolutePath(SourceDir));
122e5dd7070Spatrick 
123e5dd7070Spatrick   std::unique_ptr<CompilationDatabase> DB =
124e5dd7070Spatrick       findCompilationDatabaseFromDirectory(AbsolutePath, ErrorMessage);
125e5dd7070Spatrick 
126e5dd7070Spatrick   if (!DB)
127e5dd7070Spatrick     ErrorMessage = ("Could not auto-detect compilation database from directory \"" +
128e5dd7070Spatrick                    SourceDir + "\"\n" + ErrorMessage).str();
129e5dd7070Spatrick   return DB;
130e5dd7070Spatrick }
131e5dd7070Spatrick 
getAllCompileCommands() const132e5dd7070Spatrick std::vector<CompileCommand> CompilationDatabase::getAllCompileCommands() const {
133e5dd7070Spatrick   std::vector<CompileCommand> Result;
134e5dd7070Spatrick   for (const auto &File : getAllFiles()) {
135e5dd7070Spatrick     auto C = getCompileCommands(File);
136e5dd7070Spatrick     std::move(C.begin(), C.end(), std::back_inserter(Result));
137e5dd7070Spatrick   }
138e5dd7070Spatrick   return Result;
139e5dd7070Spatrick }
140e5dd7070Spatrick 
141e5dd7070Spatrick CompilationDatabasePlugin::~CompilationDatabasePlugin() = default;
142e5dd7070Spatrick 
143e5dd7070Spatrick namespace {
144e5dd7070Spatrick 
145e5dd7070Spatrick // Helper for recursively searching through a chain of actions and collecting
146e5dd7070Spatrick // all inputs, direct and indirect, of compile jobs.
147e5dd7070Spatrick struct CompileJobAnalyzer {
148e5dd7070Spatrick   SmallVector<std::string, 2> Inputs;
149e5dd7070Spatrick 
run__anon92ea00d00111::CompileJobAnalyzer150e5dd7070Spatrick   void run(const driver::Action *A) {
151e5dd7070Spatrick     runImpl(A, false);
152e5dd7070Spatrick   }
153e5dd7070Spatrick 
154e5dd7070Spatrick private:
runImpl__anon92ea00d00111::CompileJobAnalyzer155e5dd7070Spatrick   void runImpl(const driver::Action *A, bool Collect) {
156e5dd7070Spatrick     bool CollectChildren = Collect;
157e5dd7070Spatrick     switch (A->getKind()) {
158e5dd7070Spatrick     case driver::Action::CompileJobClass:
159e5dd7070Spatrick       CollectChildren = true;
160e5dd7070Spatrick       break;
161e5dd7070Spatrick 
162e5dd7070Spatrick     case driver::Action::InputClass:
163e5dd7070Spatrick       if (Collect) {
164e5dd7070Spatrick         const auto *IA = cast<driver::InputAction>(A);
165ec727ea7Spatrick         Inputs.push_back(std::string(IA->getInputArg().getSpelling()));
166e5dd7070Spatrick       }
167e5dd7070Spatrick       break;
168e5dd7070Spatrick 
169e5dd7070Spatrick     default:
170e5dd7070Spatrick       // Don't care about others
171e5dd7070Spatrick       break;
172e5dd7070Spatrick     }
173e5dd7070Spatrick 
174e5dd7070Spatrick     for (const driver::Action *AI : A->inputs())
175e5dd7070Spatrick       runImpl(AI, CollectChildren);
176e5dd7070Spatrick   }
177e5dd7070Spatrick };
178e5dd7070Spatrick 
179e5dd7070Spatrick // Special DiagnosticConsumer that looks for warn_drv_input_file_unused
180e5dd7070Spatrick // diagnostics from the driver and collects the option strings for those unused
181e5dd7070Spatrick // options.
182e5dd7070Spatrick class UnusedInputDiagConsumer : public DiagnosticConsumer {
183e5dd7070Spatrick public:
UnusedInputDiagConsumer(DiagnosticConsumer & Other)184e5dd7070Spatrick   UnusedInputDiagConsumer(DiagnosticConsumer &Other) : Other(Other) {}
185e5dd7070Spatrick 
HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,const Diagnostic & Info)186e5dd7070Spatrick   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
187e5dd7070Spatrick                         const Diagnostic &Info) override {
188e5dd7070Spatrick     if (Info.getID() == diag::warn_drv_input_file_unused) {
189e5dd7070Spatrick       // Arg 1 for this diagnostic is the option that didn't get used.
190e5dd7070Spatrick       UnusedInputs.push_back(Info.getArgStdStr(0));
191e5dd7070Spatrick     } else if (DiagLevel >= DiagnosticsEngine::Error) {
192e5dd7070Spatrick       // If driver failed to create compilation object, show the diagnostics
193e5dd7070Spatrick       // to user.
194e5dd7070Spatrick       Other.HandleDiagnostic(DiagLevel, Info);
195e5dd7070Spatrick     }
196e5dd7070Spatrick   }
197e5dd7070Spatrick 
198e5dd7070Spatrick   DiagnosticConsumer &Other;
199e5dd7070Spatrick   SmallVector<std::string, 2> UnusedInputs;
200e5dd7070Spatrick };
201e5dd7070Spatrick 
202e5dd7070Spatrick // Filter of tools unused flags such as -no-integrated-as and -Wa,*.
203e5dd7070Spatrick // They are not used for syntax checking, and could confuse targets
204e5dd7070Spatrick // which don't support these options.
205e5dd7070Spatrick struct FilterUnusedFlags {
operator ()__anon92ea00d00111::FilterUnusedFlags206e5dd7070Spatrick   bool operator() (StringRef S) {
207e5dd7070Spatrick     return (S == "-no-integrated-as") || S.startswith("-Wa,");
208e5dd7070Spatrick   }
209e5dd7070Spatrick };
210e5dd7070Spatrick 
GetClangToolCommand()211e5dd7070Spatrick std::string GetClangToolCommand() {
212e5dd7070Spatrick   static int Dummy;
213e5dd7070Spatrick   std::string ClangExecutable =
214e5dd7070Spatrick       llvm::sys::fs::getMainExecutable("clang", (void *)&Dummy);
215e5dd7070Spatrick   SmallString<128> ClangToolPath;
216e5dd7070Spatrick   ClangToolPath = llvm::sys::path::parent_path(ClangExecutable);
217e5dd7070Spatrick   llvm::sys::path::append(ClangToolPath, "clang-tool");
218ec727ea7Spatrick   return std::string(ClangToolPath.str());
219e5dd7070Spatrick }
220e5dd7070Spatrick 
221e5dd7070Spatrick } // namespace
222e5dd7070Spatrick 
223e5dd7070Spatrick /// Strips any positional args and possible argv[0] from a command-line
224e5dd7070Spatrick /// provided by the user to construct a FixedCompilationDatabase.
225e5dd7070Spatrick ///
226e5dd7070Spatrick /// FixedCompilationDatabase requires a command line to be in this format as it
227e5dd7070Spatrick /// constructs the command line for each file by appending the name of the file
228e5dd7070Spatrick /// to be compiled. FixedCompilationDatabase also adds its own argv[0] to the
229e5dd7070Spatrick /// start of the command line although its value is not important as it's just
230e5dd7070Spatrick /// ignored by the Driver invoked by the ClangTool using the
231e5dd7070Spatrick /// FixedCompilationDatabase.
232e5dd7070Spatrick ///
233e5dd7070Spatrick /// FIXME: This functionality should probably be made available by
234e5dd7070Spatrick /// clang::driver::Driver although what the interface should look like is not
235e5dd7070Spatrick /// clear.
236e5dd7070Spatrick ///
237e5dd7070Spatrick /// \param[in] Args Args as provided by the user.
238e5dd7070Spatrick /// \return Resulting stripped command line.
239e5dd7070Spatrick ///          \li true if successful.
240e5dd7070Spatrick ///          \li false if \c Args cannot be used for compilation jobs (e.g.
241e5dd7070Spatrick ///          contains an option like -E or -version).
stripPositionalArgs(std::vector<const char * > Args,std::vector<std::string> & Result,std::string & ErrorMsg)242e5dd7070Spatrick static bool stripPositionalArgs(std::vector<const char *> Args,
243e5dd7070Spatrick                                 std::vector<std::string> &Result,
244e5dd7070Spatrick                                 std::string &ErrorMsg) {
245e5dd7070Spatrick   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
246e5dd7070Spatrick   llvm::raw_string_ostream Output(ErrorMsg);
247e5dd7070Spatrick   TextDiagnosticPrinter DiagnosticPrinter(Output, &*DiagOpts);
248e5dd7070Spatrick   UnusedInputDiagConsumer DiagClient(DiagnosticPrinter);
249e5dd7070Spatrick   DiagnosticsEngine Diagnostics(
250e5dd7070Spatrick       IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()),
251e5dd7070Spatrick       &*DiagOpts, &DiagClient, false);
252e5dd7070Spatrick 
253e5dd7070Spatrick   // The clang executable path isn't required since the jobs the driver builds
254e5dd7070Spatrick   // will not be executed.
255e5dd7070Spatrick   std::unique_ptr<driver::Driver> NewDriver(new driver::Driver(
256e5dd7070Spatrick       /* ClangExecutable= */ "", llvm::sys::getDefaultTargetTriple(),
257e5dd7070Spatrick       Diagnostics));
258e5dd7070Spatrick   NewDriver->setCheckInputsExist(false);
259e5dd7070Spatrick 
260e5dd7070Spatrick   // This becomes the new argv[0]. The value is used to detect libc++ include
261e5dd7070Spatrick   // dirs on Mac, it isn't used for other platforms.
262e5dd7070Spatrick   std::string Argv0 = GetClangToolCommand();
263e5dd7070Spatrick   Args.insert(Args.begin(), Argv0.c_str());
264e5dd7070Spatrick 
265e5dd7070Spatrick   // By adding -c, we force the driver to treat compilation as the last phase.
266e5dd7070Spatrick   // It will then issue warnings via Diagnostics about un-used options that
267e5dd7070Spatrick   // would have been used for linking. If the user provided a compiler name as
268e5dd7070Spatrick   // the original argv[0], this will be treated as a linker input thanks to
269e5dd7070Spatrick   // insertng a new argv[0] above. All un-used options get collected by
270e5dd7070Spatrick   // UnusedInputdiagConsumer and get stripped out later.
271e5dd7070Spatrick   Args.push_back("-c");
272e5dd7070Spatrick 
273e5dd7070Spatrick   // Put a dummy C++ file on to ensure there's at least one compile job for the
274e5dd7070Spatrick   // driver to construct. If the user specified some other argument that
275e5dd7070Spatrick   // prevents compilation, e.g. -E or something like -version, we may still end
276e5dd7070Spatrick   // up with no jobs but then this is the user's fault.
277e5dd7070Spatrick   Args.push_back("placeholder.cpp");
278e5dd7070Spatrick 
279*a9ac8606Spatrick   llvm::erase_if(Args, FilterUnusedFlags());
280e5dd7070Spatrick 
281e5dd7070Spatrick   const std::unique_ptr<driver::Compilation> Compilation(
282e5dd7070Spatrick       NewDriver->BuildCompilation(Args));
283e5dd7070Spatrick   if (!Compilation)
284e5dd7070Spatrick     return false;
285e5dd7070Spatrick 
286e5dd7070Spatrick   const driver::JobList &Jobs = Compilation->getJobs();
287e5dd7070Spatrick 
288e5dd7070Spatrick   CompileJobAnalyzer CompileAnalyzer;
289e5dd7070Spatrick 
290e5dd7070Spatrick   for (const auto &Cmd : Jobs) {
291e5dd7070Spatrick     // Collect only for Assemble, Backend, and Compile jobs. If we do all jobs
292e5dd7070Spatrick     // we get duplicates since Link jobs point to Assemble jobs as inputs.
293e5dd7070Spatrick     // -flto* flags make the BackendJobClass, which still needs analyzer.
294e5dd7070Spatrick     if (Cmd.getSource().getKind() == driver::Action::AssembleJobClass ||
295e5dd7070Spatrick         Cmd.getSource().getKind() == driver::Action::BackendJobClass ||
296e5dd7070Spatrick         Cmd.getSource().getKind() == driver::Action::CompileJobClass) {
297e5dd7070Spatrick       CompileAnalyzer.run(&Cmd.getSource());
298e5dd7070Spatrick     }
299e5dd7070Spatrick   }
300e5dd7070Spatrick 
301e5dd7070Spatrick   if (CompileAnalyzer.Inputs.empty()) {
302e5dd7070Spatrick     ErrorMsg = "warning: no compile jobs found\n";
303e5dd7070Spatrick     return false;
304e5dd7070Spatrick   }
305e5dd7070Spatrick 
306*a9ac8606Spatrick   // Remove all compilation input files from the command line and inputs deemed
307*a9ac8606Spatrick   // unused for compilation. This is necessary so that getCompileCommands() can
308*a9ac8606Spatrick   // construct a command line for each file.
309*a9ac8606Spatrick   std::vector<const char *>::iterator End =
310*a9ac8606Spatrick       llvm::remove_if(Args, [&](StringRef S) {
311*a9ac8606Spatrick         return llvm::is_contained(CompileAnalyzer.Inputs, S) ||
312*a9ac8606Spatrick                llvm::is_contained(DiagClient.UnusedInputs, S);
313*a9ac8606Spatrick       });
314e5dd7070Spatrick   // Remove the -c add above as well. It will be at the end right now.
315e5dd7070Spatrick   assert(strcmp(*(End - 1), "-c") == 0);
316e5dd7070Spatrick   --End;
317e5dd7070Spatrick 
318e5dd7070Spatrick   Result = std::vector<std::string>(Args.begin() + 1, End);
319e5dd7070Spatrick   return true;
320e5dd7070Spatrick }
321e5dd7070Spatrick 
322e5dd7070Spatrick std::unique_ptr<FixedCompilationDatabase>
loadFromCommandLine(int & Argc,const char * const * Argv,std::string & ErrorMsg,const Twine & Directory)323e5dd7070Spatrick FixedCompilationDatabase::loadFromCommandLine(int &Argc,
324e5dd7070Spatrick                                               const char *const *Argv,
325e5dd7070Spatrick                                               std::string &ErrorMsg,
326*a9ac8606Spatrick                                               const Twine &Directory) {
327e5dd7070Spatrick   ErrorMsg.clear();
328e5dd7070Spatrick   if (Argc == 0)
329e5dd7070Spatrick     return nullptr;
330e5dd7070Spatrick   const char *const *DoubleDash = std::find(Argv, Argv + Argc, StringRef("--"));
331e5dd7070Spatrick   if (DoubleDash == Argv + Argc)
332e5dd7070Spatrick     return nullptr;
333e5dd7070Spatrick   std::vector<const char *> CommandLine(DoubleDash + 1, Argv + Argc);
334e5dd7070Spatrick   Argc = DoubleDash - Argv;
335e5dd7070Spatrick 
336e5dd7070Spatrick   std::vector<std::string> StrippedArgs;
337e5dd7070Spatrick   if (!stripPositionalArgs(CommandLine, StrippedArgs, ErrorMsg))
338e5dd7070Spatrick     return nullptr;
339e5dd7070Spatrick   return std::make_unique<FixedCompilationDatabase>(Directory, StrippedArgs);
340e5dd7070Spatrick }
341e5dd7070Spatrick 
342e5dd7070Spatrick std::unique_ptr<FixedCompilationDatabase>
loadFromFile(StringRef Path,std::string & ErrorMsg)343e5dd7070Spatrick FixedCompilationDatabase::loadFromFile(StringRef Path, std::string &ErrorMsg) {
344e5dd7070Spatrick   ErrorMsg.clear();
345e5dd7070Spatrick   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> File =
346e5dd7070Spatrick       llvm::MemoryBuffer::getFile(Path);
347e5dd7070Spatrick   if (std::error_code Result = File.getError()) {
348e5dd7070Spatrick     ErrorMsg = "Error while opening fixed database: " + Result.message();
349e5dd7070Spatrick     return nullptr;
350e5dd7070Spatrick   }
351*a9ac8606Spatrick   return loadFromBuffer(llvm::sys::path::parent_path(Path),
352*a9ac8606Spatrick                         (*File)->getBuffer(), ErrorMsg);
353*a9ac8606Spatrick }
354*a9ac8606Spatrick 
355*a9ac8606Spatrick std::unique_ptr<FixedCompilationDatabase>
loadFromBuffer(StringRef Directory,StringRef Data,std::string & ErrorMsg)356*a9ac8606Spatrick FixedCompilationDatabase::loadFromBuffer(StringRef Directory, StringRef Data,
357*a9ac8606Spatrick                                          std::string &ErrorMsg) {
358*a9ac8606Spatrick   ErrorMsg.clear();
359ec727ea7Spatrick   std::vector<std::string> Args;
360*a9ac8606Spatrick   StringRef Line;
361*a9ac8606Spatrick   while (!Data.empty()) {
362*a9ac8606Spatrick     std::tie(Line, Data) = Data.split('\n');
363ec727ea7Spatrick     // Stray whitespace is almost certainly unintended.
364ec727ea7Spatrick     Line = Line.trim();
365ec727ea7Spatrick     if (!Line.empty())
366ec727ea7Spatrick       Args.push_back(Line.str());
367ec727ea7Spatrick   }
368*a9ac8606Spatrick   return std::make_unique<FixedCompilationDatabase>(Directory, std::move(Args));
369e5dd7070Spatrick }
370e5dd7070Spatrick 
FixedCompilationDatabase(const Twine & Directory,ArrayRef<std::string> CommandLine)371*a9ac8606Spatrick FixedCompilationDatabase::FixedCompilationDatabase(
372*a9ac8606Spatrick     const Twine &Directory, ArrayRef<std::string> CommandLine) {
373e5dd7070Spatrick   std::vector<std::string> ToolCommandLine(1, GetClangToolCommand());
374e5dd7070Spatrick   ToolCommandLine.insert(ToolCommandLine.end(),
375e5dd7070Spatrick                          CommandLine.begin(), CommandLine.end());
376e5dd7070Spatrick   CompileCommands.emplace_back(Directory, StringRef(),
377e5dd7070Spatrick                                std::move(ToolCommandLine),
378e5dd7070Spatrick                                StringRef());
379e5dd7070Spatrick }
380e5dd7070Spatrick 
381e5dd7070Spatrick std::vector<CompileCommand>
getCompileCommands(StringRef FilePath) const382e5dd7070Spatrick FixedCompilationDatabase::getCompileCommands(StringRef FilePath) const {
383e5dd7070Spatrick   std::vector<CompileCommand> Result(CompileCommands);
384ec727ea7Spatrick   Result[0].CommandLine.push_back(std::string(FilePath));
385ec727ea7Spatrick   Result[0].Filename = std::string(FilePath);
386e5dd7070Spatrick   return Result;
387e5dd7070Spatrick }
388e5dd7070Spatrick 
389e5dd7070Spatrick namespace {
390e5dd7070Spatrick 
391e5dd7070Spatrick class FixedCompilationDatabasePlugin : public CompilationDatabasePlugin {
392e5dd7070Spatrick   std::unique_ptr<CompilationDatabase>
loadFromDirectory(StringRef Directory,std::string & ErrorMessage)393e5dd7070Spatrick   loadFromDirectory(StringRef Directory, std::string &ErrorMessage) override {
394e5dd7070Spatrick     SmallString<1024> DatabasePath(Directory);
395e5dd7070Spatrick     llvm::sys::path::append(DatabasePath, "compile_flags.txt");
396e5dd7070Spatrick     return FixedCompilationDatabase::loadFromFile(DatabasePath, ErrorMessage);
397e5dd7070Spatrick   }
398e5dd7070Spatrick };
399e5dd7070Spatrick 
400e5dd7070Spatrick } // namespace
401e5dd7070Spatrick 
402e5dd7070Spatrick static CompilationDatabasePluginRegistry::Add<FixedCompilationDatabasePlugin>
403e5dd7070Spatrick X("fixed-compilation-database", "Reads plain-text flags file");
404e5dd7070Spatrick 
405e5dd7070Spatrick namespace clang {
406e5dd7070Spatrick namespace tooling {
407e5dd7070Spatrick 
408e5dd7070Spatrick // This anchor is used to force the linker to link in the generated object file
409e5dd7070Spatrick // and thus register the JSONCompilationDatabasePlugin.
410e5dd7070Spatrick extern volatile int JSONAnchorSource;
411e5dd7070Spatrick static int LLVM_ATTRIBUTE_UNUSED JSONAnchorDest = JSONAnchorSource;
412e5dd7070Spatrick 
413e5dd7070Spatrick } // namespace tooling
414e5dd7070Spatrick } // namespace clang
415