2017-05-16 17:38:59 +08:00
|
|
|
//===--- ClangdServer.cpp - Main clangd server code --------------*- C++-*-===//
|
|
|
|
//
|
|
|
|
// The LLVM Compiler Infrastructure
|
|
|
|
//
|
|
|
|
// This file is distributed under the University of Illinois Open Source
|
|
|
|
// License. See LICENSE.TXT for details.
|
|
|
|
//
|
|
|
|
//===-------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
#include "ClangdServer.h"
|
2017-12-20 01:06:07 +08:00
|
|
|
#include "CodeComplete.h"
|
2017-12-19 20:23:48 +08:00
|
|
|
#include "SourceCode.h"
|
2017-12-20 01:06:07 +08:00
|
|
|
#include "XRefs.h"
|
2018-01-15 20:33:00 +08:00
|
|
|
#include "index/Merge.h"
|
2017-05-16 22:40:30 +08:00
|
|
|
#include "clang/Format/Format.h"
|
2017-05-16 17:38:59 +08:00
|
|
|
#include "clang/Frontend/CompilerInstance.h"
|
|
|
|
#include "clang/Frontend/CompilerInvocation.h"
|
|
|
|
#include "clang/Tooling/CompilationDatabase.h"
|
2017-11-16 02:04:56 +08:00
|
|
|
#include "clang/Tooling/Refactoring/RefactoringResultConsumer.h"
|
|
|
|
#include "clang/Tooling/Refactoring/Rename/RenamingAction.h"
|
2017-05-16 22:40:30 +08:00
|
|
|
#include "llvm/ADT/ArrayRef.h"
|
2017-10-26 20:28:13 +08:00
|
|
|
#include "llvm/Support/Errc.h"
|
2017-05-16 17:38:59 +08:00
|
|
|
#include "llvm/Support/FileSystem.h"
|
2017-11-02 17:21:51 +08:00
|
|
|
#include "llvm/Support/FormatProviders.h"
|
|
|
|
#include "llvm/Support/FormatVariadic.h"
|
2017-09-27 23:31:17 +08:00
|
|
|
#include "llvm/Support/Path.h"
|
2017-05-23 21:42:59 +08:00
|
|
|
#include "llvm/Support/raw_ostream.h"
|
|
|
|
#include <future>
|
2017-05-16 17:38:59 +08:00
|
|
|
|
2017-05-16 18:06:20 +08:00
|
|
|
using namespace clang;
|
2017-05-16 17:38:59 +08:00
|
|
|
using namespace clang::clangd;
|
|
|
|
|
2017-05-16 22:40:30 +08:00
|
|
|
namespace {
|
|
|
|
|
2018-01-23 23:07:52 +08:00
|
|
|
tooling::CompileCommand getCompileCommand(GlobalCompilationDatabase &CDB,
|
|
|
|
PathRef File, PathRef ResourceDir) {
|
|
|
|
llvm::Optional<tooling::CompileCommand> C = CDB.getCompileCommand(File);
|
|
|
|
if (!C) // FIXME: Suppress diagnostics? Let the user know?
|
|
|
|
C = CDB.getFallbackCommand(File);
|
|
|
|
|
|
|
|
// Inject the resource dir.
|
|
|
|
// FIXME: Don't overwrite it if it's already there.
|
|
|
|
C->CommandLine.push_back("-resource-dir=" + ResourceDir.str());
|
|
|
|
return std::move(*C);
|
|
|
|
}
|
|
|
|
|
2017-06-28 18:34:50 +08:00
|
|
|
std::string getStandardResourceDir() {
|
|
|
|
static int Dummy; // Just an address in this process.
|
|
|
|
return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
|
|
|
|
}
|
|
|
|
|
2017-11-09 19:30:04 +08:00
|
|
|
class RefactoringResultCollector final
|
|
|
|
: public tooling::RefactoringResultConsumer {
|
|
|
|
public:
|
|
|
|
void handleError(llvm::Error Err) override {
|
|
|
|
assert(!Result.hasValue());
|
|
|
|
// FIXME: figure out a way to return better message for DiagnosticError.
|
|
|
|
// clangd uses llvm::toString to convert the Err to string, however, for
|
|
|
|
// DiagnosticError, only "clang diagnostic" will be generated.
|
|
|
|
Result = std::move(Err);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Using the handle(SymbolOccurrences) from parent class.
|
|
|
|
using tooling::RefactoringResultConsumer::handle;
|
|
|
|
|
|
|
|
void handle(tooling::AtomicChanges SourceReplacements) override {
|
|
|
|
assert(!Result.hasValue());
|
|
|
|
Result = std::move(SourceReplacements);
|
|
|
|
}
|
|
|
|
|
|
|
|
Optional<Expected<tooling::AtomicChanges>> Result;
|
|
|
|
};
|
|
|
|
|
2017-05-16 22:40:30 +08:00
|
|
|
} // namespace
|
|
|
|
|
2017-05-30 23:11:02 +08:00
|
|
|
Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
|
2017-06-14 17:46:44 +08:00
|
|
|
RealFileSystemProvider::getTaggedFileSystem(PathRef File) {
|
2017-05-30 23:11:02 +08:00
|
|
|
return make_tagged(vfs::getRealFileSystem(), VFSTag());
|
2017-05-26 20:26:51 +08:00
|
|
|
}
|
|
|
|
|
2017-08-14 16:45:47 +08:00
|
|
|
unsigned clangd::getDefaultAsyncThreadsCount() {
|
|
|
|
unsigned HardwareConcurrency = std::thread::hardware_concurrency();
|
|
|
|
// C++ standard says that hardware_concurrency()
|
|
|
|
// may return 0, fallback to 1 worker thread in
|
|
|
|
// that case.
|
|
|
|
if (HardwareConcurrency == 0)
|
|
|
|
return 1;
|
|
|
|
return HardwareConcurrency;
|
|
|
|
}
|
|
|
|
|
|
|
|
ClangdScheduler::ClangdScheduler(unsigned AsyncThreadsCount)
|
|
|
|
: RunSynchronously(AsyncThreadsCount == 0) {
|
2017-05-16 17:38:59 +08:00
|
|
|
if (RunSynchronously) {
|
|
|
|
// Don't start the worker thread if we're running synchronously
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2017-08-14 16:45:47 +08:00
|
|
|
Workers.reserve(AsyncThreadsCount);
|
|
|
|
for (unsigned I = 0; I < AsyncThreadsCount; ++I) {
|
2017-11-02 17:21:51 +08:00
|
|
|
Workers.push_back(std::thread([this, I]() {
|
|
|
|
llvm::set_thread_name(llvm::formatv("scheduler/{0}", I));
|
2017-08-14 16:45:47 +08:00
|
|
|
while (true) {
|
2017-10-10 00:26:26 +08:00
|
|
|
UniqueFunction<void()> Request;
|
2017-08-14 16:45:47 +08:00
|
|
|
|
|
|
|
// Pick request from the queue
|
|
|
|
{
|
|
|
|
std::unique_lock<std::mutex> Lock(Mutex);
|
|
|
|
// Wait for more requests.
|
|
|
|
RequestCV.wait(Lock,
|
|
|
|
[this] { return !RequestQueue.empty() || Done; });
|
|
|
|
if (Done)
|
|
|
|
return;
|
|
|
|
|
|
|
|
assert(!RequestQueue.empty() && "RequestQueue was empty");
|
|
|
|
|
|
|
|
// We process requests starting from the front of the queue. Users of
|
|
|
|
// ClangdScheduler have a way to prioritise their requests by putting
|
|
|
|
// them to the either side of the queue (using either addToEnd or
|
|
|
|
// addToFront).
|
|
|
|
Request = std::move(RequestQueue.front());
|
|
|
|
RequestQueue.pop_front();
|
|
|
|
} // unlock Mutex
|
|
|
|
|
2017-10-10 00:26:26 +08:00
|
|
|
Request();
|
2017-08-14 16:45:47 +08:00
|
|
|
}
|
|
|
|
}));
|
|
|
|
}
|
2017-05-16 17:38:59 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
ClangdScheduler::~ClangdScheduler() {
|
|
|
|
if (RunSynchronously)
|
|
|
|
return; // no worker thread is running in that case
|
|
|
|
|
|
|
|
{
|
|
|
|
std::lock_guard<std::mutex> Lock(Mutex);
|
|
|
|
// Wake up the worker thread
|
|
|
|
Done = true;
|
|
|
|
} // unlock Mutex
|
2017-08-14 16:45:47 +08:00
|
|
|
RequestCV.notify_all();
|
|
|
|
|
|
|
|
for (auto &Worker : Workers)
|
|
|
|
Worker.join();
|
2017-05-16 17:38:59 +08:00
|
|
|
}
|
|
|
|
|
2017-11-24 00:58:22 +08:00
|
|
|
ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
|
|
|
|
DiagnosticsConsumer &DiagConsumer,
|
|
|
|
FileSystemProvider &FSProvider,
|
|
|
|
unsigned AsyncThreadsCount,
|
2017-12-13 20:51:22 +08:00
|
|
|
bool StorePreamblesInMemory,
|
2018-01-10 22:44:34 +08:00
|
|
|
bool BuildDynamicSymbolIndex, SymbolIndex *StaticIdx,
|
2017-11-24 00:58:22 +08:00
|
|
|
llvm::Optional<StringRef> ResourceDir)
|
2017-12-13 20:51:22 +08:00
|
|
|
: CDB(CDB), DiagConsumer(DiagConsumer), FSProvider(FSProvider),
|
2017-12-20 02:00:37 +08:00
|
|
|
FileIdx(BuildDynamicSymbolIndex ? new FileIndex() : nullptr),
|
|
|
|
// Pass a callback into `Units` to extract symbols from a newly parsed
|
|
|
|
// file and rebuild the file index synchronously each time an AST is
|
|
|
|
// parsed.
|
|
|
|
// FIXME(ioeric): this can be slow and we may be able to index on less
|
|
|
|
// critical paths.
|
|
|
|
Units(FileIdx
|
|
|
|
? [this](const Context &Ctx, PathRef Path,
|
|
|
|
ParsedAST *AST) { FileIdx->update(Ctx, Path, AST); }
|
|
|
|
: ASTParsedCallback()),
|
2017-06-28 18:34:50 +08:00
|
|
|
ResourceDir(ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
|
2017-05-16 17:38:59 +08:00
|
|
|
PCHs(std::make_shared<PCHContainerOperations>()),
|
2017-11-17 00:25:18 +08:00
|
|
|
StorePreamblesInMemory(StorePreamblesInMemory),
|
2018-01-15 20:33:00 +08:00
|
|
|
WorkScheduler(AsyncThreadsCount) {
|
|
|
|
if (FileIdx && StaticIdx) {
|
|
|
|
MergedIndex = mergeIndex(FileIdx.get(), StaticIdx);
|
|
|
|
Index = MergedIndex.get();
|
|
|
|
} else if (FileIdx)
|
|
|
|
Index = FileIdx.get();
|
|
|
|
else if (StaticIdx)
|
|
|
|
Index = StaticIdx;
|
|
|
|
else
|
|
|
|
Index = nullptr;
|
|
|
|
}
|
2017-05-16 17:38:59 +08:00
|
|
|
|
2017-09-27 23:31:17 +08:00
|
|
|
void ClangdServer::setRootPath(PathRef RootPath) {
|
|
|
|
std::string NewRootPath = llvm::sys::path::convert_to_slash(
|
|
|
|
RootPath, llvm::sys::path::Style::posix);
|
|
|
|
if (llvm::sys::fs::is_directory(NewRootPath))
|
|
|
|
this->RootPath = NewRootPath;
|
|
|
|
}
|
|
|
|
|
2017-12-13 20:51:22 +08:00
|
|
|
std::future<Context> ClangdServer::addDocument(Context Ctx, PathRef File,
|
|
|
|
StringRef Contents) {
|
2017-05-23 21:42:59 +08:00
|
|
|
DocVersion Version = DraftMgr.updateDraft(File, Contents);
|
|
|
|
|
2017-08-01 23:51:38 +08:00
|
|
|
auto TaggedFS = FSProvider.getTaggedFileSystem(File);
|
2018-01-23 23:07:52 +08:00
|
|
|
std::shared_ptr<CppFile> Resources =
|
|
|
|
Units.getOrCreateFile(File, ResourceDir, StorePreamblesInMemory, PCHs);
|
2017-12-13 20:51:22 +08:00
|
|
|
return scheduleReparseAndDiags(std::move(Ctx), File,
|
|
|
|
VersionedDraft{Version, Contents.str()},
|
2018-01-23 23:07:52 +08:00
|
|
|
std::move(Resources), std::move(TaggedFS),
|
|
|
|
/*AllowCachedCompileFlags=*/true);
|
2017-05-16 17:38:59 +08:00
|
|
|
}
|
|
|
|
|
2017-12-13 20:51:22 +08:00
|
|
|
std::future<Context> ClangdServer::removeDocument(Context Ctx, PathRef File) {
|
2017-08-14 16:17:24 +08:00
|
|
|
DraftMgr.removeDraft(File);
|
|
|
|
std::shared_ptr<CppFile> Resources = Units.removeIfPresent(File);
|
2017-12-13 20:51:22 +08:00
|
|
|
return scheduleCancelRebuild(std::move(Ctx), std::move(Resources));
|
2017-05-16 17:38:59 +08:00
|
|
|
}
|
|
|
|
|
2017-12-13 20:51:22 +08:00
|
|
|
std::future<Context> ClangdServer::forceReparse(Context Ctx, PathRef File) {
|
2017-08-14 16:37:32 +08:00
|
|
|
auto FileContents = DraftMgr.getDraft(File);
|
|
|
|
assert(FileContents.Draft &&
|
|
|
|
"forceReparse() was called for non-added document");
|
|
|
|
|
|
|
|
auto TaggedFS = FSProvider.getTaggedFileSystem(File);
|
2018-01-23 23:07:52 +08:00
|
|
|
std::shared_ptr<CppFile> Resources =
|
|
|
|
Units.getOrCreateFile(File, ResourceDir, StorePreamblesInMemory, PCHs);
|
|
|
|
return scheduleReparseAndDiags(std::move(Ctx), File, FileContents,
|
|
|
|
std::move(Resources), std::move(TaggedFS),
|
|
|
|
/*AllowCachedCompileFlags=*/false);
|
2017-05-26 20:26:51 +08:00
|
|
|
}
|
|
|
|
|
2017-12-13 20:51:22 +08:00
|
|
|
std::future<std::pair<Context, Tagged<CompletionList>>>
|
|
|
|
ClangdServer::codeComplete(Context Ctx, PathRef File, Position Pos,
|
2017-12-05 18:42:57 +08:00
|
|
|
const clangd::CodeCompleteOptions &Opts,
|
2017-08-01 01:09:29 +08:00
|
|
|
llvm::Optional<StringRef> OverridenContents,
|
|
|
|
IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
|
2017-12-13 20:51:22 +08:00
|
|
|
using ResultType = std::pair<Context, Tagged<CompletionList>>;
|
2017-10-25 17:35:10 +08:00
|
|
|
|
|
|
|
std::promise<ResultType> ResultPromise;
|
|
|
|
|
2017-12-13 20:51:22 +08:00
|
|
|
auto Callback = [](std::promise<ResultType> ResultPromise, Context Ctx,
|
|
|
|
Tagged<CompletionList> Result) -> void {
|
|
|
|
ResultPromise.set_value({std::move(Ctx), std::move(Result)});
|
2017-10-25 17:35:10 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
std::future<ResultType> ResultFuture = ResultPromise.get_future();
|
2017-12-13 20:51:22 +08:00
|
|
|
codeComplete(std::move(Ctx), File, Pos, Opts,
|
|
|
|
BindWithForward(Callback, std::move(ResultPromise)),
|
|
|
|
OverridenContents, UsedFS);
|
2017-10-25 17:35:10 +08:00
|
|
|
return ResultFuture;
|
|
|
|
}
|
|
|
|
|
|
|
|
void ClangdServer::codeComplete(
|
2017-12-13 20:51:22 +08:00
|
|
|
Context Ctx, PathRef File, Position Pos,
|
|
|
|
const clangd::CodeCompleteOptions &Opts,
|
|
|
|
UniqueFunction<void(Context, Tagged<CompletionList>)> Callback,
|
2017-12-05 18:42:57 +08:00
|
|
|
llvm::Optional<StringRef> OverridenContents,
|
2017-10-25 17:35:10 +08:00
|
|
|
IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
|
2017-12-13 20:51:22 +08:00
|
|
|
using CallbackType = UniqueFunction<void(Context, Tagged<CompletionList>)>;
|
2017-10-25 17:35:10 +08:00
|
|
|
|
2017-10-06 01:04:13 +08:00
|
|
|
std::string Contents;
|
|
|
|
if (OverridenContents) {
|
|
|
|
Contents = *OverridenContents;
|
|
|
|
} else {
|
2017-06-13 22:15:56 +08:00
|
|
|
auto FileContents = DraftMgr.getDraft(File);
|
|
|
|
assert(FileContents.Draft &&
|
|
|
|
"codeComplete is called for non-added document");
|
|
|
|
|
2017-10-06 01:04:13 +08:00
|
|
|
Contents = std::move(*FileContents.Draft);
|
2017-06-13 22:15:56 +08:00
|
|
|
}
|
2017-05-16 17:38:59 +08:00
|
|
|
|
2017-06-14 17:46:44 +08:00
|
|
|
auto TaggedFS = FSProvider.getTaggedFileSystem(File);
|
2017-08-01 01:09:29 +08:00
|
|
|
if (UsedFS)
|
|
|
|
*UsedFS = TaggedFS.Value;
|
|
|
|
|
2017-08-01 23:51:38 +08:00
|
|
|
std::shared_ptr<CppFile> Resources = Units.getFile(File);
|
|
|
|
assert(Resources && "Calling completion on non-added file");
|
|
|
|
|
2017-10-06 01:04:13 +08:00
|
|
|
// Remember the current Preamble and use it when async task starts executing.
|
|
|
|
// At the point when async task starts executing, we may have a different
|
|
|
|
// Preamble in Resources. However, we assume the Preamble that we obtain here
|
|
|
|
// is reusable in completion more often.
|
|
|
|
std::shared_ptr<const PreambleData> Preamble =
|
|
|
|
Resources->getPossiblyStalePreamble();
|
2017-12-05 18:42:57 +08:00
|
|
|
// Copy completion options for passing them to async task handler.
|
|
|
|
auto CodeCompleteOpts = Opts;
|
2018-01-15 20:33:00 +08:00
|
|
|
if (!CodeCompleteOpts.Index) // Respect overridden index.
|
|
|
|
CodeCompleteOpts.Index = Index;
|
2018-01-09 22:39:27 +08:00
|
|
|
|
|
|
|
// Copy File, as it is a PathRef that will go out of scope before Task is
|
|
|
|
// executed.
|
|
|
|
Path FileStr = File;
|
|
|
|
// Copy PCHs to avoid accessing this->PCHs concurrently
|
|
|
|
std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
|
2018-01-23 23:07:52 +08:00
|
|
|
|
|
|
|
assert(Resources->getLastCommand() &&
|
|
|
|
"CppFile is in inconsistent state, missing CompileCommand");
|
|
|
|
tooling::CompileCommand CompileCommand = *Resources->getLastCommand();
|
|
|
|
|
2017-10-06 01:04:13 +08:00
|
|
|
// A task that will be run asynchronously.
|
2017-10-25 17:35:10 +08:00
|
|
|
auto Task =
|
|
|
|
// 'mutable' to reassign Preamble variable.
|
2018-01-09 22:39:27 +08:00
|
|
|
[FileStr, Preamble, Resources, Contents, Pos, CodeCompleteOpts, TaggedFS,
|
2018-01-23 23:07:52 +08:00
|
|
|
PCHs, CompileCommand](Context Ctx, CallbackType Callback) mutable {
|
2017-10-25 17:35:10 +08:00
|
|
|
if (!Preamble) {
|
|
|
|
// Maybe we built some preamble before processing this request.
|
|
|
|
Preamble = Resources->getPossiblyStalePreamble();
|
|
|
|
}
|
|
|
|
// FIXME(ibiryukov): even if Preamble is non-null, we may want to check
|
|
|
|
// both the old and the new version in case only one of them matches.
|
2017-11-15 17:16:29 +08:00
|
|
|
CompletionList Result = clangd::codeComplete(
|
2018-01-23 23:07:52 +08:00
|
|
|
Ctx, FileStr, CompileCommand,
|
2017-10-25 17:35:10 +08:00
|
|
|
Preamble ? &Preamble->Preamble : nullptr, Contents, Pos,
|
2017-12-13 20:51:22 +08:00
|
|
|
TaggedFS.Value, PCHs, CodeCompleteOpts);
|
2017-10-25 17:35:10 +08:00
|
|
|
|
2017-12-13 20:51:22 +08:00
|
|
|
Callback(std::move(Ctx),
|
|
|
|
make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
|
2017-10-25 17:35:10 +08:00
|
|
|
};
|
|
|
|
|
2017-12-13 20:51:22 +08:00
|
|
|
WorkScheduler.addToFront(std::move(Task), std::move(Ctx),
|
|
|
|
std::move(Callback));
|
2017-05-16 17:38:59 +08:00
|
|
|
}
|
2017-05-23 21:42:59 +08:00
|
|
|
|
2017-10-26 20:28:13 +08:00
|
|
|
llvm::Expected<Tagged<SignatureHelp>>
|
2017-12-13 20:51:22 +08:00
|
|
|
ClangdServer::signatureHelp(const Context &Ctx, PathRef File, Position Pos,
|
2017-10-06 19:54:17 +08:00
|
|
|
llvm::Optional<StringRef> OverridenContents,
|
|
|
|
IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
|
|
|
|
std::string DraftStorage;
|
|
|
|
if (!OverridenContents) {
|
|
|
|
auto FileContents = DraftMgr.getDraft(File);
|
2017-10-26 20:28:13 +08:00
|
|
|
if (!FileContents.Draft)
|
|
|
|
return llvm::make_error<llvm::StringError>(
|
|
|
|
"signatureHelp is called for non-added document",
|
|
|
|
llvm::errc::invalid_argument);
|
2017-10-06 19:54:17 +08:00
|
|
|
|
|
|
|
DraftStorage = std::move(*FileContents.Draft);
|
|
|
|
OverridenContents = DraftStorage;
|
|
|
|
}
|
|
|
|
|
|
|
|
auto TaggedFS = FSProvider.getTaggedFileSystem(File);
|
|
|
|
if (UsedFS)
|
|
|
|
*UsedFS = TaggedFS.Value;
|
|
|
|
|
|
|
|
std::shared_ptr<CppFile> Resources = Units.getFile(File);
|
2017-10-26 20:28:13 +08:00
|
|
|
if (!Resources)
|
|
|
|
return llvm::make_error<llvm::StringError>(
|
|
|
|
"signatureHelp is called for non-added document",
|
|
|
|
llvm::errc::invalid_argument);
|
2017-10-06 19:54:17 +08:00
|
|
|
|
2018-01-23 23:07:52 +08:00
|
|
|
assert(Resources->getLastCommand() &&
|
|
|
|
"CppFile is in inconsistent state, missing CompileCommand");
|
|
|
|
|
2017-10-06 19:54:17 +08:00
|
|
|
auto Preamble = Resources->getPossiblyStalePreamble();
|
2017-12-13 20:51:22 +08:00
|
|
|
auto Result =
|
2018-01-23 23:07:52 +08:00
|
|
|
clangd::signatureHelp(Ctx, File, *Resources->getLastCommand(),
|
2017-12-13 20:51:22 +08:00
|
|
|
Preamble ? &Preamble->Preamble : nullptr,
|
|
|
|
*OverridenContents, Pos, TaggedFS.Value, PCHs);
|
2017-10-06 19:54:17 +08:00
|
|
|
return make_tagged(std::move(Result), TaggedFS.Tag);
|
|
|
|
}
|
|
|
|
|
2017-12-13 04:25:06 +08:00
|
|
|
llvm::Expected<tooling::Replacements>
|
|
|
|
ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
|
2017-05-16 22:40:30 +08:00
|
|
|
size_t Begin = positionToOffset(Code, Rng.start);
|
|
|
|
size_t Len = positionToOffset(Code, Rng.end) - Begin;
|
|
|
|
return formatCode(Code, File, {tooling::Range(Begin, Len)});
|
|
|
|
}
|
|
|
|
|
2017-12-13 04:25:06 +08:00
|
|
|
llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
|
|
|
|
PathRef File) {
|
2017-05-16 22:40:30 +08:00
|
|
|
// Format everything.
|
|
|
|
return formatCode(Code, File, {tooling::Range(0, Code.size())});
|
|
|
|
}
|
|
|
|
|
2017-12-13 04:25:06 +08:00
|
|
|
llvm::Expected<tooling::Replacements>
|
|
|
|
ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
|
2017-05-16 22:40:30 +08:00
|
|
|
// Look for the previous opening brace from the character position and
|
|
|
|
// format starting from there.
|
|
|
|
size_t CursorPos = positionToOffset(Code, Pos);
|
|
|
|
size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
|
|
|
|
if (PreviousLBracePos == StringRef::npos)
|
|
|
|
PreviousLBracePos = CursorPos;
|
2017-12-19 20:23:48 +08:00
|
|
|
size_t Len = CursorPos - PreviousLBracePos;
|
2017-05-16 22:40:30 +08:00
|
|
|
|
|
|
|
return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
|
|
|
|
}
|
2017-05-16 17:38:59 +08:00
|
|
|
|
2017-11-09 19:30:04 +08:00
|
|
|
Expected<std::vector<tooling::Replacement>>
|
2017-12-13 20:51:22 +08:00
|
|
|
ClangdServer::rename(const Context &Ctx, PathRef File, Position Pos,
|
|
|
|
llvm::StringRef NewName) {
|
2017-11-09 19:30:04 +08:00
|
|
|
std::shared_ptr<CppFile> Resources = Units.getFile(File);
|
|
|
|
RefactoringResultCollector ResultCollector;
|
|
|
|
Resources->getAST().get()->runUnderLock([&](ParsedAST *AST) {
|
|
|
|
const SourceManager &SourceMgr = AST->getASTContext().getSourceManager();
|
|
|
|
const FileEntry *FE =
|
|
|
|
SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
|
|
|
|
if (!FE)
|
|
|
|
return;
|
|
|
|
SourceLocation SourceLocationBeg =
|
|
|
|
clangd::getBeginningOfIdentifier(*AST, Pos, FE);
|
|
|
|
tooling::RefactoringRuleContext Context(
|
|
|
|
AST->getASTContext().getSourceManager());
|
|
|
|
Context.setASTContext(AST->getASTContext());
|
|
|
|
auto Rename = clang::tooling::RenameOccurrences::initiate(
|
|
|
|
Context, SourceRange(SourceLocationBeg), NewName.str());
|
|
|
|
if (!Rename) {
|
|
|
|
ResultCollector.Result = Rename.takeError();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
Rename->invoke(ResultCollector, Context);
|
|
|
|
});
|
|
|
|
assert(ResultCollector.Result.hasValue());
|
|
|
|
if (!ResultCollector.Result.getValue())
|
|
|
|
return ResultCollector.Result->takeError();
|
|
|
|
|
|
|
|
std::vector<tooling::Replacement> Replacements;
|
|
|
|
for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
|
|
|
|
tooling::Replacements ChangeReps = Change.getReplacements();
|
|
|
|
for (const auto &Rep : ChangeReps) {
|
|
|
|
// FIXME: Right now we only support renaming the main file, so we drop
|
|
|
|
// replacements not for the main file. In the future, we might consider to
|
|
|
|
// support:
|
|
|
|
// * rename in any included header
|
|
|
|
// * rename only in the "main" header
|
|
|
|
// * provide an error if there are symbols we won't rename (e.g.
|
|
|
|
// std::vector)
|
|
|
|
// * rename globally in project
|
|
|
|
// * rename in open files
|
|
|
|
if (Rep.getFilePath() == File)
|
|
|
|
Replacements.push_back(Rep);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return Replacements;
|
|
|
|
}
|
|
|
|
|
2018-01-17 20:30:24 +08:00
|
|
|
llvm::Optional<std::string> ClangdServer::getDocument(PathRef File) {
|
|
|
|
auto Latest = DraftMgr.getDraft(File);
|
|
|
|
if (!Latest.Draft)
|
|
|
|
return llvm::None;
|
|
|
|
return std::move(*Latest.Draft);
|
2017-05-16 17:38:59 +08:00
|
|
|
}
|
|
|
|
|
2017-05-23 21:42:59 +08:00
|
|
|
std::string ClangdServer::dumpAST(PathRef File) {
|
2017-08-01 23:51:38 +08:00
|
|
|
std::shared_ptr<CppFile> Resources = Units.getFile(File);
|
2018-01-17 20:30:24 +08:00
|
|
|
if (!Resources)
|
|
|
|
return "<non-added file>";
|
2017-08-01 23:51:38 +08:00
|
|
|
|
|
|
|
std::string Result;
|
2017-08-02 02:27:58 +08:00
|
|
|
Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
|
2017-08-01 23:51:38 +08:00
|
|
|
llvm::raw_string_ostream ResultOS(Result);
|
|
|
|
if (AST) {
|
|
|
|
clangd::dumpAST(*AST, ResultOS);
|
|
|
|
} else {
|
|
|
|
ResultOS << "<no-ast>";
|
|
|
|
}
|
|
|
|
ResultOS.flush();
|
2017-05-23 21:42:59 +08:00
|
|
|
});
|
2017-08-01 23:51:38 +08:00
|
|
|
return Result;
|
2017-05-16 17:38:59 +08:00
|
|
|
}
|
2017-06-29 00:12:10 +08:00
|
|
|
|
2017-10-26 20:28:13 +08:00
|
|
|
llvm::Expected<Tagged<std::vector<Location>>>
|
2017-12-13 20:51:22 +08:00
|
|
|
ClangdServer::findDefinitions(const Context &Ctx, PathRef File, Position Pos) {
|
2017-06-29 00:12:10 +08:00
|
|
|
auto TaggedFS = FSProvider.getTaggedFileSystem(File);
|
2017-08-01 23:51:38 +08:00
|
|
|
|
|
|
|
std::shared_ptr<CppFile> Resources = Units.getFile(File);
|
2017-10-26 20:28:13 +08:00
|
|
|
if (!Resources)
|
|
|
|
return llvm::make_error<llvm::StringError>(
|
|
|
|
"findDefinitions called on non-added file",
|
|
|
|
llvm::errc::invalid_argument);
|
2017-08-01 23:51:38 +08:00
|
|
|
|
|
|
|
std::vector<Location> Result;
|
2017-12-13 20:51:22 +08:00
|
|
|
Resources->getAST().get()->runUnderLock([Pos, &Result, &Ctx](ParsedAST *AST) {
|
2017-08-01 23:51:38 +08:00
|
|
|
if (!AST)
|
|
|
|
return;
|
2017-12-13 20:51:22 +08:00
|
|
|
Result = clangd::findDefinitions(Ctx, *AST, Pos);
|
2017-08-01 23:51:38 +08:00
|
|
|
});
|
2017-06-29 00:12:10 +08:00
|
|
|
return make_tagged(std::move(Result), TaggedFS.Tag);
|
|
|
|
}
|
2017-08-14 16:17:24 +08:00
|
|
|
|
2017-09-28 11:14:40 +08:00
|
|
|
llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
|
|
|
|
|
|
|
|
StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
|
|
|
|
".c++", ".m", ".mm"};
|
|
|
|
StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
|
|
|
|
|
|
|
|
StringRef PathExt = llvm::sys::path::extension(Path);
|
|
|
|
|
|
|
|
// Lookup in a list of known extensions.
|
|
|
|
auto SourceIter =
|
|
|
|
std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
|
|
|
|
[&PathExt](PathRef SourceExt) {
|
|
|
|
return SourceExt.equals_lower(PathExt);
|
|
|
|
});
|
|
|
|
bool IsSource = SourceIter != std::end(SourceExtensions);
|
|
|
|
|
|
|
|
auto HeaderIter =
|
|
|
|
std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
|
|
|
|
[&PathExt](PathRef HeaderExt) {
|
|
|
|
return HeaderExt.equals_lower(PathExt);
|
|
|
|
});
|
|
|
|
|
|
|
|
bool IsHeader = HeaderIter != std::end(HeaderExtensions);
|
|
|
|
|
|
|
|
// We can only switch between extensions known extensions.
|
|
|
|
if (!IsSource && !IsHeader)
|
|
|
|
return llvm::None;
|
|
|
|
|
|
|
|
// Array to lookup extensions for the switch. An opposite of where original
|
|
|
|
// extension was found.
|
|
|
|
ArrayRef<StringRef> NewExts;
|
|
|
|
if (IsSource)
|
|
|
|
NewExts = HeaderExtensions;
|
|
|
|
else
|
|
|
|
NewExts = SourceExtensions;
|
|
|
|
|
|
|
|
// Storage for the new path.
|
|
|
|
SmallString<128> NewPath = StringRef(Path);
|
|
|
|
|
|
|
|
// Instance of vfs::FileSystem, used for file existence checks.
|
|
|
|
auto FS = FSProvider.getTaggedFileSystem(Path).Value;
|
|
|
|
|
|
|
|
// Loop through switched extension candidates.
|
|
|
|
for (StringRef NewExt : NewExts) {
|
|
|
|
llvm::sys::path::replace_extension(NewPath, NewExt);
|
|
|
|
if (FS->exists(NewPath))
|
|
|
|
return NewPath.str().str(); // First str() to convert from SmallString to
|
|
|
|
// StringRef, second to convert from StringRef
|
|
|
|
// to std::string
|
2017-10-06 22:39:39 +08:00
|
|
|
|
2017-09-28 11:14:40 +08:00
|
|
|
// Also check NewExt in upper-case, just in case.
|
|
|
|
llvm::sys::path::replace_extension(NewPath, NewExt.upper());
|
|
|
|
if (FS->exists(NewPath))
|
|
|
|
return NewPath.str().str();
|
|
|
|
}
|
|
|
|
|
|
|
|
return llvm::None;
|
|
|
|
}
|
|
|
|
|
2017-12-13 04:25:06 +08:00
|
|
|
llvm::Expected<tooling::Replacements>
|
|
|
|
ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
|
|
|
|
ArrayRef<tooling::Range> Ranges) {
|
|
|
|
// Call clang-format.
|
|
|
|
auto TaggedFS = FSProvider.getTaggedFileSystem(File);
|
|
|
|
auto StyleOrError =
|
|
|
|
format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
|
|
|
|
if (!StyleOrError) {
|
|
|
|
return StyleOrError.takeError();
|
|
|
|
} else {
|
|
|
|
return format::reformat(StyleOrError.get(), Code, Ranges, File);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
[clangd] Document highlights for clangd
Summary: Implementation of Document Highlights Request as described in
LSP.
Contributed by William Enright (nebiroth).
Reviewers: malaperle, krasimir, bkramer, ilya-biryukov
Reviewed By: malaperle
Subscribers: mgrang, sammccall, klimek, ioeric, rwols, cfe-commits, arphaman, ilya-biryukov
Differential Revision: https://reviews.llvm.org/D38425
llvm-svn: 320474
2017-12-12 20:27:47 +08:00
|
|
|
llvm::Expected<Tagged<std::vector<DocumentHighlight>>>
|
2017-12-13 20:51:22 +08:00
|
|
|
ClangdServer::findDocumentHighlights(const Context &Ctx, PathRef File,
|
|
|
|
Position Pos) {
|
[clangd] Document highlights for clangd
Summary: Implementation of Document Highlights Request as described in
LSP.
Contributed by William Enright (nebiroth).
Reviewers: malaperle, krasimir, bkramer, ilya-biryukov
Reviewed By: malaperle
Subscribers: mgrang, sammccall, klimek, ioeric, rwols, cfe-commits, arphaman, ilya-biryukov
Differential Revision: https://reviews.llvm.org/D38425
llvm-svn: 320474
2017-12-12 20:27:47 +08:00
|
|
|
auto FileContents = DraftMgr.getDraft(File);
|
|
|
|
if (!FileContents.Draft)
|
|
|
|
return llvm::make_error<llvm::StringError>(
|
|
|
|
"findDocumentHighlights called on non-added file",
|
|
|
|
llvm::errc::invalid_argument);
|
|
|
|
|
|
|
|
auto TaggedFS = FSProvider.getTaggedFileSystem(File);
|
|
|
|
|
|
|
|
std::shared_ptr<CppFile> Resources = Units.getFile(File);
|
|
|
|
if (!Resources)
|
|
|
|
return llvm::make_error<llvm::StringError>(
|
|
|
|
"findDocumentHighlights called on non-added file",
|
|
|
|
llvm::errc::invalid_argument);
|
|
|
|
|
|
|
|
std::vector<DocumentHighlight> Result;
|
|
|
|
llvm::Optional<llvm::Error> Err;
|
2017-12-13 20:51:22 +08:00
|
|
|
Resources->getAST().get()->runUnderLock([Pos, &Ctx, &Err,
|
|
|
|
&Result](ParsedAST *AST) {
|
[clangd] Document highlights for clangd
Summary: Implementation of Document Highlights Request as described in
LSP.
Contributed by William Enright (nebiroth).
Reviewers: malaperle, krasimir, bkramer, ilya-biryukov
Reviewed By: malaperle
Subscribers: mgrang, sammccall, klimek, ioeric, rwols, cfe-commits, arphaman, ilya-biryukov
Differential Revision: https://reviews.llvm.org/D38425
llvm-svn: 320474
2017-12-12 20:27:47 +08:00
|
|
|
if (!AST) {
|
|
|
|
Err = llvm::make_error<llvm::StringError>("Invalid AST",
|
|
|
|
llvm::errc::invalid_argument);
|
|
|
|
return;
|
|
|
|
}
|
2017-12-13 20:51:22 +08:00
|
|
|
Result = clangd::findDocumentHighlights(Ctx, *AST, Pos);
|
[clangd] Document highlights for clangd
Summary: Implementation of Document Highlights Request as described in
LSP.
Contributed by William Enright (nebiroth).
Reviewers: malaperle, krasimir, bkramer, ilya-biryukov
Reviewed By: malaperle
Subscribers: mgrang, sammccall, klimek, ioeric, rwols, cfe-commits, arphaman, ilya-biryukov
Differential Revision: https://reviews.llvm.org/D38425
llvm-svn: 320474
2017-12-12 20:27:47 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
if (Err)
|
|
|
|
return std::move(*Err);
|
|
|
|
return make_tagged(Result, TaggedFS.Tag);
|
|
|
|
}
|
|
|
|
|
2017-12-13 20:51:22 +08:00
|
|
|
std::future<Context> ClangdServer::scheduleReparseAndDiags(
|
|
|
|
Context Ctx, PathRef File, VersionedDraft Contents,
|
|
|
|
std::shared_ptr<CppFile> Resources,
|
2018-01-23 23:07:52 +08:00
|
|
|
Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS,
|
|
|
|
bool AllowCachedCompileFlags) {
|
|
|
|
llvm::Optional<tooling::CompileCommand> ReusedCommand;
|
|
|
|
if (AllowCachedCompileFlags)
|
|
|
|
ReusedCommand = Resources->getLastCommand();
|
|
|
|
tooling::CompileCommand Command =
|
|
|
|
ReusedCommand ? std::move(*ReusedCommand)
|
|
|
|
: getCompileCommand(CDB, File, ResourceDir);
|
|
|
|
|
|
|
|
ParseInputs Inputs = {std::move(Command), std::move(TaggedFS.Value),
|
|
|
|
*std::move(Contents.Draft)};
|
2017-08-14 16:17:24 +08:00
|
|
|
assert(Contents.Draft && "Draft must have contents");
|
2017-12-13 20:51:22 +08:00
|
|
|
UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(const Context &)>
|
2018-01-23 23:07:52 +08:00
|
|
|
DeferredRebuild = Resources->deferRebuild(std::move(Inputs));
|
2017-12-13 20:51:22 +08:00
|
|
|
std::promise<Context> DonePromise;
|
|
|
|
std::future<Context> DoneFuture = DonePromise.get_future();
|
2017-08-14 16:17:24 +08:00
|
|
|
|
|
|
|
DocVersion Version = Contents.Version;
|
|
|
|
Path FileStr = File;
|
|
|
|
VFSTag Tag = TaggedFS.Tag;
|
|
|
|
auto ReparseAndPublishDiags =
|
|
|
|
[this, FileStr, Version,
|
2017-12-13 20:51:22 +08:00
|
|
|
Tag](UniqueFunction<llvm::Optional<std::vector<DiagWithFixIts>>(
|
|
|
|
const Context &)>
|
2017-08-14 16:17:24 +08:00
|
|
|
DeferredRebuild,
|
2017-12-13 20:51:22 +08:00
|
|
|
std::promise<Context> DonePromise, Context Ctx) -> void {
|
|
|
|
auto Guard = onScopeExit([&]() { DonePromise.set_value(std::move(Ctx)); });
|
2017-08-14 16:17:24 +08:00
|
|
|
|
|
|
|
auto CurrentVersion = DraftMgr.getVersion(FileStr);
|
|
|
|
if (CurrentVersion != Version)
|
|
|
|
return; // This request is outdated
|
|
|
|
|
2017-12-13 20:51:22 +08:00
|
|
|
auto Diags = DeferredRebuild(Ctx);
|
2017-08-14 16:17:24 +08:00
|
|
|
if (!Diags)
|
|
|
|
return; // A new reparse was requested before this one completed.
|
2017-09-20 20:58:55 +08:00
|
|
|
|
|
|
|
// We need to serialize access to resulting diagnostics to avoid calling
|
|
|
|
// `onDiagnosticsReady` in the wrong order.
|
|
|
|
std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
|
|
|
|
DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
|
|
|
|
// FIXME(ibiryukov): get rid of '<' comparison here. In the current
|
|
|
|
// implementation diagnostics will not be reported after version counters'
|
|
|
|
// overflow. This should not happen in practice, since DocVersion is a
|
|
|
|
// 64-bit unsigned integer.
|
|
|
|
if (Version < LastReportedDiagsVersion)
|
|
|
|
return;
|
|
|
|
LastReportedDiagsVersion = Version;
|
|
|
|
|
2018-01-11 01:59:27 +08:00
|
|
|
DiagConsumer.onDiagnosticsReady(Ctx, FileStr,
|
2017-08-14 16:17:24 +08:00
|
|
|
make_tagged(std::move(*Diags), Tag));
|
|
|
|
};
|
|
|
|
|
|
|
|
WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
|
2017-12-13 20:51:22 +08:00
|
|
|
std::move(DeferredRebuild), std::move(DonePromise),
|
|
|
|
std::move(Ctx));
|
2017-08-14 16:17:24 +08:00
|
|
|
return DoneFuture;
|
|
|
|
}
|
|
|
|
|
2017-12-13 20:51:22 +08:00
|
|
|
std::future<Context>
|
|
|
|
ClangdServer::scheduleCancelRebuild(Context Ctx,
|
|
|
|
std::shared_ptr<CppFile> Resources) {
|
|
|
|
std::promise<Context> DonePromise;
|
|
|
|
std::future<Context> DoneFuture = DonePromise.get_future();
|
2017-08-14 16:17:24 +08:00
|
|
|
if (!Resources) {
|
|
|
|
// No need to schedule any cleanup.
|
2017-12-13 20:51:22 +08:00
|
|
|
DonePromise.set_value(std::move(Ctx));
|
2017-08-14 16:17:24 +08:00
|
|
|
return DoneFuture;
|
|
|
|
}
|
|
|
|
|
2017-10-11 00:12:54 +08:00
|
|
|
UniqueFunction<void()> DeferredCancel = Resources->deferCancelRebuild();
|
2017-12-13 20:51:22 +08:00
|
|
|
auto CancelReparses = [Resources](std::promise<Context> DonePromise,
|
|
|
|
UniqueFunction<void()> DeferredCancel,
|
|
|
|
Context Ctx) {
|
2017-10-11 00:12:54 +08:00
|
|
|
DeferredCancel();
|
2017-12-13 20:51:22 +08:00
|
|
|
DonePromise.set_value(std::move(Ctx));
|
2017-08-14 16:17:24 +08:00
|
|
|
};
|
|
|
|
WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
|
2017-12-13 20:51:22 +08:00
|
|
|
std::move(DeferredCancel), std::move(Ctx));
|
2017-08-14 16:17:24 +08:00
|
|
|
return DoneFuture;
|
|
|
|
}
|
2017-10-03 02:00:37 +08:00
|
|
|
|
|
|
|
void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
|
|
|
|
// FIXME: Do nothing for now. This will be used for indexing and potentially
|
|
|
|
// invalidating other caches.
|
|
|
|
}
|