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 using namespace llvm;
17 namespace clang {
18 namespace clangd {
19 
20 tooling::CompileCommand
21 GlobalCompilationDatabase::getFallbackCommand(PathRef File) const {
22   std::vector<std::string> Argv = {"clang"};
23   // Clang treats .h files as C by default, resulting in unhelpful diagnostics.
24   // Parsing as Objective C++ is friendly to more cases.
25   if (sys::path::extension(File) == ".h")
26     Argv.push_back("-xobjective-c++-header");
27   Argv.push_back(File);
28   return tooling::CompileCommand(sys::path::parent_path(File),
29                                  sys::path::filename(File), std::move(Argv),
30                                  /*Output=*/"");
31 }
32 
33 DirectoryBasedGlobalCompilationDatabase::
34     DirectoryBasedGlobalCompilationDatabase(Optional<Path> CompileCommandsDir)
35     : CompileCommandsDir(std::move(CompileCommandsDir)) {}
36 
37 DirectoryBasedGlobalCompilationDatabase::
38     ~DirectoryBasedGlobalCompilationDatabase() = default;
39 
40 Optional<tooling::CompileCommand>
41 DirectoryBasedGlobalCompilationDatabase::getCompileCommand(PathRef File) const {
42   if (auto CDB = getCDBForFile(File)) {
43     auto Candidates = CDB->getCompileCommands(File);
44     if (!Candidates.empty()) {
45       addExtraFlags(File, Candidates.front());
46       return std::move(Candidates.front());
47     }
48   } else {
49     log("Failed to find compilation database for {0}", File);
50   }
51   return None;
52 }
53 
54 tooling::CompileCommand
55 DirectoryBasedGlobalCompilationDatabase::getFallbackCommand(
56     PathRef File) const {
57   auto C = GlobalCompilationDatabase::getFallbackCommand(File);
58   addExtraFlags(File, C);
59   return C;
60 }
61 
62 void DirectoryBasedGlobalCompilationDatabase::setCompileCommandsDir(Path P) {
63   std::lock_guard<std::mutex> Lock(Mutex);
64   CompileCommandsDir = P;
65   CompilationDatabases.clear();
66 }
67 
68 void DirectoryBasedGlobalCompilationDatabase::setExtraFlagsForFile(
69     PathRef File, std::vector<std::string> ExtraFlags) {
70   std::lock_guard<std::mutex> Lock(Mutex);
71   ExtraFlagsForFile[File] = std::move(ExtraFlags);
72 }
73 
74 void DirectoryBasedGlobalCompilationDatabase::addExtraFlags(
75     PathRef File, tooling::CompileCommand &C) const {
76   std::lock_guard<std::mutex> Lock(Mutex);
77 
78   auto It = ExtraFlagsForFile.find(File);
79   if (It == ExtraFlagsForFile.end())
80     return;
81 
82   auto &Args = C.CommandLine;
83   assert(Args.size() >= 2 && "Expected at least [compiler, source file]");
84   // The last argument of CommandLine is the name of the input file.
85   // Add ExtraFlags before it.
86   Args.insert(Args.end() - 1, It->second.begin(), It->second.end());
87 }
88 
89 tooling::CompilationDatabase *
90 DirectoryBasedGlobalCompilationDatabase::getCDBInDirLocked(PathRef Dir) const {
91   // FIXME(ibiryukov): Invalidate cached compilation databases on changes
92   auto CachedIt = CompilationDatabases.find(Dir);
93   if (CachedIt != CompilationDatabases.end())
94     return CachedIt->second.get();
95   std::string Error = "";
96   auto CDB = tooling::CompilationDatabase::loadFromDirectory(Dir, Error);
97   auto Result = CDB.get();
98   CompilationDatabases.insert(std::make_pair(Dir, std::move(CDB)));
99   return Result;
100 }
101 
102 tooling::CompilationDatabase *
103 DirectoryBasedGlobalCompilationDatabase::getCDBForFile(PathRef File) const {
104   namespace path = sys::path;
105   assert((path::is_absolute(File, path::Style::posix) ||
106           path::is_absolute(File, path::Style::windows)) &&
107          "path must be absolute");
108 
109   std::lock_guard<std::mutex> Lock(Mutex);
110   if (CompileCommandsDir)
111     return getCDBInDirLocked(*CompileCommandsDir);
112   for (auto Path = path::parent_path(File); !Path.empty();
113        Path = path::parent_path(Path))
114     if (auto CDB = getCDBInDirLocked(Path))
115       return CDB;
116   return nullptr;
117 }
118 
119 Optional<tooling::CompileCommand>
120 InMemoryCompilationDb::getCompileCommand(PathRef File) const {
121   std::lock_guard<std::mutex> Lock(Mutex);
122   auto It = Commands.find(File);
123   if (It == Commands.end())
124     return None;
125   return It->second;
126 }
127 
128 bool InMemoryCompilationDb::setCompilationCommandForFile(
129     PathRef File, tooling::CompileCommand CompilationCommand) {
130   std::unique_lock<std::mutex> Lock(Mutex);
131   auto ItInserted = Commands.insert(std::make_pair(File, CompilationCommand));
132   if (ItInserted.second)
133     return true;
134   ItInserted.first->setValue(std::move(CompilationCommand));
135   return false;
136 }
137 
138 void InMemoryCompilationDb::invalidate(PathRef File) {
139   std::unique_lock<std::mutex> Lock(Mutex);
140   Commands.erase(File);
141 }
142 
143 } // namespace clangd
144 } // namespace clang
145