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::setExtraFlagsForFile(
63     PathRef File, std::vector<std::string> ExtraFlags) {
64   std::lock_guard<std::mutex> Lock(Mutex);
65   ExtraFlagsForFile[File] = std::move(ExtraFlags);
66 }
67 
68 void DirectoryBasedGlobalCompilationDatabase::addExtraFlags(
69     PathRef File, tooling::CompileCommand &C) const {
70   std::lock_guard<std::mutex> Lock(Mutex);
71 
72   auto It = ExtraFlagsForFile.find(File);
73   if (It == ExtraFlagsForFile.end())
74     return;
75 
76   auto &Args = C.CommandLine;
77   assert(Args.size() >= 2 && "Expected at least [compiler, source file]");
78   // The last argument of CommandLine is the name of the input file.
79   // Add ExtraFlags before it.
80   Args.insert(Args.end() - 1, It->second.begin(), It->second.end());
81 }
82 
83 tooling::CompilationDatabase *
84 DirectoryBasedGlobalCompilationDatabase::getCDBInDirLocked(PathRef Dir) const {
85   // FIXME(ibiryukov): Invalidate cached compilation databases on changes
86   auto CachedIt = CompilationDatabases.find(Dir);
87   if (CachedIt != CompilationDatabases.end())
88     return CachedIt->second.get();
89   std::string Error = "";
90   auto CDB = tooling::CompilationDatabase::loadFromDirectory(Dir, Error);
91   auto Result = CDB.get();
92   CompilationDatabases.insert(std::make_pair(Dir, std::move(CDB)));
93   return Result;
94 }
95 
96 tooling::CompilationDatabase *
97 DirectoryBasedGlobalCompilationDatabase::getCDBForFile(PathRef File) const {
98   namespace path = sys::path;
99   assert((path::is_absolute(File, path::Style::posix) ||
100           path::is_absolute(File, path::Style::windows)) &&
101          "path must be absolute");
102 
103   std::lock_guard<std::mutex> Lock(Mutex);
104   if (CompileCommandsDir)
105     return getCDBInDirLocked(*CompileCommandsDir);
106   for (auto Path = path::parent_path(File); !Path.empty();
107        Path = path::parent_path(Path))
108     if (auto CDB = getCDBInDirLocked(Path))
109       return CDB;
110   return nullptr;
111 }
112 
113 Optional<tooling::CompileCommand>
114 InMemoryCompilationDb::getCompileCommand(PathRef File) const {
115   std::lock_guard<std::mutex> Lock(Mutex);
116   auto It = Commands.find(File);
117   if (It == Commands.end())
118     return None;
119   return It->second;
120 }
121 
122 bool InMemoryCompilationDb::setCompilationCommandForFile(
123     PathRef File, tooling::CompileCommand CompilationCommand) {
124   std::unique_lock<std::mutex> Lock(Mutex);
125   auto ItInserted = Commands.insert(std::make_pair(File, CompilationCommand));
126   if (ItInserted.second)
127     return true;
128   ItInserted.first->setValue(std::move(CompilationCommand));
129   return false;
130 }
131 
132 } // namespace clangd
133 } // namespace clang
134