1 //===--- GlobalCompilationDatabase.cpp --------------------------*- C++-*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===---------------------------------------------------------------------===//
9 
10 #include "GlobalCompilationDatabase.h"
11 #include "Logger.h"
12 #include "clang/Tooling/CompilationDatabase.h"
13 #include "llvm/Support/FileSystem.h"
14 #include "llvm/Support/Path.h"
15 
16 namespace clang {
17 namespace clangd {
18 
19 static void addExtraFlags(tooling::CompileCommand &Command,
20                           const std::vector<std::string> &ExtraFlags) {
21   if (ExtraFlags.empty())
22     return;
23   assert(Command.CommandLine.size() >= 2 &&
24          "Expected a command line containing at least 2 arguments, the "
25          "compiler binary and the output file");
26   // The last argument of CommandLine is the name of the input file.
27   // Add ExtraFlags before it.
28   auto It = Command.CommandLine.end();
29   --It;
30   Command.CommandLine.insert(It, ExtraFlags.begin(), ExtraFlags.end());
31 }
32 
33 tooling::CompileCommand getDefaultCompileCommand(PathRef File) {
34   std::vector<std::string> CommandLine{"clang", "-fsyntax-only", File.str()};
35   return tooling::CompileCommand(llvm::sys::path::parent_path(File),
36                                  llvm::sys::path::filename(File), CommandLine,
37                                  /*Output=*/"");
38 }
39 
40 DirectoryBasedGlobalCompilationDatabase::
41     DirectoryBasedGlobalCompilationDatabase(
42         clangd::Logger &Logger, llvm::Optional<Path> CompileCommandsDir)
43         : Logger(Logger), CompileCommandsDir(std::move(CompileCommandsDir)) {}
44 
45 std::vector<tooling::CompileCommand>
46 DirectoryBasedGlobalCompilationDatabase::getCompileCommands(PathRef File) {
47   std::vector<tooling::CompileCommand> Commands;
48 
49   auto CDB = getCompilationDatabase(File);
50   if (CDB)
51     Commands = CDB->getCompileCommands(File);
52   if (Commands.empty())
53     Commands.push_back(getDefaultCompileCommand(File));
54 
55   auto It = ExtraFlagsForFile.find(File);
56   if (It != ExtraFlagsForFile.end()) {
57     // Append the user-specified flags to the compile commands.
58     for (tooling::CompileCommand &Command : Commands)
59       addExtraFlags(Command, It->second);
60   }
61 
62   return Commands;
63 }
64 
65 void DirectoryBasedGlobalCompilationDatabase::setExtraFlagsForFile(
66     PathRef File, std::vector<std::string> ExtraFlags) {
67   ExtraFlagsForFile[File] = std::move(ExtraFlags);
68 }
69 
70 tooling::CompilationDatabase *
71 DirectoryBasedGlobalCompilationDatabase::tryLoadDatabaseFromPath(PathRef File) {
72 
73   namespace path = llvm::sys::path;
74   auto CachedIt = CompilationDatabases.find(File);
75 
76   assert((path::is_absolute(File, path::Style::posix) ||
77           path::is_absolute(File, path::Style::windows)) &&
78          "path must be absolute");
79 
80   if (CachedIt != CompilationDatabases.end())
81     return CachedIt->second.get();
82   std::string Error = "";
83   auto CDB = tooling::CompilationDatabase::loadFromDirectory(File, Error);
84   if (CDB && Error.empty()) {
85     auto Result = CDB.get();
86     CompilationDatabases.insert(std::make_pair(File, std::move(CDB)));
87     return Result;
88   }
89 
90   return nullptr;
91 }
92 
93 tooling::CompilationDatabase *
94 DirectoryBasedGlobalCompilationDatabase::getCompilationDatabase(PathRef File) {
95   std::lock_guard<std::mutex> Lock(Mutex);
96 
97   namespace path = llvm::sys::path;
98   if (CompileCommandsDir.hasValue()) {
99     tooling::CompilationDatabase *ReturnValue =
100         tryLoadDatabaseFromPath(CompileCommandsDir.getValue());
101     if (ReturnValue == nullptr)
102       Logger.log("Failed to find compilation database for " + Twine(File) +
103                  "in overriden directory " + CompileCommandsDir.getValue() +
104                  "\n");
105     return ReturnValue;
106   }
107 
108   for (auto Path = path::parent_path(File); !Path.empty();
109        Path = path::parent_path(Path)) {
110     auto CDB = tryLoadDatabaseFromPath(Path);
111     if (!CDB)
112       continue;
113     // FIXME(ibiryukov): Invalidate cached compilation databases on changes
114     return CDB;
115   }
116 
117   Logger.log("Failed to find compilation database for " + Twine(File) + "\n");
118   return nullptr;
119 }
120 
121 } // namespace clangd
122 } // namespace clang
123