blob: 68222dd4ca06b2cde4dc3d32713de373bde4bce4 [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"
Sam McCalla66d2cb2017-12-19 17:06:07 +000011#include "CodeComplete.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000012#include "SourceCode.h"
Sam McCalla66d2cb2017-12-19 17:06:07 +000013#include "XRefs.h"
Sam McCall0faecf02018-01-15 12:33:00 +000014#include "index/Merge.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000015#include "clang/Format/Format.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000016#include "clang/Frontend/CompilerInstance.h"
17#include "clang/Frontend/CompilerInvocation.h"
18#include "clang/Tooling/CompilationDatabase.h"
Ilya Biryukov9e11c4c2017-11-15 18:04:56 +000019#include "clang/Tooling/Refactoring/RefactoringResultConsumer.h"
20#include "clang/Tooling/Refactoring/Rename/RenamingAction.h"
Ilya Biryukovafb55542017-05-16 14:40:30 +000021#include "llvm/ADT/ArrayRef.h"
Sam McCallb5f5eb62018-01-25 17:01:39 +000022#include "llvm/ADT/ScopeExit.h"
Benjamin Krameree19f162017-10-26 12:28:13 +000023#include "llvm/Support/Errc.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000024#include "llvm/Support/FileSystem.h"
Marc-Andre Laperle37de9712017-09-27 15:31:17 +000025#include "llvm/Support/Path.h"
Ilya Biryukovf01af682017-05-23 13:42:59 +000026#include "llvm/Support/raw_ostream.h"
27#include <future>
Ilya Biryukov38d79772017-05-16 09:38:59 +000028
Ilya Biryukov2f314102017-05-16 10:06:20 +000029using namespace clang;
Ilya Biryukov38d79772017-05-16 09:38:59 +000030using namespace clang::clangd;
31
Ilya Biryukovafb55542017-05-16 14:40:30 +000032namespace {
33
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000034// Issues an async read of AST and waits for results.
35template <class Ret, class Func>
36Ret blockingRunWithAST(TUScheduler &S, PathRef File, Func &&F) {
Ilya Biryukov25258702018-01-31 11:26:43 +000037 // Using shared_ptr to workaround MSVC bug. It requires future<> arguments to
38 // have default and copy ctor.
39 auto SharedPtrFunc = [&](llvm::Expected<InputsAndAST> Arg) {
40 return std::make_shared<Ret>(F(std::move(Arg)));
41 };
42 std::packaged_task<std::shared_ptr<Ret>(llvm::Expected<InputsAndAST>)> Task(
43 SharedPtrFunc);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000044 auto Future = Task.get_future();
45 S.runWithAST(File, std::move(Task));
Ilya Biryukov25258702018-01-31 11:26:43 +000046 return std::move(*Future.get());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000047}
48
49// Issues an async read of preamble and waits for results.
50template <class Ret, class Func>
51Ret blockingRunWithPreamble(TUScheduler &S, PathRef File, Func &&F) {
Ilya Biryukov25258702018-01-31 11:26:43 +000052 // Using shared_ptr to workaround MSVC bug. It requires future<> arguments to
53 // have default and copy ctor.
54 auto SharedPtrFunc = [&](llvm::Expected<InputsAndPreamble> Arg) {
55 return std::make_shared<Ret>(F(std::move(Arg)));
56 };
57 std::packaged_task<std::shared_ptr<Ret>(llvm::Expected<InputsAndPreamble>)>
58 Task(SharedPtrFunc);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000059 auto Future = Task.get_future();
60 S.runWithPreamble(File, std::move(Task));
Ilya Biryukov25258702018-01-31 11:26:43 +000061 return std::move(*Future.get());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +000062}
63
64void ignoreError(llvm::Error Err) {
65 handleAllErrors(std::move(Err), [](const llvm::ErrorInfoBase &) {});
66}
67
Ilya Biryukova46f7a92017-06-28 10:34:50 +000068std::string getStandardResourceDir() {
69 static int Dummy; // Just an address in this process.
70 return CompilerInvocation::GetResourcesPath("clangd", (void *)&Dummy);
71}
72
Haojian Wu345099c2017-11-09 11:30:04 +000073class RefactoringResultCollector final
74 : public tooling::RefactoringResultConsumer {
75public:
76 void handleError(llvm::Error Err) override {
77 assert(!Result.hasValue());
78 // FIXME: figure out a way to return better message for DiagnosticError.
79 // clangd uses llvm::toString to convert the Err to string, however, for
80 // DiagnosticError, only "clang diagnostic" will be generated.
81 Result = std::move(Err);
82 }
83
84 // Using the handle(SymbolOccurrences) from parent class.
85 using tooling::RefactoringResultConsumer::handle;
86
87 void handle(tooling::AtomicChanges SourceReplacements) override {
88 assert(!Result.hasValue());
89 Result = std::move(SourceReplacements);
90 }
91
92 Optional<Expected<tooling::AtomicChanges>> Result;
93};
94
Ilya Biryukovafb55542017-05-16 14:40:30 +000095} // namespace
96
Ilya Biryukov22602992017-05-30 15:11:02 +000097Tagged<IntrusiveRefCntPtr<vfs::FileSystem>>
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +000098RealFileSystemProvider::getTaggedFileSystem(PathRef File) {
Ilya Biryukov22602992017-05-30 15:11:02 +000099 return make_tagged(vfs::getRealFileSystem(), VFSTag());
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000100}
101
Sam McCalladccab62017-11-23 16:58:22 +0000102ClangdServer::ClangdServer(GlobalCompilationDatabase &CDB,
103 DiagnosticsConsumer &DiagConsumer,
104 FileSystemProvider &FSProvider,
105 unsigned AsyncThreadsCount,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000106 bool StorePreamblesInMemory,
Haojian Wuba28e9a2018-01-10 14:44:34 +0000107 bool BuildDynamicSymbolIndex, SymbolIndex *StaticIdx,
Sam McCalladccab62017-11-23 16:58:22 +0000108 llvm::Optional<StringRef> ResourceDir)
Ilya Biryukov929697b2018-01-25 14:19:21 +0000109 : CompileArgs(CDB,
110 ResourceDir ? ResourceDir->str() : getStandardResourceDir()),
111 DiagConsumer(DiagConsumer), FSProvider(FSProvider),
Eric Liubfac8f72017-12-19 18:00:37 +0000112 FileIdx(BuildDynamicSymbolIndex ? new FileIndex() : nullptr),
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000113 PCHs(std::make_shared<PCHContainerOperations>()),
114 // Pass a callback into `WorkScheduler` to extract symbols from a newly
115 // parsed file and rebuild the file index synchronously each time an AST
116 // is parsed.
Eric Liubfac8f72017-12-19 18:00:37 +0000117 // FIXME(ioeric): this can be slow and we may be able to index on less
118 // critical paths.
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000119 WorkScheduler(
120 AsyncThreadsCount, StorePreamblesInMemory,
121 FileIdx ? [this](const Context &Ctx, PathRef Path,
122 ParsedAST *AST) { FileIdx->update(Ctx, Path, AST); }
123 : ASTParsedCallback()) {
Sam McCall0faecf02018-01-15 12:33:00 +0000124 if (FileIdx && StaticIdx) {
125 MergedIndex = mergeIndex(FileIdx.get(), StaticIdx);
126 Index = MergedIndex.get();
127 } else if (FileIdx)
128 Index = FileIdx.get();
129 else if (StaticIdx)
130 Index = StaticIdx;
131 else
132 Index = nullptr;
133}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000134
Marc-Andre Laperle37de9712017-09-27 15:31:17 +0000135void ClangdServer::setRootPath(PathRef RootPath) {
136 std::string NewRootPath = llvm::sys::path::convert_to_slash(
137 RootPath, llvm::sys::path::Style::posix);
138 if (llvm::sys::fs::is_directory(NewRootPath))
139 this->RootPath = NewRootPath;
140}
141
Ilya Biryukov940901e2017-12-13 12:51:22 +0000142std::future<Context> ClangdServer::addDocument(Context Ctx, PathRef File,
143 StringRef Contents) {
Ilya Biryukovf01af682017-05-23 13:42:59 +0000144 DocVersion Version = DraftMgr.updateDraft(File, Contents);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000145 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukov940901e2017-12-13 12:51:22 +0000146 return scheduleReparseAndDiags(std::move(Ctx), File,
147 VersionedDraft{Version, Contents.str()},
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000148 std::move(TaggedFS));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000149}
150
Ilya Biryukov940901e2017-12-13 12:51:22 +0000151std::future<Context> ClangdServer::removeDocument(Context Ctx, PathRef File) {
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000152 DraftMgr.removeDraft(File);
Ilya Biryukov929697b2018-01-25 14:19:21 +0000153 CompileArgs.invalidate(File);
154
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000155 std::promise<Context> DonePromise;
156 std::future<Context> DoneFuture = DonePromise.get_future();
157
158 auto Callback = BindWithForward(
159 [](Context Ctx, std::promise<Context> DonePromise, llvm::Error Err) {
160 if (Err)
161 ignoreError(std::move(Err));
162 DonePromise.set_value(std::move(Ctx));
163 },
164 std::move(Ctx), std::move(DonePromise));
165
166 WorkScheduler.remove(File, std::move(Callback));
167 return DoneFuture;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000168}
169
Ilya Biryukov940901e2017-12-13 12:51:22 +0000170std::future<Context> ClangdServer::forceReparse(Context Ctx, PathRef File) {
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000171 auto FileContents = DraftMgr.getDraft(File);
172 assert(FileContents.Draft &&
173 "forceReparse() was called for non-added document");
174
Ilya Biryukov929697b2018-01-25 14:19:21 +0000175 // forceReparse promises to request new compilation flags from CDB, so we
176 // remove any cahced flags.
177 CompileArgs.invalidate(File);
178
Ilya Biryukov91dbf5b2017-08-14 08:37:32 +0000179 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000180 return scheduleReparseAndDiags(std::move(Ctx), File, std::move(FileContents),
181 std::move(TaggedFS));
Ilya Biryukov0f62ed22017-05-26 12:26:51 +0000182}
183
Ilya Biryukov940901e2017-12-13 12:51:22 +0000184std::future<std::pair<Context, Tagged<CompletionList>>>
185ClangdServer::codeComplete(Context Ctx, PathRef File, Position Pos,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000186 const clangd::CodeCompleteOptions &Opts,
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000187 llvm::Optional<StringRef> OverridenContents,
188 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000189 using ResultType = std::pair<Context, Tagged<CompletionList>>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000190
191 std::promise<ResultType> ResultPromise;
192
Ilya Biryukov940901e2017-12-13 12:51:22 +0000193 auto Callback = [](std::promise<ResultType> ResultPromise, Context Ctx,
194 Tagged<CompletionList> Result) -> void {
195 ResultPromise.set_value({std::move(Ctx), std::move(Result)});
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000196 };
197
198 std::future<ResultType> ResultFuture = ResultPromise.get_future();
Ilya Biryukov940901e2017-12-13 12:51:22 +0000199 codeComplete(std::move(Ctx), File, Pos, Opts,
200 BindWithForward(Callback, std::move(ResultPromise)),
201 OverridenContents, UsedFS);
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000202 return ResultFuture;
203}
204
205void ClangdServer::codeComplete(
Ilya Biryukov940901e2017-12-13 12:51:22 +0000206 Context Ctx, PathRef File, Position Pos,
207 const clangd::CodeCompleteOptions &Opts,
208 UniqueFunction<void(Context, Tagged<CompletionList>)> Callback,
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000209 llvm::Optional<StringRef> OverridenContents,
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000210 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukov940901e2017-12-13 12:51:22 +0000211 using CallbackType = UniqueFunction<void(Context, Tagged<CompletionList>)>;
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000212
Ilya Biryukovaf0c04b2017-06-14 09:46:44 +0000213 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
Ilya Biryukoved99e4c2017-07-31 17:09:29 +0000214 if (UsedFS)
215 *UsedFS = TaggedFS.Value;
216
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000217 // Copy completion options for passing them to async task handler.
218 auto CodeCompleteOpts = Opts;
Sam McCall0faecf02018-01-15 12:33:00 +0000219 if (!CodeCompleteOpts.Index) // Respect overridden index.
220 CodeCompleteOpts.Index = Index;
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000221
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000222 std::string Contents;
223 if (OverridenContents) {
224 Contents = OverridenContents->str();
225 } else {
226 VersionedDraft Latest = DraftMgr.getDraft(File);
227 assert(Latest.Draft && "codeComplete called for non-added document");
228 Contents = *Latest.Draft;
229 }
230
Ilya Biryukovf6e2b4c2018-01-09 14:39:27 +0000231 // Copy PCHs to avoid accessing this->PCHs concurrently
232 std::shared_ptr<PCHContainerOperations> PCHs = this->PCHs;
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000233 auto Task = [PCHs, Pos, TaggedFS, CodeCompleteOpts](
234 Context Ctx, std::string Contents, Path File,
235 CallbackType Callback, llvm::Expected<InputsAndPreamble> IP) {
236 assert(IP && "error when trying to read preamble for codeComplete");
237 auto PreambleData = IP->Preamble;
238 auto &Command = IP->Inputs.CompileCommand;
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000239
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000240 // FIXME(ibiryukov): even if Preamble is non-null, we may want to check
241 // both the old and the new version in case only one of them matches.
242 CompletionList Result = clangd::codeComplete(
243 Ctx, File, Command, PreambleData ? &PreambleData->Preamble : nullptr,
244 Contents, Pos, TaggedFS.Value, PCHs, CodeCompleteOpts);
Ilya Biryukov90bbcfd2017-10-25 09:35:10 +0000245
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000246 Callback(std::move(Ctx),
247 make_tagged(std::move(Result), std::move(TaggedFS.Tag)));
248 };
249
250 WorkScheduler.runWithPreamble(
251 File, BindWithForward(Task, std::move(Ctx), std::move(Contents),
252 File.str(), std::move(Callback)));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000253}
Ilya Biryukovf01af682017-05-23 13:42:59 +0000254
Benjamin Krameree19f162017-10-26 12:28:13 +0000255llvm::Expected<Tagged<SignatureHelp>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000256ClangdServer::signatureHelp(const Context &Ctx, PathRef File, Position Pos,
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000257 llvm::Optional<StringRef> OverridenContents,
258 IntrusiveRefCntPtr<vfs::FileSystem> *UsedFS) {
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000259 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
260 if (UsedFS)
261 *UsedFS = TaggedFS.Value;
262
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000263 std::string Contents;
264 if (OverridenContents) {
265 Contents = OverridenContents->str();
266 } else {
267 VersionedDraft Latest = DraftMgr.getDraft(File);
268 if (!Latest.Draft)
269 return llvm::make_error<llvm::StringError>(
270 "signatureHelp is called for non-added document",
271 llvm::errc::invalid_argument);
272 Contents = std::move(*Latest.Draft);
273 }
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000274
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000275 auto Action = [=, &Ctx](llvm::Expected<InputsAndPreamble> IP)
276 -> Expected<Tagged<SignatureHelp>> {
277 if (!IP)
278 return IP.takeError();
279 auto PreambleData = IP->Preamble;
280 auto &Command = IP->Inputs.CompileCommand;
281
282 return make_tagged(
283 clangd::signatureHelp(Ctx, File, Command,
284 PreambleData ? &PreambleData->Preamble : nullptr,
285 Contents, Pos, TaggedFS.Value, PCHs),
286 TaggedFS.Tag);
287 };
288 return blockingRunWithPreamble<Expected<Tagged<SignatureHelp>>>(WorkScheduler,
289 File, Action);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000290}
291
Raoul Wols212bcf82017-12-12 20:25:06 +0000292llvm::Expected<tooling::Replacements>
293ClangdServer::formatRange(StringRef Code, PathRef File, Range Rng) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000294 size_t Begin = positionToOffset(Code, Rng.start);
295 size_t Len = positionToOffset(Code, Rng.end) - Begin;
296 return formatCode(Code, File, {tooling::Range(Begin, Len)});
297}
298
Raoul Wols212bcf82017-12-12 20:25:06 +0000299llvm::Expected<tooling::Replacements> ClangdServer::formatFile(StringRef Code,
300 PathRef File) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000301 // Format everything.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000302 return formatCode(Code, File, {tooling::Range(0, Code.size())});
303}
304
Raoul Wols212bcf82017-12-12 20:25:06 +0000305llvm::Expected<tooling::Replacements>
306ClangdServer::formatOnType(StringRef Code, PathRef File, Position Pos) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000307 // Look for the previous opening brace from the character position and
308 // format starting from there.
Ilya Biryukovafb55542017-05-16 14:40:30 +0000309 size_t CursorPos = positionToOffset(Code, Pos);
310 size_t PreviousLBracePos = StringRef(Code).find_last_of('{', CursorPos);
311 if (PreviousLBracePos == StringRef::npos)
312 PreviousLBracePos = CursorPos;
Sam McCallb536a2a2017-12-19 12:23:48 +0000313 size_t Len = CursorPos - PreviousLBracePos;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000314
315 return formatCode(Code, File, {tooling::Range(PreviousLBracePos, Len)});
316}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000317
Haojian Wu345099c2017-11-09 11:30:04 +0000318Expected<std::vector<tooling::Replacement>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000319ClangdServer::rename(const Context &Ctx, PathRef File, Position Pos,
320 llvm::StringRef NewName) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000321 using RetType = Expected<std::vector<tooling::Replacement>>;
322 auto Action = [=](Expected<InputsAndAST> InpAST) -> RetType {
323 if (!InpAST)
324 return InpAST.takeError();
325 auto &AST = InpAST->AST;
326
327 RefactoringResultCollector ResultCollector;
328 const SourceManager &SourceMgr = AST.getASTContext().getSourceManager();
Haojian Wu345099c2017-11-09 11:30:04 +0000329 const FileEntry *FE =
330 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
331 if (!FE)
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000332 return llvm::make_error<llvm::StringError>(
333 "rename called for non-added document", llvm::errc::invalid_argument);
Haojian Wu345099c2017-11-09 11:30:04 +0000334 SourceLocation SourceLocationBeg =
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000335 clangd::getBeginningOfIdentifier(AST, Pos, FE);
Haojian Wu345099c2017-11-09 11:30:04 +0000336 tooling::RefactoringRuleContext Context(
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000337 AST.getASTContext().getSourceManager());
338 Context.setASTContext(AST.getASTContext());
Haojian Wu345099c2017-11-09 11:30:04 +0000339 auto Rename = clang::tooling::RenameOccurrences::initiate(
340 Context, SourceRange(SourceLocationBeg), NewName.str());
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000341 if (!Rename)
342 return Rename.takeError();
Haojian Wu345099c2017-11-09 11:30:04 +0000343
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000344 Rename->invoke(ResultCollector, Context);
345
346 assert(ResultCollector.Result.hasValue());
347 if (!ResultCollector.Result.getValue())
348 return ResultCollector.Result->takeError();
349
350 std::vector<tooling::Replacement> Replacements;
351 for (const tooling::AtomicChange &Change : ResultCollector.Result->get()) {
352 tooling::Replacements ChangeReps = Change.getReplacements();
353 for (const auto &Rep : ChangeReps) {
354 // FIXME: Right now we only support renaming the main file, so we
355 // drop replacements not for the main file. In the future, we might
356 // consider to support:
357 // * rename in any included header
358 // * rename only in the "main" header
359 // * provide an error if there are symbols we won't rename (e.g.
360 // std::vector)
361 // * rename globally in project
362 // * rename in open files
363 if (Rep.getFilePath() == File)
364 Replacements.push_back(Rep);
365 }
Haojian Wu345099c2017-11-09 11:30:04 +0000366 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000367 return Replacements;
368 };
369 return blockingRunWithAST<RetType>(WorkScheduler, File, std::move(Action));
Haojian Wu345099c2017-11-09 11:30:04 +0000370}
371
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000372llvm::Optional<std::string> ClangdServer::getDocument(PathRef File) {
373 auto Latest = DraftMgr.getDraft(File);
374 if (!Latest.Draft)
375 return llvm::None;
376 return std::move(*Latest.Draft);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000377}
378
Ilya Biryukovf01af682017-05-23 13:42:59 +0000379std::string ClangdServer::dumpAST(PathRef File) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000380 auto Action = [](llvm::Expected<InputsAndAST> InpAST) -> std::string {
381 if (!InpAST) {
382 ignoreError(InpAST.takeError());
383 return "<no-ast>";
Ilya Biryukov02d58702017-08-01 15:51:38 +0000384 }
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000385
386 std::string Result;
387
388 llvm::raw_string_ostream ResultOS(Result);
389 clangd::dumpAST(InpAST->AST, ResultOS);
Ilya Biryukov02d58702017-08-01 15:51:38 +0000390 ResultOS.flush();
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000391
392 return Result;
393 };
394 return blockingRunWithAST<std::string>(WorkScheduler, File,
395 std::move(Action));
Ilya Biryukov38d79772017-05-16 09:38:59 +0000396}
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000397
Benjamin Krameree19f162017-10-26 12:28:13 +0000398llvm::Expected<Tagged<std::vector<Location>>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000399ClangdServer::findDefinitions(const Context &Ctx, PathRef File, Position Pos) {
Ilya Biryukov02d58702017-08-01 15:51:38 +0000400 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
401
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000402 using RetType = llvm::Expected<Tagged<std::vector<Location>>>;
403 auto Action = [=, &Ctx](llvm::Expected<InputsAndAST> InpAST) -> RetType {
404 if (!InpAST)
405 return InpAST.takeError();
406 auto Result = clangd::findDefinitions(Ctx, InpAST->AST, Pos);
407 return make_tagged(std::move(Result), TaggedFS.Tag);
408 };
409 return blockingRunWithAST<RetType>(WorkScheduler, File, Action);
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000410}
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000411
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000412llvm::Optional<Path> ClangdServer::switchSourceHeader(PathRef Path) {
413
414 StringRef SourceExtensions[] = {".cpp", ".c", ".cc", ".cxx",
415 ".c++", ".m", ".mm"};
416 StringRef HeaderExtensions[] = {".h", ".hh", ".hpp", ".hxx", ".inc"};
417
418 StringRef PathExt = llvm::sys::path::extension(Path);
419
420 // Lookup in a list of known extensions.
421 auto SourceIter =
422 std::find_if(std::begin(SourceExtensions), std::end(SourceExtensions),
423 [&PathExt](PathRef SourceExt) {
424 return SourceExt.equals_lower(PathExt);
425 });
426 bool IsSource = SourceIter != std::end(SourceExtensions);
427
428 auto HeaderIter =
429 std::find_if(std::begin(HeaderExtensions), std::end(HeaderExtensions),
430 [&PathExt](PathRef HeaderExt) {
431 return HeaderExt.equals_lower(PathExt);
432 });
433
434 bool IsHeader = HeaderIter != std::end(HeaderExtensions);
435
436 // We can only switch between extensions known extensions.
437 if (!IsSource && !IsHeader)
438 return llvm::None;
439
440 // Array to lookup extensions for the switch. An opposite of where original
441 // extension was found.
442 ArrayRef<StringRef> NewExts;
443 if (IsSource)
444 NewExts = HeaderExtensions;
445 else
446 NewExts = SourceExtensions;
447
448 // Storage for the new path.
449 SmallString<128> NewPath = StringRef(Path);
450
451 // Instance of vfs::FileSystem, used for file existence checks.
452 auto FS = FSProvider.getTaggedFileSystem(Path).Value;
453
454 // Loop through switched extension candidates.
455 for (StringRef NewExt : NewExts) {
456 llvm::sys::path::replace_extension(NewPath, NewExt);
457 if (FS->exists(NewPath))
458 return NewPath.str().str(); // First str() to convert from SmallString to
459 // StringRef, second to convert from StringRef
460 // to std::string
Ilya Biryukov33334942017-10-06 14:39:39 +0000461
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000462 // Also check NewExt in upper-case, just in case.
463 llvm::sys::path::replace_extension(NewPath, NewExt.upper());
464 if (FS->exists(NewPath))
465 return NewPath.str().str();
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000466 }
467
468 return llvm::None;
469}
470
Raoul Wols212bcf82017-12-12 20:25:06 +0000471llvm::Expected<tooling::Replacements>
472ClangdServer::formatCode(llvm::StringRef Code, PathRef File,
473 ArrayRef<tooling::Range> Ranges) {
474 // Call clang-format.
475 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
476 auto StyleOrError =
477 format::getStyle("file", File, "LLVM", Code, TaggedFS.Value.get());
478 if (!StyleOrError) {
479 return StyleOrError.takeError();
480 } else {
481 return format::reformat(StyleOrError.get(), Code, Ranges, File);
482 }
483}
484
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000485llvm::Expected<Tagged<std::vector<DocumentHighlight>>>
Ilya Biryukov940901e2017-12-13 12:51:22 +0000486ClangdServer::findDocumentHighlights(const Context &Ctx, PathRef File,
487 Position Pos) {
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000488 auto FileContents = DraftMgr.getDraft(File);
489 if (!FileContents.Draft)
490 return llvm::make_error<llvm::StringError>(
491 "findDocumentHighlights called on non-added file",
492 llvm::errc::invalid_argument);
493
494 auto TaggedFS = FSProvider.getTaggedFileSystem(File);
495
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000496 using RetType = llvm::Expected<Tagged<std::vector<DocumentHighlight>>>;
497 auto Action = [=, &Ctx](llvm::Expected<InputsAndAST> InpAST) -> RetType {
498 if (!InpAST)
499 return InpAST.takeError();
500 auto Result = clangd::findDocumentHighlights(Ctx, InpAST->AST, Pos);
501 return make_tagged(std::move(Result), TaggedFS.Tag);
502 };
503 return blockingRunWithAST<RetType>(WorkScheduler, File, Action);
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000504}
505
Ilya Biryukov940901e2017-12-13 12:51:22 +0000506std::future<Context> ClangdServer::scheduleReparseAndDiags(
507 Context Ctx, PathRef File, VersionedDraft Contents,
Ilya Biryukov929697b2018-01-25 14:19:21 +0000508 Tagged<IntrusiveRefCntPtr<vfs::FileSystem>> TaggedFS) {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000509 tooling::CompileCommand Command = CompileArgs.getCompileCommand(File);
Ilya Biryukov929697b2018-01-25 14:19:21 +0000510
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000511 using OptDiags = llvm::Optional<std::vector<DiagWithFixIts>>;
512
513 DocVersion Version = Contents.Version;
514 Path FileStr = File.str();
515 VFSTag Tag = std::move(TaggedFS.Tag);
516
Ilya Biryukov940901e2017-12-13 12:51:22 +0000517 std::promise<Context> DonePromise;
518 std::future<Context> DoneFuture = DonePromise.get_future();
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000519
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000520 auto Callback = [this, Version, FileStr,
521 Tag](std::promise<Context> DonePromise, Context Ctx,
522 OptDiags Diags) {
Sam McCallb5f5eb62018-01-25 17:01:39 +0000523 auto Guard =
524 llvm::make_scope_exit([&]() { DonePromise.set_value(std::move(Ctx)); });
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000525 if (!Diags)
526 return; // A new reparse was requested before this one completed.
Ilya Biryukov47f22022017-09-20 12:58:55 +0000527
528 // We need to serialize access to resulting diagnostics to avoid calling
529 // `onDiagnosticsReady` in the wrong order.
530 std::lock_guard<std::mutex> DiagsLock(DiagnosticsMutex);
531 DocVersion &LastReportedDiagsVersion = ReportedDiagnosticVersions[FileStr];
532 // FIXME(ibiryukov): get rid of '<' comparison here. In the current
533 // implementation diagnostics will not be reported after version counters'
534 // overflow. This should not happen in practice, since DocVersion is a
535 // 64-bit unsigned integer.
536 if (Version < LastReportedDiagsVersion)
537 return;
538 LastReportedDiagsVersion = Version;
539
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000540 DiagConsumer.onDiagnosticsReady(
541 Ctx, FileStr, make_tagged(std::move(*Diags), std::move(Tag)));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000542 };
543
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000544 WorkScheduler.update(std::move(Ctx), File,
545 ParseInputs{std::move(Command),
546 std::move(TaggedFS.Value),
547 std::move(*Contents.Draft)},
548 BindWithForward(Callback, std::move(DonePromise)));
Ilya Biryukovc5ad35f2017-08-14 08:17:24 +0000549 return DoneFuture;
550}
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000551
552void ClangdServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
553 // FIXME: Do nothing for now. This will be used for indexing and potentially
554 // invalidating other caches.
555}
Ilya Biryukovdf842342018-01-25 14:32:21 +0000556
557std::vector<std::pair<Path, std::size_t>>
558ClangdServer::getUsedBytesPerFile() const {
Ilya Biryukov75f1dd92018-01-31 08:51:16 +0000559 return WorkScheduler.getUsedBytesPerFile();
Ilya Biryukovdf842342018-01-25 14:32:21 +0000560}