blob: d0b4da72613e4f9306831d7e89483d31ca356eb8 [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdServer.cpp - Main clangd server code --------------*- 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 "ClangdServer.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000011#include "clang/Format/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000012#include "clang/Frontend/ASTUnit.h"
13#include "clang/Frontend/CompilerInstance.h"
14#include "clang/Frontend/CompilerInvocation.h"
15#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000016#include "llvm/ADT/ArrayRef.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000017#include "llvm/Support/FileSystem.h"
Marc-Andre Laperle37de9712017-09-27 15:31:17 +000018#include "llvm/Support/Path.h"
Ilya Biryukovf01af682017-05-23 13:42:59 +000019#include "llvm/Support/raw_ostream.h"
20#include <future>
Ilya Biryukov38d79772017-05-16 09:38:59 +000021
Ilya Biryukov2f314102017-05-16 10:06:20 +000022using namespace clang;
Ilya Biryukov38d79772017-05-16 09:38:59 +000023using namespace clang::clangd;
24
Ilya Biryukovafb55542017-05-16 14:40:30 +000025namespace {
26
Ilya Biryukov02d58702017-08-01 15:51:38 +000027class FulfillPromiseGuard {
28public:
29 FulfillPromiseGuard(std::promise<void> &Promise) : Promise(Promise) {}
30
31 ~FulfillPromiseGuard() { Promise.set_value(); }
32
33private:
34 std::promise<void> &Promise;
35};
36
Ilya Biryukovafb55542017-05-16 14:40:30 +000037std::vector<tooling::Replacement> formatCode(StringRef Code, StringRef Filename,
38 ArrayRef<tooling::Range> Ranges) {
39 // Call clang-format.
40 // FIXME: Don't ignore style.
41 format::FormatStyle Style = format::getLLVMStyle();
42 auto Result = format::reformat(Style, Code, Ranges, Filename);
43
44 return std::vector<tooling::Replacement>(Result.begin(), Result.end());
45}
46
Ilya Biryukova46f7a92017-06-28 10:34:50 +000047std::string getStandardResourceDir() {
48 static int Dummy; // Just an address in this process.
49 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
50}
51
Ilya Biryukovafb55542017-05-16 14:40:30 +000052} // namespace
53
54size_t clangd::positionToOffset(StringRef Code, Position P) {
55 size_t Offset = 0;
56 for (int I = 0; I != P.line; ++I) {
57 // FIXME: \r\n
58 // FIXME: UTF-8
59 size_t F = Code.find('\n', Offset);
60 if (F == StringRef::npos)
61 return 0; // FIXME: Is this reasonable?
62 Offset = F + 1;
63 }
64 return (Offset == 0 ? 0 : (Offset - 1)) + P.character;
65}
66
67/// Turn an offset in Code into a [line, column] pair.
68Position clangd::offsetToPosition(StringRef Code, size_t Offset) {
69 StringRef JustBefore = Code.substr(0, Offset);
70 // FIXME: \r\n
71 // FIXME: UTF-8
72 int Lines = JustBefore.count('\n');
73 int Cols = JustBefore.size() - JustBefore.rfind('\n') - 1;
74 return {Lines, Cols};
75}
76
Ilya Biryukov22602992017-05-30 15:11:02 +000077Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +000078RealFileSystemProvider::getTaggedFileSystem(PathRef File) {
Ilya Biryukov22602992017-05-30 15:11:02 +000079 return make_tagged(vfs::getRealFileSystem(), VFSTag());
Ilya Biryukov0f62ed22017-05-26 12:26:51 +000080}
81
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000082unsigned clangd::getDefaultAsyncThreadsCount() {
83 unsigned HardwareConcurrency = std::thread::hardware_concurrency();
84 // C++ standard says that hardware_concurrency()
85 // may return 0, fallback to 1 worker thread in
86 // that case.
87 if (HardwareConcurrency == 0)
88 return 1;
89 return HardwareConcurrency;
90}
91
92ClangdScheduler::ClangdScheduler(unsigned AsyncThreadsCount)
93 : RunSynchronously(AsyncThreadsCount == 0) {
Ilya Biryukov38d79772017-05-16 09:38:59 +000094 if (RunSynchronously) {
95 // Don't start the worker thread if we're running synchronously
96 return;
97 }
98
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +000099 Workers.reserve(AsyncThreadsCount);
100 for (unsigned I = 0; I < AsyncThreadsCount; ++I) {
101 Workers.push_back(std::thread([this]() {
102 while (true) {
103 std::future<void> Request;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000104
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000105 // Pick request from the queue
106 {
107 std::unique_lock<std::mutex> Lock(Mutex);
108 // Wait for more requests.
109 RequestCV.wait(Lock,
110 [this] { return !RequestQueue.empty() || Done; });
111 if (Done)
112 return;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000113
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000114 assert(!RequestQueue.empty() && "RequestQueue was empty");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000115
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000116 // We process requests starting from the front of the queue. Users of
117 // ClangdScheduler have a way to prioritise their requests by putting
118 // them to the either side of the queue (using either addToEnd or
119 // addToFront).
120 Request = std::move(RequestQueue.front());
121 RequestQueue.pop_front();
122 } // unlock Mutex
Ilya Biryukov38d79772017-05-16 09:38:59 +0000123
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000124 Request.get();
125 }
126 }));
127 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000128}
129
130ClangdScheduler::~ClangdScheduler() {
131 if (RunSynchronously)
132 return; // no worker thread is running in that case
133
134 {
135 std::lock_guard<std::mutex> Lock(Mutex);
136 // Wake up the worker thread
137 Done = true;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000138 } // unlock Mutex
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000139 RequestCV.notify_all();
140
141 for (auto &Worker : Workers)
142 Worker.join();
Ilya Biryukov38d79772017-05-16 09:38:59 +0000143}
144
Ilya Biryukov103c9512017-06-13 15:59:43 +0000145ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
146 DiagnosticsConsumer &DiagConsumer,
147 FileSystemProvider &FSProvider,
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000148 unsigned AsyncThreadsCount, bool SnippetCompletions,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000149 clangd::Logger &Logger,
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000150 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukove5128f72017-09-20 07:24:15 +0000151 : Logger(Logger), CDB(CDB), DiagConsumer(DiagConsumer),
152 FSProvider(FSProvider),
Ilya Biryukova46f7a92017-06-28 10:34:50 +0000153 ResourceDir(ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
Ilya Biryukov38d79772017-05-16 09:38:59 +0000154 PCHs(std::make_shared<PCHContainerOperations>()),
Ilya Biryukovf4e95d72017-09-20 19:32:06 +0000155 SnippetCompletions(SnippetCompletions), WorkScheduler(AsyncThreadsCount) {
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000156}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000157
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000158void ClangdServer::setRootPath(PathRef RootPath) {
159 std::string NewRootPath = llvm::sys::path::convert_to_slash(
160 RootPath, llvm::sys::path::Style::posix);
161 if (llvm::sys::fs::is_directory(NewRootPath))
162 this->RootPath = NewRootPath;
163}
164
Ilya Biryukov02d58702017-08-01 15:51:38 +0000165std::future<void> ClangdServer::addDocument(PathRef File, StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000166 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukovf01af682017-05-23 13:42:59 +0000167
Ilya Biryukov02d58702017-08-01 15:51:38 +0000168 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000169 std::shared_ptr<CppFile> Resources = Units.getOrCreateFile(
170 File, ResourceDir, CDB, PCHs, TaggedFS.Value, Logger);
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000171 return scheduleReparseAndDiags(File, VersionedDraft{Version, Contents.str()},
172 std::move(Resources), std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000173}
174
Ilya Biryukov02d58702017-08-01 15:51:38 +0000175std::future<void> ClangdServer::removeDocument(PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000176 DraftMgr.removeDraft(File);
177 std::shared_ptr<CppFile> Resources = Units.removeIfPresent(File);
178 return scheduleCancelRebuild(std::move(Resources));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000179}
180
Ilya Biryukov02d58702017-08-01 15:51:38 +0000181std::future<void> ClangdServer::forceReparse(PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000182 auto FileContents = DraftMgr.getDraft(File);
183 assert(FileContents.Draft &&
184 "forceReparse() was called for non-added document");
185
186 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
187 auto Recreated = Units.recreateFileIfCompileCommandChanged(
Ilya Biryukove5128f72017-09-20 07:24:15 +0000188 File, ResourceDir, CDB, PCHs, TaggedFS.Value, Logger);
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000189
190 // Note that std::future from this cleanup action is ignored.
191 scheduleCancelRebuild(std::move(Recreated.RemovedFile));
192 // Schedule a reparse.
193 return scheduleReparseAndDiags(File, std::move(FileContents),
194 std::move(Recreated.FileInCollection),
195 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000196}
197
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000198Tagged<std::vector<CompletionItem>>
199ClangdServer::codeComplete(PathRef File, Position Pos,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000200 llvm::Optional<StringRef> OverridenContents,
201 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov0e27ce42017-06-13 14:15:56 +0000202 std::string DraftStorage;
203 if (!OverridenContents) {
204 auto FileContents = DraftMgr.getDraft(File);
205 assert(FileContents.Draft &&
206 "codeComplete is called for non-added document");
207
208 DraftStorage = std::move(*FileContents.Draft);
209 OverridenContents = DraftStorage;
210 }
Ilya Biryukov38d79772017-05-16 09:38:59 +0000211
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000212 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000213 if (UsedFS)
214 *UsedFS = TaggedFS.Value;
215
Ilya Biryukov02d58702017-08-01 15:51:38 +0000216 std::shared_ptr<CppFile> Resources = Units.getFile(File);
217 assert(Resources && "Calling completion on non-added file");
218
219 auto Preamble = Resources->getPossiblyStalePreamble();
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000220 std::vector<CompletionItem> Result = clangd::codeComplete(
221 File, Resources->getCompileCommand(),
222 Preamble ? &Preamble->Preamble : nullptr, *OverridenContents, Pos,
Ilya Biryukove5128f72017-09-20 07:24:15 +0000223 TaggedFS.Value, PCHs, SnippetCompletions, Logger);
Ilya Biryukov22602992017-05-30 15:11:02 +0000224 return make_tagged(std::move(Result), TaggedFS.Tag);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000225}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000226
Ilya Biryukovafb55542017-05-16 14:40:30 +0000227std::vector<tooling::Replacement> ClangdServer::formatRange(PathRef File,
228 Range Rng) {
229 std::string Code = getDocument(File);
230
231 size_t Begin = positionToOffset(Code, Rng.start);
232 size_t Len = positionToOffset(Code, Rng.end) - Begin;
233 return formatCode(Code, File, {tooling::Range(Begin, Len)});
234}
235
236std::vector<tooling::Replacement> ClangdServer::formatFile(PathRef File) {
237 // Format everything.
238 std::string Code = getDocument(File);
239 return formatCode(Code, File, {tooling::Range(0, Code.size())});
240}
241
242std::vector<tooling::Replacement> ClangdServer::formatOnType(PathRef File,
243 Position Pos) {
244 // Look for the previous opening brace from the character position and
245 // format starting from there.
246 std::string Code = getDocument(File);
247 size_t CursorPos = positionToOffset(Code, Pos);
248 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
249 if (PreviousLBracePos == StringRef::npos)
250 PreviousLBracePos = CursorPos;
251 size_t Len = 1 + CursorPos - PreviousLBracePos;
252
253 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
254}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000255
256std::string ClangdServer::getDocument(PathRef File) {
257 auto draft = DraftMgr.getDraft(File);
258 assert(draft.Draft && "File is not tracked, cannot get contents");
259 return *draft.Draft;
260}
261
Ilya Biryukovf01af682017-05-23 13:42:59 +0000262std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000263 std::shared_ptr<CppFile> Resources = Units.getFile(File);
264 assert(Resources && "dumpAST is called for non-added document");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000265
Ilya Biryukov02d58702017-08-01 15:51:38 +0000266 std::string Result;
Ilya Biryukov6e1f3b12017-08-01 18:27:58 +0000267 Resources->getAST().get()->runUnderLock([&Result](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000268 llvm::raw_string_ostream ResultOS(Result);
269 if (AST) {
270 clangd::dumpAST(*AST, ResultOS);
271 } else {
272 ResultOS << "<no-ast>";
273 }
274 ResultOS.flush();
Ilya Biryukovf01af682017-05-23 13:42:59 +0000275 });
Ilya Biryukov02d58702017-08-01 15:51:38 +0000276 return Result;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000277}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000278
Ilya Biryukov02d58702017-08-01 15:51:38 +0000279Tagged<std::vector<Location>> ClangdServer::findDefinitions(PathRef File,
280 Position Pos) {
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000281 auto FileContents = DraftMgr.getDraft(File);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000282 assert(FileContents.Draft &&
283 "findDefinitions is called for non-added document");
284
285 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
286
287 std::shared_ptr<CppFile> Resources = Units.getFile(File);
288 assert(Resources && "Calling findDefinitions on non-added file");
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000289
290 std::vector<Location> Result;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000291 Resources->getAST().get()->runUnderLock([Pos, &Result, this](ParsedAST *AST) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000292 if (!AST)
293 return;
Ilya Biryukove5128f72017-09-20 07:24:15 +0000294 Result = clangd::findDefinitions(*AST, Pos, Logger);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000295 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000296 return make_tagged(std::move(Result), TaggedFS.Tag);
297}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000298
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000299llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
300
301 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
302 ".c++", ".m", ".mm"};
303 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
304
305 StringRef PathExt = llvm::sys::path::extension(Path);
306
307 // Lookup in a list of known extensions.
308 auto SourceIter =
309 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
310 [&PathExt](PathRef SourceExt) {
311 return SourceExt.equals_lower(PathExt);
312 });
313 bool IsSource = SourceIter != std::end(SourceExtensions);
314
315 auto HeaderIter =
316 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
317 [&PathExt](PathRef HeaderExt) {
318 return HeaderExt.equals_lower(PathExt);
319 });
320
321 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
322
323 // We can only switch between extensions known extensions.
324 if (!IsSource && !IsHeader)
325 return llvm::None;
326
327 // Array to lookup extensions for the switch. An opposite of where original
328 // extension was found.
329 ArrayRef<StringRef> NewExts;
330 if (IsSource)
331 NewExts = HeaderExtensions;
332 else
333 NewExts = SourceExtensions;
334
335 // Storage for the new path.
336 SmallString<128> NewPath = StringRef(Path);
337
338 // Instance of vfs::FileSystem, used for file existence checks.
339 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
340
341 // Loop through switched extension candidates.
342 for (StringRef NewExt : NewExts) {
343 llvm::sys::path::replace_extension(NewPath, NewExt);
344 if (FS->exists(NewPath))
345 return NewPath.str().str(); // First str() to convert from SmallString to
346 // StringRef, second to convert from StringRef
347 // to std::string
348
349 // Also check NewExt in upper-case, just in case.
350 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
351 if (FS->exists(NewPath))
352 return NewPath.str().str();
353
354 }
355
356 return llvm::None;
357}
358
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000359std::future<void> ClangdServer::scheduleReparseAndDiags(
360 PathRef File, VersionedDraft Contents, std::shared_ptr<CppFile> Resources,
361 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
362
363 assert(Contents.Draft && "Draft must have contents");
364 std::future<llvm::Optional<std::vector<DiagWithFixIts>>> DeferredRebuild =
365 Resources->deferRebuild(*Contents.Draft, TaggedFS.Value);
366 std::promise<void> DonePromise;
367 std::future<void> DoneFuture = DonePromise.get_future();
368
369 DocVersion Version = Contents.Version;
370 Path FileStr = File;
371 VFSTag Tag = TaggedFS.Tag;
372 auto ReparseAndPublishDiags =
373 [this, FileStr, Version,
374 Tag](std::future<llvm::Optional<std::vector<DiagWithFixIts>>>
375 DeferredRebuild,
376 std::promise<void> DonePromise) -> void {
377 FulfillPromiseGuard Guard(DonePromise);
378
379 auto CurrentVersion = DraftMgr.getVersion(FileStr);
380 if (CurrentVersion != Version)
381 return; // This request is outdated
382
383 auto Diags = DeferredRebuild.get();
384 if (!Diags)
385 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000386
387 // We need to serialize access to resulting diagnostics to avoid calling
388 // `onDiagnosticsReady` in the wrong order.
389 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
390 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
391 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
392 // implementation diagnostics will not be reported after version counters'
393 // overflow. This should not happen in practice, since DocVersion is a
394 // 64-bit unsigned integer.
395 if (Version < LastReportedDiagsVersion)
396 return;
397 LastReportedDiagsVersion = Version;
398
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000399 DiagConsumer.onDiagnosticsReady(FileStr,
400 make_tagged(std::move(*Diags), Tag));
401 };
402
403 WorkScheduler.addToFront(std::move(ReparseAndPublishDiags),
404 std::move(DeferredRebuild), std::move(DonePromise));
405 return DoneFuture;
406}
407
408std::future<void>
409ClangdServer::scheduleCancelRebuild(std::shared_ptr<CppFile> Resources) {
410 std::promise<void> DonePromise;
411 std::future<void> DoneFuture = DonePromise.get_future();
412 if (!Resources) {
413 // No need to schedule any cleanup.
414 DonePromise.set_value();
415 return DoneFuture;
416 }
417
418 std::future<void> DeferredCancel = Resources->deferCancelRebuild();
419 auto CancelReparses = [Resources](std::promise<void> DonePromise,
420 std::future<void> DeferredCancel) {
421 FulfillPromiseGuard Guard(DonePromise);
422 DeferredCancel.get();
423 };
424 WorkScheduler.addToFront(std::move(CancelReparses), std::move(DonePromise),
425 std::move(DeferredCancel));
426 return DoneFuture;
427}