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 std::string getFallbackClangPath() {
20   static int Dummy;
21   std::string ClangdExecutable =
22       llvm::sys::fs::getMainExecutable("clangd", (void *)&Dummy);
23   SmallString<128> ClangPath;
24   ClangPath = llvm::sys::path::parent_path(ClangdExecutable);
25   llvm::sys::path::append(ClangPath, "clang");
26   return ClangPath.str();
27 }
28 
29 tooling::CompileCommand
30 GlobalCompilationDatabase::getFallbackCommand(PathRef File) const {
31   std::vector<std::string> Argv = {getFallbackClangPath()};
32   // Clang treats .h files as C by default, resulting in unhelpful diagnostics.
33   // Parsing as Objective C++ is friendly to more cases.
34   if (llvm::sys::path::extension(File) == ".h")
35     Argv.push_back("-xobjective-c++-header");
36   Argv.push_back(File);
37   return tooling::CompileCommand(llvm::sys::path::parent_path(File),
38                                  llvm::sys::path::filename(File),
39                                  std::move(Argv),
40                                  /*Output=*/"");
41 }
42 
43 DirectoryBasedGlobalCompilationDatabase::
44     DirectoryBasedGlobalCompilationDatabase(
45         llvm::Optional<Path> CompileCommandsDir)
46     : CompileCommandsDir(std::move(CompileCommandsDir)) {}
47 
48 DirectoryBasedGlobalCompilationDatabase::
49     ~DirectoryBasedGlobalCompilationDatabase() = default;
50 
51 llvm::Optional<tooling::CompileCommand>
52 DirectoryBasedGlobalCompilationDatabase::getCompileCommand(
53     PathRef File, ProjectInfo *Project) const {
54   if (auto CDB = getCDBForFile(File, Project)) {
55     auto Candidates = CDB->getCompileCommands(File);
56     if (!Candidates.empty()) {
57       return std::move(Candidates.front());
58     }
59   } else {
60     log("Failed to find compilation database for {0}", File);
61   }
62   return None;
63 }
64 
65 std::pair<tooling::CompilationDatabase *, /*Cached*/ bool>
66 DirectoryBasedGlobalCompilationDatabase::getCDBInDirLocked(PathRef Dir) const {
67   // FIXME(ibiryukov): Invalidate cached compilation databases on changes
68   auto CachedIt = CompilationDatabases.find(Dir);
69   if (CachedIt != CompilationDatabases.end())
70     return {CachedIt->second.get(), true};
71   std::string Error = "";
72   auto CDB = tooling::CompilationDatabase::loadFromDirectory(Dir, Error);
73   auto Result = CDB.get();
74   CompilationDatabases.insert(std::make_pair(Dir, std::move(CDB)));
75   return {Result, false};
76 }
77 
78 tooling::CompilationDatabase *
79 DirectoryBasedGlobalCompilationDatabase::getCDBForFile(
80     PathRef File, ProjectInfo *Project) const {
81   namespace path = llvm::sys::path;
82   assert((path::is_absolute(File, path::Style::posix) ||
83           path::is_absolute(File, path::Style::windows)) &&
84          "path must be absolute");
85 
86   tooling::CompilationDatabase *CDB = nullptr;
87   bool Cached = false;
88   std::lock_guard<std::mutex> Lock(Mutex);
89   if (CompileCommandsDir) {
90     std::tie(CDB, Cached) = getCDBInDirLocked(*CompileCommandsDir);
91     if (Project && CDB)
92       Project->SourceRoot = *CompileCommandsDir;
93   } else {
94     for (auto Path = path::parent_path(File); !CDB && !Path.empty();
95          Path = path::parent_path(Path)) {
96       std::tie(CDB, Cached) = getCDBInDirLocked(Path);
97       if (Project && CDB)
98         Project->SourceRoot = Path;
99     }
100   }
101   // FIXME: getAllFiles() may return relative paths, we need absolute paths.
102   // Hopefully the fix is to change JSONCompilationDatabase and the interface.
103   if (CDB && !Cached)
104     OnCommandChanged.broadcast(CDB->getAllFiles());
105   return CDB;
106 }
107 
108 OverlayCDB::OverlayCDB(const GlobalCompilationDatabase *Base,
109                        std::vector<std::string> FallbackFlags)
110     : Base(Base), FallbackFlags(std::move(FallbackFlags)) {
111   if (Base)
112     BaseChanged = Base->watch([this](const std::vector<std::string> Changes) {
113       OnCommandChanged.broadcast(Changes);
114     });
115 }
116 
117 llvm::Optional<tooling::CompileCommand>
118 OverlayCDB::getCompileCommand(PathRef File, ProjectInfo *Project) const {
119   {
120     std::lock_guard<std::mutex> Lock(Mutex);
121     auto It = Commands.find(File);
122     if (It != Commands.end()) {
123       if (Project)
124         Project->SourceRoot = "";
125       return It->second;
126     }
127   }
128   return Base ? Base->getCompileCommand(File, Project) : None;
129 }
130 
131 tooling::CompileCommand OverlayCDB::getFallbackCommand(PathRef File) const {
132   auto Cmd = Base ? Base->getFallbackCommand(File)
133                   : GlobalCompilationDatabase::getFallbackCommand(File);
134   std::lock_guard<std::mutex> Lock(Mutex);
135   Cmd.CommandLine.insert(Cmd.CommandLine.end(), FallbackFlags.begin(),
136                          FallbackFlags.end());
137   return Cmd;
138 }
139 
140 void OverlayCDB::setCompileCommand(
141     PathRef File, llvm::Optional<tooling::CompileCommand> Cmd) {
142   {
143     std::unique_lock<std::mutex> Lock(Mutex);
144     if (Cmd)
145       Commands[File] = std::move(*Cmd);
146     else
147       Commands.erase(File);
148   }
149   OnCommandChanged.broadcast({File});
150 }
151 
152 } // namespace clangd
153 } // namespace clang
154