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(
42     PathRef File, ProjectInfo *Project) const {
43   if (auto CDB = getCDBForFile(File, Project)) {
44     auto Candidates = CDB->getCompileCommands(File);
45     if (!Candidates.empty()) {
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 std::pair<tooling::CompilationDatabase *, /*Cached*/ bool>
55 DirectoryBasedGlobalCompilationDatabase::getCDBInDirLocked(PathRef Dir) const {
56   // FIXME(ibiryukov): Invalidate cached compilation databases on changes
57   auto CachedIt = CompilationDatabases.find(Dir);
58   if (CachedIt != CompilationDatabases.end())
59     return {CachedIt->second.get(), true};
60   std::string Error = "";
61   auto CDB = tooling::CompilationDatabase::loadFromDirectory(Dir, Error);
62   auto Result = CDB.get();
63   CompilationDatabases.insert(std::make_pair(Dir, std::move(CDB)));
64   return {Result, false};
65 }
66 
67 tooling::CompilationDatabase *
68 DirectoryBasedGlobalCompilationDatabase::getCDBForFile(
69     PathRef File, ProjectInfo *Project) const {
70   namespace path = sys::path;
71   assert((path::is_absolute(File, path::Style::posix) ||
72           path::is_absolute(File, path::Style::windows)) &&
73          "path must be absolute");
74 
75   tooling::CompilationDatabase *CDB = nullptr;
76   bool Cached = false;
77   std::lock_guard<std::mutex> Lock(Mutex);
78   if (CompileCommandsDir) {
79     std::tie(CDB, Cached) = getCDBInDirLocked(*CompileCommandsDir);
80     if (Project && CDB)
81       Project->SourceRoot = *CompileCommandsDir;
82   } else {
83     for (auto Path = path::parent_path(File); !CDB && !Path.empty();
84          Path = path::parent_path(Path)) {
85       std::tie(CDB, Cached) = getCDBInDirLocked(Path);
86       if (Project && CDB)
87         Project->SourceRoot = Path;
88     }
89   }
90   // FIXME: getAllFiles() may return relative paths, we need absolute paths.
91   // Hopefully the fix is to change JSONCompilationDatabase and the interface.
92   if (CDB && !Cached)
93     OnCommandChanged.broadcast(CDB->getAllFiles());
94   return CDB;
95 }
96 
97 OverlayCDB::OverlayCDB(const GlobalCompilationDatabase *Base,
98                        std::vector<std::string> FallbackFlags)
99     : Base(Base), FallbackFlags(std::move(FallbackFlags)) {
100   if (Base)
101     BaseChanged = Base->watch([this](const std::vector<std::string> Changes) {
102       OnCommandChanged.broadcast(Changes);
103     });
104 }
105 
106 Optional<tooling::CompileCommand>
107 OverlayCDB::getCompileCommand(PathRef File, ProjectInfo *Project) const {
108   {
109     std::lock_guard<std::mutex> Lock(Mutex);
110     auto It = Commands.find(File);
111     if (It != Commands.end()) {
112       if (Project)
113         Project->SourceRoot = "";
114       return It->second;
115     }
116   }
117   return Base ? Base->getCompileCommand(File, Project) : None;
118 }
119 
120 tooling::CompileCommand OverlayCDB::getFallbackCommand(PathRef File) const {
121   auto Cmd = Base ? Base->getFallbackCommand(File)
122                   : GlobalCompilationDatabase::getFallbackCommand(File);
123   std::lock_guard<std::mutex> Lock(Mutex);
124   Cmd.CommandLine.insert(Cmd.CommandLine.end(), FallbackFlags.begin(),
125                          FallbackFlags.end());
126   return Cmd;
127 }
128 
129 void OverlayCDB::setCompileCommand(
130     PathRef File, llvm::Optional<tooling::CompileCommand> Cmd) {
131   {
132     std::unique_lock<std::mutex> Lock(Mutex);
133     if (Cmd)
134       Commands[File] = std::move(*Cmd);
135     else
136       Commands.erase(File);
137   }
138   OnCommandChanged.broadcast({File});
139 }
140 
141 } // namespace clangd
142 } // namespace clang
143