blob: 91d77026293c25e0e20caefce0b0d2107e57638f [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- 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 "clang/Tooling/CompilationDatabase.h"
12#include "llvm/Support/FileSystem.h"
13#include "llvm/Support/Path.h"
14
15using namespace clang::clangd;
16using namespace clang;
17
18std::vector<tooling::CompileCommand>
19DirectoryBasedGlobalCompilationDatabase::getCompileCommands(PathRef File) {
20 std::vector<tooling::CompileCommand> Commands;
21
22 auto CDB = getCompilationDatabase(File);
23 if (!CDB)
24 return {};
25 return CDB->getCompileCommands(File);
26}
27
28tooling::CompilationDatabase *
29DirectoryBasedGlobalCompilationDatabase::getCompilationDatabase(PathRef File) {
30 std::lock_guard<std::mutex> Lock(Mutex);
31
32 namespace path = llvm::sys::path;
33
34 assert((path::is_absolute(File, path::Style::posix) ||
35 path::is_absolute(File, path::Style::windows)) &&
36 "path must be absolute");
37
38 for (auto Path = path::parent_path(File); !Path.empty();
39 Path = path::parent_path(Path)) {
40
41 auto CachedIt = CompilationDatabases.find(Path);
42 if (CachedIt != CompilationDatabases.end())
43 return CachedIt->second.get();
44 std::string Error;
45 auto CDB = tooling::CompilationDatabase::loadFromDirectory(Path, Error);
46 if (!CDB) {
47 if (!Error.empty()) {
48 // FIXME(ibiryukov): logging
49 // Output.log("Error when trying to load compilation database from " +
50 // Twine(Path) + ": " + Twine(Error) + "\n");
51 }
52 continue;
53 }
54
55 // FIXME(ibiryukov): Invalidate cached compilation databases on changes
56 auto result = CDB.get();
57 CompilationDatabases.insert(std::make_pair(Path, std::move(CDB)));
58 return result;
59 }
60
61 // FIXME(ibiryukov): logging
62 // Output.log("Failed to find compilation database for " + Twine(File) +
63 // "\n");
64 return nullptr;
65}